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

4

7

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?

Mcabee answered 30/1, 2012 at 6:44 Comment(0)
B
7

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)
Boorish answered 30/1, 2012 at 6:49 Comment(0)
S
3

You should handle null separately, like this:

DejanskaKolicina == null ? "N/A" : DejanskaKolicina.Value.ToString(CultureInfo.CurrentCulture)  
Scrivenor answered 30/1, 2012 at 6:50 Comment(0)
D
0

Use the Value property of the nullable object:

DejanskaKolicina == null ? "" : DejanskaKolicina.Value.ToString(CultureInfo.CurrentCulture);
Distinguish answered 30/1, 2012 at 6:49 Comment(1)
If you don't check for null first, and the property is null, you'll get an exception that I understood to be undesirable.Boorish
L
0

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.

Luiseluiza answered 30/1, 2012 at 6:56 Comment(1)
That example doesn't compile: you cannot implicitly convert an int? to an int. The behaviour you describe is what you get when you add a cast: Second = (int)nFirst;.Boorish

© 2022 - 2024 — McMap. All rights reserved.