nitecow
asked on
C# Generics - Single Function to pass in a type double and string and have it return a null
I have 2 functions below where I've removed the meat of the work in this equation for simplicity. The 'meat' is the same for both functions. I want a single function that I can use for both nullable and non-nullable types. If thats not possible then at least 1 function that will contain the actual logic and one function just calls another but for some reason I can't get it going. The answer most likely will be in the T declaration or the constraints. Just can't get it to do exactly what I want.
The FindEntryNull function is used where the objects can be null (string for example) where the FindEntry is used where the type can't be null (double for example).
Any help is appreciated.
The FindEntryNull function is used where the objects can be null (string for example) where the FindEntry is used where the type can't be null (double for example).
Any help is appreciated.
public Nullable<T> FindEntry<T>(string key, object OneBasedIndex, Nullable<DateTime> asOfDate) where T : struct, IConvertible
{
string item = FindEntry<string>(key);
if (null == item)
return null;
return (T)Convert.ChangeType(item, typeof(T));
}
public T FindEntryNull<T>(string key, object OneBasedIndex, Nullable<DateTime> asOfDate) where T : class, IConvertible
{
string item = FindEntry<string>(key);
if (null == item)
return null;
return (T)Convert.ChangeType(item, typeof(T));
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I would think that Nullable<yourtype> would be part of thet type in the first place. You could just pass Nullable<int> as the parameter to your template when you use it, then you woudlnt need two different templates at all because you could call myTemplate<Nullable<Type>> or myTemplate<Type> depending on if you wanted it to be nullable (you can pass templated types as parameters into templates).