Generic methods and optional arguments
Asked Answered
S

3

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;
    }            
}
Supposititious answered 27/3, 2012 at 13:25 Comment(0)
H
19

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

Heedless answered 27/3, 2012 at 13:28 Comment(0)
P
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))
Petasus answered 27/3, 2012 at 13:29 Comment(0)
C
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.

Celadon answered 27/3, 2012 at 13:33 Comment(3)
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.Supposititious
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.Celadon
#197161 for more detailsCeladon

© 2022 - 2024 — McMap. All rights reserved.