Difference between class and interface in C#

A C# Class Considered being the primary building block of the language. What I mean by the primary building block of the language is that every time you work with C# you will create Classes to form a program. We use Classes as a template to put the properties and functionalities or behaviors in one building block for some group of objects and after that we use that template to create the objects we need.

A class can contain declarations of the following members:

Constructors, Destructors, Constants, Fields, Methods, Properties,Indexers, Operators, Events, Delegates, Classes, Interfaces, Structs

An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface. A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.

An interface can inherit from one or more base interfaces. When a base type list contains a base class and interfaces, the base class must come first in the list.


interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation: 
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }

    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();

        // Call the member.
        obj.SampleMethod();
    }
}

No comments:

Post a Comment