Create a Variant Generic Type - CSharp Custom Type

CSharp examples for Custom Type:Generics

Description

Create a Variant Generic Type

Demo Code


using System;/*ww  w .j  a  va  2  s  .c o m*/

class MainClass
    {
        static void Main(string[] args)
        {
            IMyInterface<DerivedType> variant = new ImplClass<DerivedType>(new DerivedType());
            processData(variant);
        }

        static void processData(IMyInterface<BaseType> data)
        {
            data.getValue().printMessage();
        }
    }

    class BaseType
    {
        public virtual void printMessage()
        {
            Console.WriteLine("BaseType Message");
        }
    }

    class DerivedType : BaseType
    {
        public override void printMessage()
        {
            Console.WriteLine("DerivedType Message");
        }
    }

    public interface IMyInterface<out T>
    {
        T getValue();
    }

    public class ImplClass<T> : IMyInterface<T>
    {
        private T value;
        public ImplClass(T val)
        {
            value = val;
        }

        public T getValue()
        {
            return value;
        }
    }

Result


Related Tutorials