Is it possible in a C# generic method to return either an object type or a Nullable type?
For instance, if I have a safe index accessor for a List and I want to return a value that I can check later with either == null or .HasValue().
I currently have the following two methods:
static T? SafeGet<T>(List<T> list, int index) where T : struct
{
if (list == null || index < 0 || index >= list.Count)
{
return null;
}
return list[index];
}
static T SafeGetObj<T>(List<T> list, int index) where T : class
{
if (list == null || index < 0 || index >= list.Count)
{
return null;
}
return list[index];
}
If I try to combine the methods into a single method.
static T SafeGetTest<T>(List<T> list, int index)
{
if (list == null || index < 0 || index >= list.Count)
{
return null;
}
return list[index];
}
I get a compile error:
Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead.
But I don't want to use default(T) because in the case of primitives, 0, which is the default for an int, is a possible real value that I need to distinguish from a not available value.
Is it possible for these methods be combined into a single method?
(For the record I am using .NET 3.0 and while I interested in what more modern C# can do I will personally only be able to use answers that work in 3.0)
Tis anint,T?would not be convertible toT. Even your first method, even though it compiles, has issues, if you tried writing something likeint i = SafeGet<int>(myIntList, 0), you would get an error "Cannot implicitly convert type 'int?' to 'int'...". Maybe in your test you are using thevarkeyword, which infersint?instead ofint...varfor type inference.Countchecks everywhere I wanted to encapsulate my checks in a single method. Ideally I'd be able to useNullableto wrap reference types as well as value types (much like Option Types) but that doesn't seem to be an option in C#.vardoesn't change anything - if the return type isint(because that's whatTis) the compiler will infer that type, and you can't return anint?.