user4546142
user4546142

Reputation:

C# list of substitutable type

I have following structure:

awesomeItemBase
+ int a
+ int b

awesomeItemSpecial1: awesomeItemBase
+ int c
+ string s
..etc

awesomeItemSpecial2: awesomeItemBase
+ int d
+ string t
..etc

Let's assume I want to create a list of those 2 derived classes by wrapping them in one common type, so that each list item holds the information int a, int b An interface cannot have fields..

How could I do this?

Upvotes: 0

Views: 54

Answers (1)

John Riehl
John Riehl

Reputation: 1330

If I understand your question properly, you could do this:

public class AwesomeItemBase {
    // you could also make these fields
    public int A {get; set;}
    public int B {get; set;}
}

public class AwesomeItemSpecial1 : AwesomeItemBase {
    // additional fields and properties
}

public class AwesomeItemSpecial2 : AwesomeItemBase {
    // additional fields and properties
}

You'd then be able to:

var foo = new AwesomeItemSpecial1();
foo.A = 42;
foo.B = -1;
var bar = new AwesomeItemSpecial2();
bar.A = 3;
bar.B = 59;

var awesomeList = new List<AwesomeItemBase>();
awesomeList.Add(foo);
awesomeList.Add(bar);

foreach (var item in awesomeList) {
    Console.WriteLine("A = {0}, B = {1}", item.A, item.B);
}

// output is:
// A = 42, B = -1
// A = 3, B = 59

Upvotes: 2

Related Questions