C# Tutorial

C# Tutorial C# First Application C# Variables C# Data Types C# Operators C# Keywords

C# Control Statement

C# If Statements C# Switch Statements C# for Loop C# While Loop C# do While loop C# Jump Statements C# Function C# functions with out variable

C# Arrays

C# Arrays

C# Function

C# Function call by value C# Call by reference C# Passing array to function C# Multidimensional Arrays C# Jagged Arrays C# Params C# Array Class C# Command Line Arguments

C# Object Class

C# Object and Classes C# Constructors C# Destructor C# this Keyword C# static field C# static class C# Static Constructor C# Structs C# enum C# Properties

C# Inheritance

C# Inheritance C# Multilevel Inheritance C# Aggregation C# Member overloading C# Method Overriding C# Base

C# Polymorphism

C# Polymorphism C# Sealed

C# Abstraction

C# Abstraction C# Interface

C# Namespace

C# Namespace C# Access Modifiers C# Encapsulation

C# Strings

C# String

C# Misc

C# Design Patterns Dictionary in C# Boxing and Unboxing in C# Ref and Out in C# Serialization in C# Dispose and Finalize in C# CONSOLE LOG IN C# Get File extension in C# Insert query in c# Difference Between List and Dictionary in C# Getters and Setters in C# Extension Methods in C# Insert query in c# CONSOLE LOG IN C# Get File extension in C# Random.NextDouble() Method in C# Binary Search in C# Difference between Delegates and Interfaces in C# Double.IsFinite() Method in C# Index Constructor in C# Abstraction in C# Basic OOPS Concepts In C# Queue.CopyTo() Method in C# single.compareto() method in C# C# Throw Exception in Constructor DECODE IN C# file.setlastwritetimeutc() method in C# Convert Object to List in C# convert.ToSByte(string, IFormatProvider) Method in C# C# Declare Delegate in Interface console.TreatControl C As Input property in C# Copying the queue elements to 1-D Array in C# Array.Constrainedcopy() Method in C# C# in and out Char.IsLetterOrDigit() method in C# Debugging in C# decimal.compare() method in C# Difference between Console.Read and Console.Readline in C# Metadata in C# C# Event Handler Example Default Interface Methods in C# Difference between hashtable and dictionary in C# C# program to implement IDisposable Interface Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File C# Error Logging C# ENCRIPTION Can we create an object for Abstract Class in C# Console.CursorVisible in C# SortedDictionary Implementation in C# C# Hash Table with Examples Setting the Location of the Label in c# Collections in c# Virtual Keyword in C# Reverse of string in C# String and StringBuilder in C# Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File Difference between ref and out in C# Singleton Class in C# Const And Readonly In Csharp BinaryReader and BinaryWriter in C# C# Attributes C# Delegates DirectoryInfo Class in C# Export and Import Excel Data in C# File Class in C# FileInfo Class in C# How to Cancel Parallel Operations in C#? Maximum Degree of Parallelism in C# Parallel Foreach Loop in C# Parallel Invoke in C# StreamReader and StreamWriter in C# TextReader and TextWriter in C# AsQueryable() in C# Basic Database Operations Using C# C# Anonymous Methods C# Events C# Generics C# Indexers C# Multidimensional Indexers C# Multithreading C# New Features C# Overloading of Indexers Difference between delegates and events in C# Operator overloading in C# Filter table in C# C# Queue with Examples C# Sortedlist With Examples C# Stack with Examples C# Unsafe Code File Handling in C# HashSet in C# with Examples List Implementation in C# SortedSet in C# with Examples C# in Depth Delegates and Events in C# Finally Block in C# How to Split String in C# Loggers in C# Nullable Types in C# REVERSE A STRING IN C# TYPE CASTING IN C# What is Generics in C# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# Atomic Methods Thread Safety and Race Conditions in C# Parallel LINQ in C# Design Principles in C# Difference Between Struct And Class In C# Difference between Abstraction and Encapsulation in C# Escape Sequence Characters in C# What is IOC in C# Multiple Catch blocks in C# Appdomain in C# Call back methods in C# Change Datetime format in C# Declare String array in C# Default Access Specifier in c# Foreach in LINQ C# How to compare two lists in C# How to Convert String to Datetime in c# How to get only Date from DateTime in C# Ispostback in asp net C# JSON OBJECT IN C# JSON STRINGIFY IN C# LAMBDA FUNCTION IN C# LINQ Lambda Expression in C# Microservices in C# MSIL IN C# Reference parameter in C# Shadowing(Method hiding) in C# Solid principles in C# Static Members in C# Task run in C# Transaction scope in C# Type Conversion in c# Unit of Work in C# Unit Test Cases in c# User Defined Exception in c# Using Keyword in C# Var Keyword in C# What is gac in C#

