Cannot specify a culture in string conversion explicitly when converting nullable decimal (decimal?) to string

5k views Asked by At

I have a property:

public decimal? DejanskaKolicina { get; set; }

and Resharper shows me:

specify a culture in string conversion explicitly

But if I use:

DejanskaKolicina.ToString(CultureInfo.CurrentCulture) 

I always get the message that:

ToString method has 0 parameter(s) but it is invoked with 1 arguments

If I change the decimal property so that it is no longer nullable then it works. How do I use ToString(CultureInfo.CurrentCulture) on nullable property?

4

There are 4 answers

0
AudioBubble On BEST ANSWER

That particular ToString overload only exists for a decimal, so you can make it work by only calling it for a decimal:

DejanskaKolicina == null ? String.Empty : DejanskaKolicina.Value.ToString(CultureInfo.CurrentCulture)
1
rikitikitik On

Use the Value property of the nullable object:

DejanskaKolicina == null ? "" : DejanskaKolicina.Value.ToString(CultureInfo.CurrentCulture);
0
Nuffin On

You should handle null separately, like this:

DejanskaKolicina == null ? "N/A" : DejanskaKolicina.Value.ToString(CultureInfo.CurrentCulture)  
1
Sandy On

I think, this example may help you:

A nullable type can be used in the same way that a regular value type can be used. In fact, implicit conversions are built in for converting between a nullable and non-nullable variable of the same type. This means you can assign a standard integer to a nullable integer and vice-versa:

int? nFirst = null;
int Second = 2; nFirst = Second; // Valid
nFirst = 123; // Valid
Second = nFirst; // Also valid
nFirst = null; // Valid
Second = nFirst; // Exception, Second is nonnullable.

In looking at the above statements, you can see that a nullable and nonnullable variable can exchange values as long as the nullable variable does not contain a null. If it contains a null, an exception is thrown. To help avoid throwing an exception, you can use the nullable's HasValue property:

if (nFirst.HasValue) Second = nFirst;

As you can see, if nFirst has a value, the assignment will happen; otherwise, the assignment is skipped.