Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic methods and optional arguments

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;
    }            
}
like image 863
hardsky Avatar asked Mar 27 '12 13:03

hardsky


People also ask

What is a generic argument?

Generic arguments, or arguments applied to an entire class or group of opposing arguments, occur frequently in academic debate. Many generic argument positions endure across debate resolutions.

What is optional argument in C#?

Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.

How do I make my generic optional?

To make a generic type optional, you have to assign the void as the default value. In the example below, even though the function takes a generic type T, still you can call this function without passing the generic type and it takes void as default.

Are optional arguments bad?

The thing with optional parameters is, they are BAD because they are unintuitive - meaning they do NOT behave the way you would expect it.


2 Answers

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

like image 194
Dave S Avatar answered Sep 16 '22 11:09

Dave S


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))
like image 32
Bas Avatar answered Sep 18 '22 11:09

Bas