gwizardry
gwizardry

Reputation: 511

Use properties to refer derived class member variables to base class member variables

My current code looks a little like this.

class BaseClass2
{
    public List<BaseClass1> list { get; set; }
}

class DerivedClass2 : BaseClass2
{
    public DerivedClass1A objA { get; set; }
    public DerivedClass1B objB  { get; set; }
}

What i have is a DerivedClass2 where i know the types of the list in the base class and i know there will be two types of DerivedClass1A and DerivedClass1B.

I could create new variables as above but i'd prefer not to use the memory and cleverly access and set the original list, how can i do this?

Thanks

Upvotes: 0

Views: 434

Answers (2)

Jakub Konecki
Jakub Konecki

Reputation: 46008

You can use generics:

class BaseClass2<T>
  T : BaseClass1
{
    public List<T> list { get; set; }
}

class DerivedClass2 : BaseClass2<BaseClass1>
{
    public DerivedClass1A objA { get; set; }
    public DerivedClass1B objB  { get; set; }
}

Or if you just want to get a subclasses from your list you can use TypeOf() method:

baseClass2Instance.list.TypeOf<DerivedClass1A>();

Upvotes: 1

YoryeNathan
YoryeNathan

Reputation: 14502

Do you mean something like this?

class DerivedClass2 : BaseClass2
{
    public DerivedClass1A objA
    {
        get
        {
            return (DerivedClass1A)base.list[0];
        }
        set
        {
            base.list[0] = value;
        }
    }

    public DerivedClass1B objB
    {
        get
        {
            return (DerivedClass1B)base.list[1];
        }
        set
        {
            base.list[1] = value;
        }
    }
}

That isn't good design though... Why would you have that list? What are you really trying to do?

Upvotes: 0

Related Questions