Cannot specify culture in string conversion explicitly when converting zero decimal (decimal?) To string

I have a property:

public decimal? DejanskaKolicina { get; set; } 

and Resharper shows me:

explicitly specify culture in string conversion

But if I use:

 DejanskaKolicina.ToString(CultureInfo.CurrentCulture) 

I always get a message that:

The ToString method has 0 parameters, but it is called with 1 argument

If I change the decimal property so that it is no longer valid, it works. How to use ToString(CultureInfo.CurrentCulture) property nullable?

+7
source share
4 answers

This special ToString overload exists only for decimal , so you can make it work only by calling it for decimal :

 DejanskaKolicina == null ? String.Empty : DejanskaKolicina.Value.ToString(CultureInfo.CurrentCulture) 
+7
source

You must handle null separately, for example:

 DejanskaKolicina == null ? "N/A" : DejanskaKolicina.Value.ToString(CultureInfo.CurrentCulture) 
+3
source

Use the Value property for an object with a NULL capability:

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

I think this example may help you:

A type with a null value can be used in the same way as a regular value type. In fact, implicit conversions are built in to convert between a variable with a null and non-empty value of the same type. This means that you can assign a standard integer with a zero number 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. 

When looking at the statements above, you can see that a variable with a null value and an immutable variable can exchange values ​​as long as a variable with a null value does not contain zero. If it contains null, an exception is thrown. To avoid throwing an exception, you can use the nullable HasValue property:

 if (nFirst.HasValue) Second = nFirst; 

As you can see, if nFirst matters, this will happen; otherwise assignment is skipped.

0
source

All Articles