PositiveGuy
PositiveGuy

Reputation: 47743

How to check for valid value before converting Decimal

I assume this will blow up if total is null (I don't recall if decimals are initalized to null at the beginning or zero)

public int SomePropertyName
{
    get { return Convert.ToInt32(Decimal.Round(total)); }
}

So should I check for null or > 0 ?

Upvotes: 0

Views: 3018

Answers (5)

vgru
vgru

Reputation: 51214

System.Decimal is a value type, so it cannot be null. Second thing, the method's return value is decimal, so why would you want to convert to a Int32?

Upvotes: 1

Philip Wallace
Philip Wallace

Reputation: 8015

As others have said, Decimal is a value type and cannot be null. However, if converting from a string then Decimal.TryParse is your friend...

Upvotes: 1

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

Decimal is a value type and can not be null.

If you need to know if it had been initialized, you should probably use a nullable decimal:

Decimal? total = null;

public int SomePropertyName
{
    get 
    { 
        if (total.HasValue) Convert.ToInt32(Decimal.Round(total.Value)); 
        return 0; // or whatever
    }
}

Upvotes: 2

Tor Haugen
Tor Haugen

Reputation: 19627

Decimals are value types, and so cannot be null.

So no need to check there..

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500105

Decimal is a value type - there's no such value as "null" for a decimal.

However, it's perfectly possible for a decimal to be out of range for an int. You might want:

decimal rounded = decimal.Round(total);
if (rounded < int.MinValue || rounded > int.MaxValue)
{
    // Do whatever you ought to here (it will depend on your application)
}
return (int) rounded;

I'm somewhat confused as to why you're using Convert.ToInt32 at all though, given that your property is declared to return a decimal. What's the bigger picture here? What are you trying to achieve?

Upvotes: 5

Related Questions