Search code examples
c#typesinstanceprimitive

setting value to the instance of primitive types


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?


Solution

  • 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.
    }