views:

29

answers:

1

I have a function which performs some operation i.e. fetches some data from database. The generic it takes is primitive type always i.e. int, char, bool, string etc. I can easily create its instance. But I can't set the value that I have fetched from database to this instance.

public T PerformOperation<T>()
{    
    object instance = (T)Activator.CreateInstance(typeof(T));

    object result=FetchData();

    instance = (T)result; //It gives error on this statement
}

The function is called as:

int result = PerformOperation<int>();

Is there some way of casting the object Type to any generic type which is always primitive?

+1  A: 

When you already have type T, why box it into Object unnecessary.

public T PerformOperation<T>()
{    
    T instance = (T)Activator.CreateInstance(typeof(T)); // why do you need this ?

    T result = FetchData();

    //instance = (T)result;
    return result;
}

or may be this way, if you must use Object.

public T PerformOperation<T>()
{    
    //object instance = (T)Activator.CreateInstance(typeof(T));    
    //object result=FetchData();

    return (T)FetchData(); // If I could get you correctly.
}
this. __curious_geek
That's exactly I am doing but its throwing the exception that specific Cast Not Allowed.
Samreen
If FetchData() returns a `string` and the type T is `int` at runtime, you will surely get the error. You should also make your FetchData() generic and call like this `T result = FetchData<T>();`
this. __curious_geek
I found the error. Actually it cannot convert the decimal type that is being fetched from database. So Convert.ChangeType(result,typeof(T)); coverted the data coming from database to the desired type at runtime. Thanks a lot for the favour:)
Samreen