Monday, August 18, 2014

Understanding interfaces in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Apps
{
    // Interface is a collection of abstract members and properties.
    // Unlike the Abstract class the interface cannot contain the non-abstract members.

    interface Iclass1
    {
        // A property in interface can be specified without any body
        int a { set; get; }
        void PrintProperty();

        // Access modifiers for the members of interface defaults to Public
        void Read();
}

    interface Iclass2
    {
        void Write();
}

    class Test9 : Iclass1Iclass2      // Multiple interfaces
{

       // The class should implement all the methods and properties contained in the interface.(if not gives compile error)
        public int a { setget; }

        public void Print()
        {
            Console.WriteLine("Non-interface method implemented in class, Value=" + a);
        }

        public void PrintProperty()
        {
            Console.WriteLine(a);
        }

        public void Read()
        {
            Console.WriteLine("Reading example");
        }

        public void Write()
        {
            Console.WriteLine("Writing example");
        }
    }

    class UnderstandingInterfaces
    {
        public static void Main()
        {
            Iclass1 ts = new Test9();
            Iclass2 ts1 = new Test9();
            ts.Read();
            ts1.Write();
            ts.PrintProperty();

            Test9 ts2 = new Test9();
            ts2.Print();
        }
    }
}

No comments:

Post a Comment