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;
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.
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.
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.
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>();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With