Reputation: 47743
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
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
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
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
Reputation: 19627
Decimals are value types, and so cannot be null.
So no need to check there..
Upvotes: 1
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