user1108948
user1108948

Reputation:

cannot convert from 'object' to 'decimal'

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

Answers (2)

Oded
Oded

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 objects 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

Blorgbeard
Blorgbeard

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

Related Questions