tags:

views:

155

answers:

3
+2  Q: 

dynamic casting

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.

+8  A: 

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.

Andrew Hare
Generic methods FTW!
Randolpho
Now just hope Retriever isn't a ContextBoundObject.
TheMissingLINQ
Since ContextBoundObjects cannot have generic methods I think we are OK to assume that the "Retriever" type does not inherit from "ContextBoundObject" since it is exposing a generic method.
Andrew Hare
A: 

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);
}
Daniel Brückner
A: 

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);
}
Dario