Knowledge Management Banner

Knowledge Management Banner

C# : Sealed class , Interface : Part 10

Sealed class
  • Once the class is marked as sealed than it cannot be used as inheritance, or as a base class.
Interface
  • It is used only for declaration, implementation is not done here.
  • All the declaration are public by default.
  • It contains only declarations no fields.
  • If a class inherits from an interface than it must provide implementation for all interface members, other wise it will provide compile time error.
  • Class cannot inherit from more than one class where as it can inherit from more than one interface.
e.g. 

namespace Interface
{
    public interface Interface1
    {
        int Add(int a, int b);
    }

    public class Class1 : Interface1
    {
         
        public int Add(int a, int b)
        {
            return a + b;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Class1 objClass1 = new Class1();
            var result = objClass1.Add(3, 6);
        }
    }
}

Explicit Implementation of Interface
  • If the class inherits from two or more interface and all of them have same method with same signature, than there comes the need of explicit implementation.
  • If Explicit implementation is not done, it will not give any compile time error, but method from which interface is invoked is not cleared.
  • Thus explicit implementation of interface is done by type casting of object.
e.g. 1 type casting is not done

namespace ExplicitInterfceImplementation
{
    public interface Interface1
    {
        int Add(int a, int b);
    }

    public interface Interface2
    {
        int Add(int a, int b);
    }

    public class Class1 : Interface1, Interface2
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Class1 objClass1 = new Class1();
            var result = objClass1.Add(3, 6);
        }
    }
}

e.g. 2 With type casting implementation of interface

namespace ExplicitInterfceImplementation
{
    public interface Interface1
    {
        int Add(int a, int b);
    }

    public interface Interface2
    {
        int Add(int a, int b);
    }

    public class Class1 : Interface1, Interface2
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Class1 objClass1 = new Class1();
            var result = ((Interface1)objClass1).Add(3, 6);
        }
    }
}







No comments

Powered by Blogger.