Home > other >  Treat null as 0 for generic types
Treat null as 0 for generic types

Time:05-11

Want to convert generic typed null values to "0." I wrote the following to try to temporary convert back and forth after setting, but get an exception when value is null...

IEvaluateService Create<T>(
            string compareOperator,
            T value,
            ...)
{
    value ??= (T)Convert.ChangeType("0", typeof(T));
}

Exception: System.InvalidCastException: Invalid cast from 'System.String' to 'System.Nullable1[[System.Int32,`

CodePudding user response:

I'm guessing you are after the default literal

value = default;

That will convert to null for reference types, or whatever the default value is for value types. I.e. 0 for numeric types and false for booleans.

But combining it with the null-coalescing assignment operator probably makes little sense since a value type cannot be null, so assigning the default value would never happen for value types, and default would be null for reference types, so it seem to always be a no-op. So you should probably think about what it is you are actually trying to accomplish.

If you want to represent non existing values in generic methods I would suggest a Maybe/Option type.

CodePudding user response:

Maybe you can do:

            T value,
//...
{
    var u = Nullable.GetUnderlyingType(typeof(T));
    if (u != null)
    {
        value ??= (T)Convert.ChangeType(0, u);
    }
}

I write 0, not "0".

  • Related