Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16290

Syntax for comparing type?

I need to check the datatype of a datareader's columns:

Type type = dataTable.Columns[i].DataType;
if (type.Equals(System.Decimal))
{
    //...
}

However, the line if (type.Equals(System.Decimal)) is not correct. What's the correct syntax?

Upvotes: 1

Views: 74

Answers (5)

Marimuthu
Marimuthu

Reputation: 193

You can use typeof operator to check the type of DataColumn type.

if(dataTable.Columns[i].DataType== typeof(System.Decimal))
{
  //Your code
}

Upvotes: 0

Hisham Maudarbocus
Hisham Maudarbocus

Reputation: 620

You could simply do

if (dataTable.Columns[i] is System.Decimal)
{
    //...
}

Its a simplified type comparator

Upvotes: 0

Irshad
Irshad

Reputation: 3131

No need for the type variable;

if(dataTable.Columns[i].GetType().Equals(typeof(decimal)))
{
    //
}

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

You have to add typeof:

  if (type == typeof(Decimal)) {...}

note that Equals is not required and == is more readable.

Upvotes: 2

David Arno
David Arno

Reputation: 43254

You almost have it right. Just change it to:

if (type.Equals(typeof(System.Decimal)))

Though a better way of expressing it would be:

if (type == typeof(System.Decimal))

and if you add a using System; to the top of your file, you can make it:

if (type == typeof(Decimal))

Upvotes: 6

Related Questions