14

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;
    }            
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
hardsky
  • 514
  • 5
  • 15

3 Answers3

19

I haven't tried this but change T defVal = 0 to T defVal = default(T)

Dave S
  • 775
  • 5
  • 7
5

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))
Bas
  • 26,772
  • 8
  • 53
  • 86
4

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.

Jf Beaulac
  • 5,206
  • 1
  • 25
  • 46
  • Yes, I cant call TryParse. But maybe something similar? Maybe add some constraint to type parameter (I mean 'where: ...')? If numeric types implement some converting interface. – hardsky Mar 27 '12 at 13:47
  • the CLR has no concept of "virtual static methods", the compiler cannot infer static methods from a type. As far as I know there is no clean solution for that. – Jf Beaulac Mar 27 '12 at 14:11
  • http://stackoverflow.com/questions/196661/calling-a-static-method-on-a-generic-type-parameter for more details – Jf Beaulac Mar 27 '12 at 14:12