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?
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)...
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 a parameter to another function in javascript" --- yes you can, it is an ordinary variable with a reference to current object.
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.
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.
You have a few options:
instance.GetType()
: this method (defined in Object) will return the instance's type.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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With