I'm trying to write the following method using generics. (My actual method is more complex than this.)
public T ParseDictionaryItem<T>(string s, Dictionary<string, T> dictionary)
{
T result;
if (dictionary.TryGetValue(s, out result))
return result;
// TODO: Return special value such as null to indicate invalid item
}
My goal is to return something like null
if the item is not in the dictionary.
The problem is that I don't know what type T
is. If T
was an integer, for example, then I should return the type T?
. However, if T
is a class, then it is already nullable. And I won't know this until run time.
Can anyone see a clean way to return a special value in this method to indicate the item is invalid? I'm open to returning something other than null
, but it has to be a special value. (0 is not a special value for integers.)
I would suggest returning a ParseResult<T>
, which is defined as something like:
public struct ParseResult<T>
{
// Or an exception, or a way of creating an exception
private readonly bool success;
private readonly T value;
// Accessors etc
}
That way you don't have to worry about nullability, and you can make it very clear what you're doing. This is the pattern I've used in Noda Time and to my mind it's worked very well. (Currently we use a class rather than a struct, but I might change that...)
I prefer it to other approaches because:
out
parameterT
is a reference type or a value typenull
is a successful parse valuePerhaps two overloads would help:
public T? ParseStructDictionaryItem<T>(string s, Dictionary<string, T> dictionary) where T : struct
{
T result;
if (dictionary.TryGetValue(s, out result))
return result;
return null;
}
public T ParseReferenceDictionaryItem<T>(string s, Dictionary<string, T> dictionary) where T : class
{
T result;
if (dictionary.TryGetValue(s, out result))
return result;
return default(T);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With