7

I have a function that has Type Parameter.

public static object SetValuesToObject(Type tClass, DataRow dr)
{
   //
   .............
   //
   return object
} 

I have no idea how to pass a class as parameter for this function. Here i want to pass parmeter Class "Product".

I tried this

 SetValuesToObject(Product,datarow);

But it doesn't work. How could i do this?

Thilina H
  • 5,754
  • 6
  • 26
  • 56
folk
  • 687
  • 3
  • 8
  • 16

2 Answers2

7

The typeof keyword when you know the class at compile time.

SetValuesToObject(typeof(Product),datarow);

You can also use object.GetType() on instances that you don't know their type at compile time.

argaz
  • 1,458
  • 10
  • 15
  • This saved me! You point out an important distinction about what's known at compile time and what's not. object.GetType() is what I needed. – Scott Ridings May 26 '20 at 13:28
4

You have a few options:

  1. instance.GetType() : this method (defined in Object) will return the instance's type.
  2. typeof(MyClass) : will give you the type for a class.

Finally, if you own the method, you could change it to use Generics, and call it like this instead

SetValuesToObject<Product>(datarow)

Esteban Araya
  • 29,284
  • 24
  • 107
  • 141