Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an Object type to Type parameter in C#

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?

like image 934
folk Avatar asked Oct 30 '13 04:10

folk


People also ask

How do you pass an object type as a parameter?

This would be called like: int val = (int)GetColumnValue(columnName, typeof(int)); The other option would be to use generics: T GetColumnValue<T>(string columnName) { // If you need the type, you can use typeof(T)...

Can I pass a type as a parameter C#?

They work the same way, and you can even pass the type parameter as a type parameter to another function. Notably though, you can use the type parameter in the actual parameters of the function.

Can I pass this as parameter?

"Can I pass “this” as a parameter to another function in javascript" --- yes you can, it is an ordinary variable with a reference to current object.

How do you pass a function as a parameter in C#?

If we want to pass a function that does not return a value, we have to use the Action<> delegate in C#. The Action<T> delegate works just like the function delegate; it is used to define a function with the T parameter. We can use the Action<> delegate to pass a function as a parameter to another function.


2 Answers

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.

like image 58
argaz Avatar answered Sep 22 '22 15:09

argaz


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)

like image 43
Esteban Araya Avatar answered Sep 24 '22 15:09

Esteban Araya