7

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; 
1
  • Thats the tidiest way. You could encapsulate that in your own utility method if you need. Commented Mar 30, 2011 at 14:36

2 Answers 2

6

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>(); 
Sign up to request clarification or add additional context in comments.

1 Comment

Hands down the best answer.
4

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.