Reputation: 5083
How do I cast a parameter passed into a function at runtime?
private object PopulateObject(object dataObj, System.Data.DataRow dataRow, string query)
{
object = DataAccess.Retriever.RetrieveArray<dataObj.GetType()>(query);
i'd like to know how to get dataObj.GetType() inside the type declaration at runtime.
Upvotes: 2
Views: 357
Reputation: 351648
Try something like this:
private T PopulateObject<T>(T dataObj, System.Data.DataRow dataRow, string query)
{
dataObj = DataAccess.Retriever.RetrieveArray<T>(query);
}
This will allow you to avoid any reflection in this method as the type argument supplied to PopulateObject
will also be the type argument for RetrieveArray
. By calling this method the compiler will be able to infer the type of T
, allowing you to avoid writing runtime type checking.
Upvotes: 8
Reputation: 49218
You want to know how to set a generic type parameter at runtime?
You'll need Reflection here - MakeGenericMethod
Note: When the Type can be determined at compile-time, rewrite this using a type parameter.
private T PopulateObject<T>(T dataObj, System.Data.DataRow dataRow, string query)
{
dataObj = DataAccess.Retriever.RetrieveArray<T>(query);
}
Upvotes: 0
Reputation: 59705
You cannot do this, because variable declaration happens at compile time, not runtime. You should create a generic method.
private T PopulateObject<T>(T dataObj, DataRow dataRow, String query)
{
return DataAccess.Retriever.RetrieveArray<T>(query);
}
Upvotes: 0