1 year ago

#382317

test-img

binariti

Generics: cast derived class back to it's parent super class

I have three base classes:

public class ItemBase
{
    public string Name { get; set; }
}

public class ProductBase<T> : ItemBase
    where T : ItemBase
{
    public List<T> Modifiers { get; set; }
    public List<T> GroupModifiers { get; set; }
}

public class ModifierBase<T> : ItemBase
    where T : ItemBase
{
    public List<T> ChildModifiers { get; set; }
}

And two derived classes:

public class Product : ProductBase<Modifier>
{
    public string Some_Product_Specific_Property { get; set; }
}

public class Modifier : ModifierBase<Modifier>
{
    public string Some_Modifier_Specific_Property { get; set; }
}

The intent behind all this is to have different sets of derived classes like Product and ProductFromOtherSystem each with it's own specific properties but with the same basic properties.

And now I need to process basic properties of any class derived from ProductBase<T>. For this purpose I want to use something like this:

public static void DoSomething(ProductBase<ModifierBase<ItemBase>> item)
{
    Console.WriteLine(item.Name);
}

The issue here is that I cannot pass parameters to it:

Product product1 = new Product();
DoSomething(product1);

ProductFromOtherSystem product2 = new ProductFromOtherSystem();
DoSomething(product2 as ProductBase<ModifierBase<ItemBase>>);

The error is like

Cannot convert type _ to _ via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

I've tried to downcast it somehow but have not found any solution. I wonder if it is possible to do it?

c#

oop

generics

polymorphism

0 Answers

Your Answer

Accepted video resources