21

I am wondering what would be the best way (in the sense of safer and succinct) to convert from one nullable type to another "compatible" nullable type.

Specifically, converting from decimal? to double? can be done using:

public double? ConvertToNullableDouble(decimal? source)
{
    return source.HasValue ? Convert.ToDouble(source) : (double?) null;
}

Is there any better way to do this? Maybe leveraging a standard conversion?

Camilo Martinez
  • 1,723
  • 2
  • 21
  • 26

2 Answers2

38

Built in casts for the win! Just tested this in VS2012 and VS2010:

 decimal? numberDecimal = new Decimal(5); 
 decimal? nullDecimal = null;
 double? numberDouble = (double?)numberDecimal; // = 5.0
 double? nullDouble = (double?)nullDecimal;     // = null

Just using an explicit cast will cast null to null, and the internal decimal value to double. Success!

Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63
1

In general, if you want o convert from any data type to the other as long as they are compatible, use this:

    Convert.ChangeType(your variable, typeof(datatype you want convert to));

for example:

    string str= "123";
    int value1 = (int)Convert.ChangeType(str, typeof(int));
    float? value2 = (float?)Convert.ChangeType(str, typeof(float));
    ...................................

A little bit further, if you want it to be more safer, you can add a try catch on it:

string str= "123";
try
{
    int value1 = (int)Convert.ChangeType(str, typeof(int));
    int? value2 = (int?)Convert.ChangeType(str, typeof(int));
    float value3 = (float)Convert.ChangeType(str, typeof(float));
    float? value4 = (float?)Convert.ChangeType(str, typeof(float));
}
catch(Exception ex)
{
  // do nothing, or assign a default value
}

this is tested under VS 2010

diwatu
  • 5,641
  • 5
  • 38
  • 61
  • Yes, this is a more general way to convert between types, not as succinct as the accepted answer. @Giswin Does it works for nullables as well? I imagine so, but I don't find a specific comment on this in the [documentation](http://msdn.microsoft.com/en-us/library/dtb69x08.aspx). – Camilo Martinez May 02 '13 at 21:35
  • you can use this: decimal? v1 =222; double? V2 = (double?)Convert.ChangeType(v1, typeof(double)); but if v1 is null, Convert.ChangeType will throw a exception. and then the try catch dose the left job. – diwatu May 02 '13 at 21:51