Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion between Nullable types

Tags:

c#

.net

nullable

Is there a converter in .NET 4.0 that supports conversions between nullable types to shorten instructions like:

bool? nullableBool = GetSomething();
byte? nbyte = nullableBool.HasValue ? (byte?)Convert.ToByte(nullableBool.Value) : null;
like image 295
Maciej Wozniak Avatar asked Mar 30 '11 14:03

Maciej Wozniak


People also ask

How do you fix converting null literal or possible null value to non-nullable type?

Cannot convert null literal to non-nullable reference type. Fortunately, there is a solution to this warning – all you do is add the Elvis operator after the variable 'text' and the warning goes away.

What happens when we box or unbox nullable types?

Boxing a value of a nullable-type produces a null reference if it is the null value (HasValue is false), or the result of unwrapping and boxing the underlying value otherwise. will output the string “Box contains an int” on the console.

How do you change a nullable to a non-nullable in Dart?

If you're sure that an expression with a nullable type isn't null, you can use a null assertion operator ( ! ) to make Dart treat it as non-nullable. By adding ! just after the expression, you tell Dart that the value won't be null, and that it's safe to assign it to a non-nullable variable.


2 Answers

I would write an extension method:

public static class Extensions
{
    public static TDest? ConvertTo<TSource, TDest>(this TSource? source) 
        where TDest: struct 
        where TSource: struct
    {
        if (source == null)
        {
            return null;
        }
        return (TDest)Convert.ChangeType(source.Value, typeof(TDest));
    }
}

and then:

bool? nullableBool = true;
byte? nbyte = nullableBool.ConvertTo<bool, byte>();
like image 71
Darin Dimitrov Avatar answered Oct 17 '22 13:10

Darin Dimitrov


Not that I am aware of.
You could just write a helper method like this:

public Nullable<TTarget> NullableConvert<TSource, TTarget>(
          Nullable<TSource> source, Func<TSource, TTarget> converter)
    where TTarget: struct
    where TSource: struct
{
    return source.HasValue ? 
               (Nullable<TTarget>)converter(source.Value) : 
               null;
}

Call it like this:

byte? nbyte = NullableConvert(nullableBool, Convert.ToByte);
like image 39
Daniel Hilgarth Avatar answered Oct 17 '22 15:10

Daniel Hilgarth