How can I convert decimal? to decimal

C#.NetDecimalType ConversionNullable

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

Try using the ?? operator:

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

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

Solution 3 - C#

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.

Solution 4 - C#

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;

Solution 5 - C#

You can use.

decimal? v = 2;

decimal v2 = Convert.ToDecimal(v);

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNegarView Question on Stackoverflow
Solution 1 - C#Marc GravellView Answer on Stackoverflow
Solution 2 - C#Carles CompanyView Answer on Stackoverflow
Solution 3 - C#Cody GrayView Answer on Stackoverflow
Solution 4 - C#Øyvind BråthenView Answer on Stackoverflow
Solution 5 - C#curlackhackerView Answer on Stackoverflow