C # Returning zero in the appropriate input type

I need a function that does this:

    private static dynamic Zero(Type T)
    {
        if (T == typeof(Decimal))
        {
            return Decimal.Zero;
        }
        else if (T == typeof(Double))
        {
            return new Double();
        }
        else if (T == typeof(Int64))
        {
            return new Int64();
        }
        ...
    }

But for all types. I would like you not to write an expression about the giant. Is there any other way to do this? I am using C # 4.0.

+3
source share
3 answers

The default constructor will be used for the value type.

if(T.IsValueType()) return Activator.CreateInstance(T);

Then you can do other things, for example, testing the Zero method by type and, if so, calling it.

+2
source
return default(T);
+5
source

No need dynamichere:

private static T Zero<T>()
{
    return default(T);
}
+1
source

Source: https://habr.com/ru/post/1729005/


All Articles