Is there a single-line way of casting an object to a decimal? data type?
My code looks something like this:
foreach(DataRow row in dt.Rows)
{
var a = new ClassA()
{
PropertyA = row["ValueA"] as decimal?,
PropertyB = row["ValueB"] as decimal?,
PropertyC = row["ValueC"] as decimal?
};
// Do something
}
However casting an object to a decimal? doesn’t work the way I expect it to, and returns null every time.
The data rows are read from an Excel file, so the data type of the object in each row is either a double if there is a value, or a null string if it’s left blank.
The suggested method to perform this cast is to use decimal.TryParse, however I do not want to create a temp variable for every decimal property on the class (I have about 7 properties on my actual class that are decimals, not 3).
decimal tmpvalue;
decimal? result = decimal.TryParse((string)value, out tmpvalue) ?
tmpvalue : (decimal?)null;
Is there a way I can cast a potentially null value to a decimal? in a single line?
I tried the answer posted here, however it doesn’t appear to be working and gives me a null value as well because row["ValueA"] as string returns null.
Okay, so this complicates matters as sometimes you need to parse it and sometimes you don’t.
The first thing we’ll want to do is check if it’s already a
doubleand cast it, because casting is much cheaper than parsing; parsing is expensive.Given that this logic will be non-trivial, it belongs in it’s own method:
If you know that it will always be a double, and you’ll never want the string values, then it’s easier still. In that case you need to cast it to a double, first, since that’s it’s real type, and then you can easily convert it to a decimal: