Vererbung In C

Vererbung in C#

Hier ein Beispiel wie Vererbung in C# funktionieren kann. Danke an Michael Stoyke.

namespace CSharpPlayground
{
    public class BaseClass
    {
        public string Id { get; private set; }

        public string Misc1 { get; set; }

        public BaseClass(string id)
        {
            Id = id;
            Misc1 = string.Empty;
        }
    }

    public class DerivedClass : BaseClass
    {
        public int Value { get; private set; }

        public string Misc2 { get; set; }

        public DerivedClass(string id, int value)
            : base(id)
        {
            Value = value;
            Misc2 = string.Empty;
        }
    }

    class Test
    {
        static void Main(string[] args)
        {
            BaseClass class1 = new BaseClass("obj1");
            DerivedClass class2 = new DerivedClass("obj2", 2);

            BaseClass class3 = new DerivedClass("obj3", 3) { Misc1 = "Hello", Misc2 = "World" };
        }
    }
}

Tags: C# | Vererbung