Reputation:
Basically I have a list:
List<Decimal> SortOrders = new List<Decimal>();
And a DataRow. I wan to compare whether the list contains an item from a control. But I got an exception,
cannot convert from "Object " to "decimal
DataRow dr = dataSetSomething.Tables[0].NewRow();
...
dr["SortOrder"] = Convert.ToDecimal(numericOrder.Value);// works fine here
if (SortOrders.Contains(dr["SortOrder"]))// exception here, Why?
{
}
Thanks for help.
Upvotes: 2
Views: 4990
Reputation: 499382
The type of dr["SortOrder"]
is Object
.
Any type in .NET is an object (as all types inherit from Object
, directly or through the inheritance chain), so assigning a decimal
to an object
is fine.
The opposite is not true - not all object
s are decimal
.
You need to cast in order to get the expected behaviour:
if (SortOrders.Contains((decimal)dr["SortOrder"]))
(which will throw an exception if the underlying type is not a decimal
).
Upvotes: 2
Reputation: 103575
Because the type of dr["SortOrder"]
is object
, even if you put a decimal
in there. If you know it's actually a decimal, you can cast it:
if (SortOrders.Contains((decimal)dr["SortOrder"]))
Upvotes: 2