Alex Rivera | Logout

C# polymorphism simple question

Asked 2010-02-09T19:01:43.857
9

I got a class X and a class Y, the latter which derives from X :

class x {}
class y : x {}

Then somewhere I am using a list of X :

List<X> lstX;
...

Then I'd like to use a new list of Y, from the data in my other list...something along those lines :

List<Y> lstY = lstX;

I would believe that the items in the list of X would get converted automatically into Y, but thats not the case.

Also, how could I initialize a new instance of Y, from a certain X? I would like to do :

var newX = new X();
var newY = new Y(X);

but it does not seem to work like that.

Thanks for your help! and sorry for formatting, trying my best

Edit
Report

1 Answer

1

Try this:


using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List myList;

            myList = GetMyList(MyListTypeEnum.MyList1);
            myList = GetMyList(MyListTypeEnum.MyList2);
        }

        public static List GetMyList(MyListTypeEnum tipo)
        {
            List result;
            result = new List();

            switch (tipo)
            {
                case MyListTypeEnum.MyList1:
                    List myList1 = GetMyList1();
                    foreach (var item in myList1)
                    {
                        result.Add((IMyList) item);
                    }
                    break;
                case MyListTypeEnum.MyList2:
                    List myList2 = GetMyList2();
                    foreach (var item in myList2)
                    {
                        result.Add((IMyList) item);
                    }
                    break;
            }

            return result;
        }

        public static List GetMyList1()
        {
            List myList1 = new List();
            myList1.Add(new MyList1 { Code = 1 });
            myList1.Add(new MyList1 { Code = 2 });
            myList1.Add(new MyList1 { Code = 3 });
            return myList1;
        }

        public static List GetMyList2()
        {
            List myList2 = new List();
            myList2.Add(new MyList2 { Name = "1" });
            myList2.Add(new MyList2 { Name = "2" });
            myList2.Add(new MyList2 { Name = "3" });
            return myList2;
        }
    }

    public interface IMyList
    {
    }

    public class MyList1 : IMyList
    {
        public int Code { get; set; }
    }

    public class MyList2 : IMyList
    {
        public string Name { get; set; }
    }

    public enum MyListTypeEnum
    {
        MyList1,
        MyList2
    }
}

answered 2012-04-28T13:28:49.743

Your Answer