Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
I have 2 methods which I'm planning to refactor into a single method

C#
IFactory _factory

// Method 1

TClass obj = (TClass )_factory.CreateA(param1);

// Method 2

HClass obj  = (HClass )__factory.CreateB(param2);


Now I want a generic method which will return me generic object

Below is the code which I tried,But in vain.Get typecast error

C#
T CreateInst<<T>>() 
{
    T _requestType;
        if(_requestType.GetType() == typeof(TClass ))
        {
             _requestType = (TClass)_factory.CreateA(param1)  ;
        }
        else if(_requestType.GetType() == typeof(HClass ))
        {
            _requestType = (HClass)_factory.CreateB(param1)  ;
        }

    return _requestType;
}
Posted
Updated 21-Aug-13 0:04am
v6

That happens because your method tries to assign an object of type TClass or HClass to an object of type T. Since there are no constraints for T, T can be anything and, you cannot assign TClass or HClass to anything...


Maybe, you intended to write something like:


C#
T CreateInst<T>(object param1) where T : class
{
    T _requestType = null;

    if(typeof(T) == typeof(TClass))
    {
        _requestType = _factory.CreateA(param1) as T  ;
    }
    else if(typeof(T) == typeof(HClass))
    {
        _requestType = _factory.CreateB(param1) as T ;
    }
 
    return _requestType;
}
 
Share this answer
 
Comments
explorerC 21-Aug-13 8:32am    
Hey it works!!!...Thanks for the input
Is it possible to hold this object in generic object and access its properties ??
Shmuel Zang 21-Aug-13 8:56am    
It is possible if you have a type constraint for a type that contains those properties. Think about it, since this is a generic type, the compiler needs a way to be sure that the type has the properties (or anything you want to do with that type)...
explorerC 22-Aug-13 4:24am    
Thanks very much for your inputs
explorerC 22-Aug-13 7:09am    
Hi Shmuel,

Type constraint is there, But it doesn't allow add multiple class constraint.

T CreateInst<t>(object param1) where T : TClass,HClass
Shmuel Zang 24-Aug-13 15:04pm    
That's because no .NET class can be derived from 2 classes (in your case TClass and HClass)...
C#
T CreateInst<<T>>()
{
    T _requestType;
        if(_requestType is TClass)
        {
             _requestType = (TClass)_factory.CreateA(param1)  ;
        }
        else if(_requestType is HClass )
        {
            _requestType = (HClass)_factory.CreateB(param1)  ;
        }

    return _requestType;
}
 
Share this answer
 
Comments
explorerC 21-Aug-13 8:01am    
Hi Moses
Again getting compilation error.Are you missing a cast

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900