Tuesday, August 3, 2010

Interface In C#

  • In C# we can define an Interface using Interface key word. Define
    //Difine an Interface
    interface MyInterface
    {
} 
  • Interfaces can be consisting of methods, properties, events, indexers or any combination of those types.
  • By default all the interface members are Public. So if we use any access modifiers it will prompt compile time error.
  • Add Interface methods have only declarations, not method implementations.
  • Class can be inherited by more than one Interface.
  • Interface can be inherited from other interface as well.
  • Interface not allows creating instances. 
    //Difine an Interface
    interface MyInterface
    {
        void MyMethods();
        void MyMethods2();
    }
    class clsMyClass : MyInterface
{
    //Can’t create Privet member
        public void MyMethods()
        {
            //Method Implementation
            Console.WriteLine("Implement Method MyMethods()");
        }

        public void MyMethods2()
        {
            //Method Implementation
            Console.WriteLine("Implement Method MyMethods2()");
        }

        public static void Main()
        {
            clsMyClass oclsMyClass = new clsMyClass();
            oclsMyClass.MyMethods();
            oclsMyClass.MyMethods2();
        }
    } 
  • When inherit from an Interface need to provide the implementation for all methods. Unless a compile error will be generated.
  • If the Class or struct is unable to provide the implementation for all methods, which are in the Interface have to be marked as Abstract.
//Difine an Interface
    interface MyInterface
    {
        void MyMethods();
        void MyMethods2();
    }
    class clsMyClass : MyInterface
    {
        public void MyMethods()
        {
            //Method Implementation
            Console.WriteLine("Implement Method MyMethods()");
        }

        //No Implementation
        abstract public void MyMethods2();


        public static void Main()
        {
            clsMyClass oclsMyClass = new clsMyClass();
            oclsMyClass.MyMethods();
            oclsMyClass.MyMethods2();
        }
    }



Related Posts
Abstract Class In C#
Sealed Class In C#
Interface In C#
Abstract Class vs. Interface in C#
NET framework Comparison
C# Interview Questions

No comments:

Post a Comment