Question about generics....  
Author Message
DodgySwampy





PostPosted: .NET Base Class Library, Question about generics.... Top

I have several classes that inherit from abstract class B, which itself inherits from abstract class A. I want to be able to call the DoSomething() method from class C and class D and have that method then call the base methods from A and B. Now this I’ve achieved. However, I want to create a generic list class and get that list class to iterate through its collection and return the relevant strings from the calls DoSomething(). In this case I would want s1 = “ABCABCABC” and s2 = “ABDABDABD”. Is this possible Any help you can provide would be much appreciated. Thanks in advance for any help you can provide.

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
C c1 = new C();
C c2 = new C();
C c3 = new C();
List<C> lc1 = new List<C>();
lc1.Add(c1);
lc1.Add(c2);
lc1.Add(c3);
string s1 = lc1.Output(); // I would like this to be equal to "ABCABCABC"! Is this possible

D d1 = new D();
D d2 = new D();
D d3 = new D();
List<D> lc2 = new List<D>();
lc2.Add(d1);
lc2.Add(d2);
lc2.Add(d3);
string s2 = lc2.Output(); // I would like this to be equal to "ABDABDABD"! Is this possible
}
}

public class List<T> : CollectionBase where T : A
{

public List() { }

public T this[int index]
{
get { return (T)List[index]; }
set { List[index] = value; }
}

public int Add(T value)
{
return List.Add(value);
}

public string Output()
{
string output = null;
for (int i = 0; i < List.Count; i++)
{
T t = (T)ListIdea;
output += t.DoSomething();
}
return output;
}

}

public abstract class A
{
public virtual string DoSomething()
{
// Do something very generic....
return "A";
}
}

public abstract class B : A
{
public virtual string DoSomething()
{
// Do something not quite so generic and not quite so specific....
return base.DoSomething() + "B";
}
}

public class C : B
{
public string DoSomething()
{
// Do something very specific....
return base.DoSomething() + "C";
}
}

public class D : B
{
public string DoSomething()
{
// Do something very specific....
return base.DoSomething() + "D";
}
}



.NET Development12  
 
 
Mattias Sjogren





PostPosted: .NET Base Class Library, Question about generics.... Top

Totally possible, just add the override keyword to the DoSomething methods in B, C and D.

 
 
Swampy





PostPosted: .NET Base Class Library, Question about generics.... Top

Thank you very much Mattias, , that worked a treat, you are a .