Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of abstract class

Tags:

c#

list

abstract

I have abstract class:

public abstract class MyClass
{
    public abstract string nazwa
    {
        get;
    }
}

And two classes which inherit from MyClass:

public class MyClass1 : MyClass
{
    public override string nazwa
    {
        get { return "aaa"; }
    }
}

public class MyClass2 : MyClass
{
    public override string nazwa
    {
        get { return "bbb"; }
    }
}

In another class I create List:

List<MyClass> myList;

Now I want to create

myList = new List<MyClass1>;

The compiler show an error:

Cannot implicitly convert type 'System.Collections.Generic.List<Program.MyClass1>' to 'System.Collections.Generic.List<Program.MyClass>'

I must be some easy way to convert it... I cannot find anything useful

like image 663
Pieniadz Avatar asked Sep 19 '11 17:09

Pieniadz


People also ask

What are the types of abstract class?

In object-oriented programming, an abstract class may include abstract methods or abstract properties that are shared by its subclasses. Other names for language features that are (or may be) used to implement abstract types include traits, mixins, flavors, roles, or type classes.

Is list an abstract class?

List lst = new LinkedList(); which shows that List is some sort of Class. So, why call it an Interface? We can simply call it an Abstract class which implements Collection.

Is ArrayList an abstract class?

Example 1: AbstractList is an abstract class, so it should be assigned an instance of its subclasses such as ArrayList, LinkedList, or Vector.

Which is the best example of an abstract class?

The best example of an abstract class is GenericServlet . GenericServlet is the parent class of HttpServlet . It is an abstract class.


1 Answers

You can create the list as the base type:

List<MyClass> myList = new List<MyClass>();

Which you can then add derived items to:

myList.Add(new MyClass2());
like image 168
Joel Beckham Avatar answered Oct 22 '22 22:10

Joel Beckham