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?

Abbas
  • 6,720
  • 4
  • 35
  • 49
senzacionale
  • 20,448
  • 67
  • 204
  • 316

4 Answers4

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)
3

You should handle null separately, like this:

DejanskaKolicina == null ? "N/A" : DejanskaKolicina.Value.ToString(CultureInfo.CurrentCulture)  
Nuffin
  • 3,882
  • 18
  • 34
0

Use the Value property of the nullable object:

DejanskaKolicina == null ? "" : DejanskaKolicina.Value.ToString(CultureInfo.CurrentCulture);
rikitikitik
  • 2,414
  • 2
  • 26
  • 37
  • If you don't check for null first, and the property is null, you'll get an exception that I understood to be undesirable. –  Jan 30 '12 at 06:52
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.

Sandy
  • 6,285
  • 15
  • 65
  • 93
  • 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;`. –  Jan 30 '12 at 07:52