Home > OS >  Return base type instead of derived type in a generic method
Return base type instead of derived type in a generic method

Time:04-21

I have a BaseClass as follows

public class BaseClass
{
    public string A { get; set;}
    public string B { get; set;}
}

and another class derives from the BaseClass as follows

public class DerivedClass : BaseClass
{
    public string C { get; set;}
}

I have a generic method which may return any derived class which inherits BaseClass.

public T MyMethod(bool returnBase) where T : BaseClass
{
    if(!returnBase)
    {
        T result = JsonConvert.DeserializeObject<T>(someString);
        return T;
    }
    else
    {
        BaseClass bc = new BaseClass
        {
            A = "some string",
            B = "some other string"
        };
        return (T)bc;
    }
}

In this code, when returnBase is FALSE everything works OK, but when it is set to TRUE, I want to return BaseClass, but since I have defined the return type (T) as the DerivedClass in the calling code, I get Exception.

How can I get this code running?

CodePudding user response:

Just set the method return type as BaseClass and avoid the (T) casting when you return the base

public BaseClass MyMethod(bool returnBase) where T : BaseClass
{
    if(!returnBase)
    {
        T result = JsonConvert.DeserializeObject<T>(someString);
        return T;
    }
    else
    {
        BaseClass bc = new BaseClass
        {
            A = "some string",
            B = "some other string"
        };
        return bc;
    }
}

CodePudding user response:

It would be an error in inheritance in the cast (T)bc since you can not cast the parent to the child. It is equivalent to saying all Animals are Dogs although there are other animals (e.g. Cats) as well, which are definitely not dogs.

In order to get it running, I would propose to implement the else in the following way:

T defaultObj = new T
{
   A = "some string",
   B = "some other string"
}

return defaultObj;

Since T is a child of BaseClass, it should have all properties from the base class.

  • Related