64

may be it is a simple question but I'm try all of conversion method! and it still has error! would you help me?

decimal? (nullable decimal) to decimal

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Negar
  • 866
  • 2
  • 10
  • 20

5 Answers5

118

There's plenty of options...

decimal? x = ...

decimal a = (decimal)x; // works; throws if x was null
decimal b = x ?? 123M; // works; defaults to 123M if x was null
decimal c = x.Value; // works; throws if x was null
decimal d = x.GetValueOrDefault(); // works; defaults to 0M if x was null
decimal e = x.GetValueOrDefault(123M); // works; defaults to 123M if x was null
object o = x; // this is not the ideal usage!
decimal f = (decimal)o; // works; throws if x was null; boxes otherwise
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 2
    +1. I prefer `GetValueOrDefault`, because it does not depend on C# syntax and as such, can be used in VB.NET as well. It is also easily adjustable, in case default value of the type does not work for you. – Victor Zakharov Apr 15 '14 at 18:50
  • what about Convert.ToDecimal(); ? can i use it for decimal to decimal coversion? – ManirajSS Jun 16 '14 at 07:38
  • @NullReference what would it mean to do "decimal to decimal" conversion? There is [decimal Convert.ToDecimal(decimal)](http://msdn.microsoft.com/en-us/library/8xhfcwt6(v=vs.110).aspx), but that **literally** just returns the input value – Marc Gravell Jun 16 '14 at 08:33
61

Try using the ?? operator:

decimal? value=12;
decimal value2=value??0;

0 is the value you want when the decimal? is null.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Carles Company
  • 7,118
  • 5
  • 49
  • 75
15

You don't need to convert a nullable type to obtain its value.

You simply take advantage of the HasValue and Value properties exposed by Nullable<T>.

For example:

Decimal? largeValue = 5830.25M;

if (largeValue.HasValue)
{
    Console.WriteLine("The value of largeNumber is {0:C}.", largeValue.Value);
}
else
{
    Console.WriteLine("The value of largeNumber is not defined.");
}

Alternatively, you can use the null coalescing operator in C# 2.0 or later as a shortcut.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
5

It depends what you want to do if the decimal? is null, since a decimal can't be null. If you want to default that to 0, you can use this code (using the null coalescing operator):

decimal? nullabledecimal = 12;

decimal myDecimal = nullabledecimal ?? 0;
Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
-2

You can use.

decimal? v = 2;

decimal v2 = Convert.ToDecimal(v);

If the value is null (v), it will be converted to 0.

curlackhacker
  • 435
  • 5
  • 10
  • I thought that Convert.ToDecimal() was string representations, not for converting nullable decimal to decimal. See here: https://msdn.microsoft.com/en-us/library/9k6z9cdw(v=vs.110).aspx – Mike Upjohn Feb 16 '16 at 16:17