How to Implement Interface in C#

What is an Interface?

A programming structure or syntax known as an interface enables the computer to -impose characteristics on an object (class). Let's take an example where we have classes for cars, scooters, and trucks. There should be a start_engine() action for each of these three classes. The domain of the interface is the requirement that each vehicle has a start_engine action; how each vehicle's "engine is started" is left to that specific class.

A contract exists between an interface and any class that implements it. An interface may contain events, attributes, or methods. It merely includes a declaration of its members; the class that implements the interface will provide the implementation of its members. Program maintenance is made simple by the interface. The interface's defined terms are listed below.

An interface can have members like as methods, properties, events, and indexers, much like a class. However, interfaces will only include the members' declarations. The class that implements the interface either explicitly or indirectly will be responsible for providing the members' implementation.

  • The interface keyword can be used to specify an interface.
  • Private members are not allowed on interfaces.
  • All interface members are publicly accessible by default.
  • Interfaces impose requirements on classes to implement their members.
  • Members of an interface are public and abstract by default.
  • Fields and constructors are not permitted in an interface.

There are two methods by which we can implement the interface, as follows:

1. Implicit

2. Explicit

Interface in C#:

The interface keyword in C# can be used to define an interface. Declarations of methods, properties, indexers, and events are all possible in an interface. It is unable to include instance fields, though.

Members of the interface are not subject to access modifiers. Starting with C #8.0, you can utilize virtual, abstract, sealed, static, extern, partial, private, protected, internal, and public modifiers under specific circumstances.

Syntax for Interface:

Declaration:

interface  Interface_name

{

    // declare methods

    //Declare properties

}

Implementation:

Class name: Interface_name

{

    //code

}

Example for declaring interface in C#:

interface IExample

{

    void Greetings();

    void Welcome(string text);

}

