Generic methods and optional arguments
-
27-05-2021 - |
Question
Is it possible to write similar construction?
I want to set, somehow, default value for argument of type T.
private T GetNumericVal<T>(string sColName, T defVal = 0)
{
string sVal = GetStrVal(sColName);
T nRes;
if (!T.TryParse(sVal, out nRes))
return defVal;
return nRes;
}
Additionally, I found following link:
Generic type conversion FROM string
I think, this code must work
private T GetNumericVal<T>(string sColName, T defVal = default(T)) where T : IConvertible
{
string sVal = GetStrVal(sColName);
try
{
return (T)Convert.ChangeType(sVal, typeof(T));
}
catch (FormatException)
{
return defVal;
}
}
Solution
I haven't tried this but change T defVal = 0
to T defVal = default(T)
OTHER TIPS
If you know that T will have a parameterless constructor you can use new T() as such:
private T GetNumericVal<T>(string sColName, T defVal = new T()) where T : new()
Otherwise you can use default(T)
private T GetNumericVal<T>(string sColName, T defVal = default(T))
To answer the question that would work to set the default value
private T GetNumericVal<T>(string sColName, T defVal = default(T))
{
string sVal = GetStrVal(sColName);
T nRes;
if (!T.TryParse(sVal, out nRes))
return defVal;
return nRes;
}
But you cannot call the static TryParse method since the compiler has no way to know type T declares this static method.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow