I want a typed lookup helper function for a heterogenous collection: It should return a struct or class, else null if the item is not found.
Below is an example using a trivial collection lookup, but it could be a database call or whatever.
Is there any way to achieve this with a single method signature?
public T GetClass<T>(string key) where T : class
{
object o;
if (Contents.TryGetValue(key, out o))
{
return o as T;
}
return null;
}
public T? GetStruct<T>(string key) where T : struct
{
object o;
if (Contents.TryGetValue(key, out o))
{
if (o is T)
{
return (T?) o;
}
}
return null;
}
What I’ve already tried:
- I understand that generic restrictions can’t be used to disambiguate overloads. So I can’t simply give these two methods the same name.
- Returning
(Default) Tisn’t an option, since 0 is a valid int value. - I have tried calling with
<int ?>as the type, but as discussed,Nullable<T>isn’t a reference type.
Is there some way to indicate that I’m going to return a boxed int?
The following method works for both classes and nullable structures:
Usage:
Notice how the
?is part of generic type argument and not defined by the method on the return type.