The interface IExample is declared in the above. (It is advised to begin an interface name with the letter "I" so that it is immediately apparent that this is an interface and not a class: Greetings() and Welcome(string) are the two methods available in the IExample interface.

Implementing Interface in C# using the class:

A class or a structure can implement one or more interfaces using a colon: When you deploy an interface, you must control its members.

Syntax:

class Class_name : Interface_name

{

  //methods and properties

}

Example:

public interface IShape

{

    double CalculateArea();

}

public class Circle : IShape

{

    public double Radius { get; set; }

    public Circle(double radius)

    {

        Radius = radius;

    }

    public double CalculateArea()

    {

        return Math.PI * Radius * Radius;

    }

}

public class Rectangle : IShape

{

    public double Width { get; set; }

    public double Height { get; set; }

    public Rectangle(double width, double height)

    {

        Width = width;

        Height = height;

    }

    public double CalculateArea()

    {

        return Width * Height;

    }

}

class Program

{

    static void Main(string[] args)

    {

        Circle circle = new Circle(5);

        Console.WriteLine("Area of Circle: " + circle.CalculateArea());

        Rectangle rectangle = new Rectangle(4, 6);

        Console.WriteLine("Area of Rectangle: " + rectangle.CalculateArea());

    }

}

Output:

How to Implement Interface in C#

Classes can implement an interface's members to abide by the contract defined by the interface in C#. To calculate the area of different geometric forms, for example, consider an interface called IShape that has a method called CalculateArea(). It is required of classes that implement IShape to supply their own CalculateArea() implementation.

The classes Circle and Rectangle in our example implement IShape. Every class has unique logic for computing the area using the formula for that shape. Polymorphism, which allows treating objects of different classes implementing the same interface interchangeably, is the benefit of using interfaces.

We first build instances of the Circle and Rectangle classes in the Main method and then call their CalculateArea() functions. They are called with the same interface reference even though they have separate implementations. This flexibility enables cleaner code because it simplifies maintenance, encourages code reuse, and makes testing easier. Furthermore, by allowing classes to rely on abstractions rather than specific implementations, interfaces encourage loose coupling and improve the scalability and extensibility of big software systems.

Explicit Implementation:

<InterfaceName>.<MemberName> can be used to implement an interface explicitly. When a class implements more than one interface, explicit implementation helps to make it easier to read and clear up any confusion. Coincidentally, it is also helpful if interfaces have the same method name.

Example Code:

using System;

public interface IMyInterface

{

    void MyMethod();

    string MyProperty { get; set; }

}

public class MyClass : IMyInterface

{

    private string _myProperty;

    void IMyInterface.MyMethod()

    {

        Console.WriteLine("Explicit implementation");

    }

    public string MyProperty

    {

        get

        {

            return _myProperty;

        }

        set

        {

            _myProperty = value;

        }

    }

}

class Program

{

    static void Main()

    {

        MyClass myClass = new MyClass();

        ((IMyInterface)myClass).MyMethod();

        myClass.MyProperty = "Hello, all!";

        Console.WriteLine(myClass.MyProperty);

    }

}

Output:

How to Implement Interface in C#

With a method called MyMethod and a property called MyProperty, the code defines an interface called IMyInterface. This interface is implemented by the class MyClass. MyMethod can be accessed by casting an instance of MyClass to IMyInterface since it is implemented using explicit interface implementation. By using MyClass instances, this technique conceals the method from direct access. In addition to being expressly implemented, MyProperty also has public accessors that enable direct access to the value kept in the private field _myProperty. An instance of MyClass is created in the Main method, and MyMethod is called after casting. The value of MyProperty is then printed once it has been set to "Hello, World!" By resolving naming conflicts and guaranteeing encapsulation, explicit implementation directs users to access interface members based on the interface type.

Multiple Interfaces Implementation:

Multiple interfaces can be implemented by a class or struct. It needs to offer every interface member's implementation.

using System;

public interface IShape

{

    double Area();

}

public interface IDrawable

{

    void Draw();

}

public class Circle : IShape, IDrawable

{

    private double _radius;

    public Circle(double radius)

    {

        _radius = radius;

    }

    public double Area()

    {

        return Math.PI * _radius * _radius;

    }

    public void Draw()

    {

        Console.WriteLine($"Drawing a circle with radius {_radius}");

    }

}

class Program

{

    static void Main()

    {

        Circle circle = new Circle(5.0);

        Console.WriteLine($"Area of the circle: {circle.Area()}");

        circle.Draw();

    }

}

Output:

How to Implement Interface in C#

Two interfaces, IShape and IDrawable, are implemented by the class Circle, as the code illustrates. The Area method, which determines a circle's area from its radius, must be used in order to use the IShape interface. The Draw function, which is in charge of informing the user that a circle with a given radius is being drawn, must be implemented in order to use the IDrawable interface.

The circle's radius is represented in the Circle class by the _radius field. The Area technique calculates the area using the formula Math: _ radius* PI* _ radius. The Draw method outputs a message using the Console.WriteLine with the radius value included.

A Circle instance with a radius of 5.0 is created in the Main function. In this instance, the area of the circle is calculated and shown by invoking the Area method. The drawing of the circle with its radius is then graphically shown by calling the Draw function.

Thus, the Circle class acquires the capability to calculate its area and display a visual representation by implementing both the IShape and IDrawable interfaces, demonstrating the flexibility of multiple interface implementation in C#.

Default Interface Methods:

using System;

interface IFile

{

    void ReadFile();

    void WriteFile(string text);

    void DisplayName()

    {

        Console.WriteLine("IFile");

    }

}

class FileInfo : IFile

{

    public void ReadFile()

    {

        Console.WriteLine("Reading File");

    }

    public void WriteFile(string text)

    {

        Console.WriteLine("Writing to file");

    }

}

public class Program

{

    public static void Main()

    {

        IFile file1 = new FileInfo();

        file1.ReadFile();

        file1.WriteFile("content");

        file1.DisplayName();

        FileInfo file2 = new FileInfo();

    }

}

Output:

How to Implement Interface in C#

The code defines the IFile interface, which has three members: the default DisplayName method that prints "IFile" to the console, ReadFile, and WriteFile. The FileInfo class, which implements IFile, provides concrete implementations of ReadFile and WriteFile.

A FileInfo instance called file1 is assigned to IFile in Main. This demonstrates the versatility of the interface by enabling direct calls to the default DisplayName method, ReadFile, and WriteFile. On the other hand, because of its type, file2, which is likewise an instance of FileInfo, is unable to invoke the default DisplayName function directly. This demonstrates how alternative method accessibility can be provided via interfaces based on the kind of object.

In essence, the code highlights the variety and polymorphism possible with C# interface implementation by showing how interfaces can have default implementations and how objects of various kinds can interact with interface members.the digital gap and connect residents of underprivileged areas to the internet.