How can I convert decimal? to decimal

Negar picture Negar · Feb 2, 2011 · Viewed 78.9k times · Source

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

Answer

Marc Gravell picture Marc Gravell · Feb 2, 2011

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