You can return default(T) .
For the class, this will be null . For any Nullable<T> it will be Nullable<T> without a value (effectively null ).
If you use this with a struct rather than Nullable<T> as a type, default(T) will be the default value for the structure.
If you want to make this work evenly for any class or structure, you will most likely need to return two values ββ- you could use the framework as inspiration here and have a TryXXX method, that is:
public bool TryFind(out T)
Then you can use default(T) when the value is not found, and return false. This avoids null types. You can also write this return Tuple<bool, T> or the like if you want to avoid the out parameter, i.e.:
public Tuple<bool, T> Find()
The last option, potentially, was to make your class not shared, and then use a couple of common methods:
class YourClass // Non generic { public T FindReference<T>() where T : class { // ... return null; } public Nullable<T> FindValue<T>() where T : struct { // ... return default(T); } }
Note that you need different names, since you cannot overload a method based only on the return type.
Reed copsey
source share