Suppose I have the following class:
public class GenericClass<T>
{
public T Find()
{
//return T if found otherwise null or Nullable<T>
}
}
Somewhere I’d like to specialize my class using T with a class, other times with a struct.
I’m facing this issue: I can’t return a Nullable<T> if T type isn’t restricted to be a struct.
I would like to provide an implementation of my Find method that works if T is specialized with both a class or a struct.
In case Find fails , I’d like to return null if T is a class otherwise Nullable<T>.
Is that possible without using reflection? If yes how?
You can return
default(T).For a class, this will be
null. For anyNullable<T>, this will be aNullable<T>without a value (effectivelynull).That being said, if you use this with a
structand not aNullable<T>as the type,default(T)will be the default value of the struct.If you want to make this work uniformly for any class or struct, you would likely need to return two values – you could use the framework as inspiration here, and have a TryXXX method, ie:
You could then use
default(T)when the value isn’t found, and return false. This avoids the need for nullable types. You could also write this returning aTuple<bool, T>or similar, if you wanted to avoid the out parameter, ie:A final option, potentially, would be to make your class non-generic, then use a pair of generic methods:
Note that you need distinct names, since you can’t have an overloaded method purely based on the return type.