C# Interface

PHPz
PHPzOriginal
2024-09-03 15:30:00561browse

Interface, in C#, is a keyword, which holds a group of abstract methods and properties, which are to be implemented or used by an abstract or non-abstract class. Defining the methods are properties inside an interface which makes them public and abstract by default.

In simplest terms, An Interface is like a Contract, where every member or component included in the body has to follow the contract, it defines what must be done. The interface does not contain any fields and is always defined by the use of the keyword “interface”.

Syntax:

Syntax starts with the interface keyword followed by the name for the interface and then the body.

interface <name_for_interface>
{
//abstract methods
//abstract properties.
}

As you can see, we have our standard syntax for Interface in C#, which begins with the ‘interface’ keyword then the name for interface and then abstract methods and properties inside the body. In C#, multiple interfaces can be implemented and used, inside a class or a struct. These interfaces can hold various methods, indexers, properties and also events as members.

Why do we need C# Interface?

Basically we have understood that there is no specific functionality inside an interface, if it is so, then why do we need Interface?

When to use Interface?

  • Security: When we have to simply hide some features and have to use those later. It is essential to hide a few details while only showing the details important to the user.
  • Multiple Inheritance: In c#, one class can inherit from a simple parent class, inheriting all its features. Multiple Inheritance is not supported in C# for the simple reason to not make C# complex. But with the use of an interface, multiple interfaces can be implemented into a single class.

C# Interface typically includes the following elements:

  1. Declaration – In C#, an interface is a contract that defines a set of method signatures, properties, events, or indexers. It contains no implementation and serves as a blueprint for classes to adhere to. Classes that implement an interface must provide concrete implementations for all the members declared in the interface.
  2. Members – interface members are methods, properties, events, and indexers declared within an interface. They define a contract that implementing classes must adhere to, ensuring consistent behavior across various classes. Implementing classes must provide concrete implementations for these members, promoting code consistency, and enabling polymorphism and code reuse.
  3. Implementation – A class that implements an interface must provide an implementation for all the members declared in the interface. The class can explicitly specify that it implements an interface using the : interfaceName syntax. For example:
    public class MyClass : IMyInterface
    {
    public void Method1()
    {
    // Method implementation
    }public string Property1 { get; set; }
    
    public event EventHandler Event1;
    }
  4. Multiple Inheritance : C# supports multiple inheritance through interfaces. A class can implement multiple interfaces, allowing it to inherit multiple sets of method signatures without the complexities associated with multiple inheritance of implementation. This enables greater flexibility in designing classes while avoiding the diamond problem inherent in traditional multiple inheritance.
  5. Interface Inheritance: In C#, interface inheritance allows a derived interface to inherit the method signatures defined in one or more base interfaces. A class implementing the derived interface must provide implementations for all the inherited methods. This enables the creation of hierarchies of interfaces, promoting code reuse and flexibility in object design.

Examples of C# Interface

Now that we have understood what interface is and its need. Let’s demonstrate a simple example of C# code with interface implementation.

Example #1

Program implements Interface and prints a simple statement.

Code:

using System;
namespace MyApplication {
interface SampleInterface {
void InterfaceMethod();
}
class Int_Example : SampleInterface
{
public void InterfaceMethod() {
Console.WriteLine("\nThis is simple example of Interface in C#.");
}
}
class Program {
static void Main(string[] args) {
Int_Example myInterface = new Int_Example();
myInterface.InterfaceMethod();
Console.Read();
}
}
}

Code Interpretation: Starting with the use and namespace, a basic interface is generated as a SampleInterface that has a single method in its body. This method inside an interface does not have any particular body. Then we have our new class which is to implement the interface we created. Created with, class keyword followed by the class name and then implementing the interface with colon symbol followed by the interface name. Inside our class Int_Example, we have our earlier created interface method, which was bodiless by then, now we have added the simple print statement, which says, ” This is a simple example of Interface in C#.”

Then begins our mail class, namely Program, with the static void main statement. Inside our main class, we have created a new object for our Int_Example class which inherits interface. The new object is created and to the next line, our method created earlier is called up. Finally, our newly created object will call the earlier created method and the body inside that method will be executed here. With Console.Read(); the program will wait for user input before exiting.

Output:

C# Interface

Upon successful compilation and execution, the program must simply print the statement: “This is a simple example of Interface in C#.”

Example #2

Arithmetic operations using the interface.

Code:

using System;
namespace arth_interface {
public interface SampleInterface {
void sam_add(int a, int b);
void sam_sub(int a, int b);
void display();
}
class interface_class : SampleInterface {
int x, y;
public void sam_add(int a, int b) {
int m, n;
m = a;
n = b;
x = m + n;
}
public void sam_sub(int a, int b) {
int m, n;
m = a;
n = b;
y = a - b;
}
public void display() {
Console.WriteLine("Added Value is:" + x);
Console.WriteLine("Subtracted value is:" + y);
}
}
class arth_interface {
static void Main(string[] args) {
interface_class obj_interface_class = new interface_class();
int fnumber, snumber;
Console.WriteLine("Please Enter 1st Number to perform Addition and Subtraction:");
fnumber = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Now 2nd Number to perform Addition and Subtraction:");
snumber = Convert.ToInt16(Console.ReadLine());
obj_interface_class.sam_add(fnumber, snumber);
obj_interface_class.sam_sub(fnumber, snumber);
obj_interface_class.display();
Console.ReadKey();
}
}
}

Code Interpretation: Similar to our first example, we have used and namespace statements, followed by the interface and its body with methods. We have two basic methods for addition and subtraction with void as return type, two integers inside every method, respectively. Next, we have our class which implements our interface.

We’ve declared two integers and then we have our first method to calculate addition. Here is the operation that needs to be done for addition and the same is for the subtraction. Then we have our display method, which consists of two print statements, printing addition and subtraction values of the numbers passed.

Finally, we have our class with the main method, where we initially created an object for our interface. Then the program prints “Please Enter the 1st Number to perform Addition and Subtraction:”, where the user inputs a first number and the later second number, for the purpose of calculations. With the object created earlier, the program calls the add and sub-methods from the interface and the same operations are done. At last, we have our display method, which displays our results as defined in the display method and ReadKey(); method holds up our program until any key is pressed.

Output:

C# Interface

Advantages

Below are some of the advantages given.

  • One of the major advantages of Interface in C# is a better alternative to implement multiple inheritances.
  • The interface enables the plug-and-play method.
  • Complete Abstraction can be achieved by the implementation of Interface.
  • Along with making our code easy to maintain, concept loose coupling can be achieved.

Conclusion

We have understood what Interface in C# is. The proper syntax for an interface along with an explanation. To wrap it up, Interfaces in C# are a way to fill the emptiness of multiple inheritances in the language. Later we learned why do we actually need the interface in C# followed by the examples to demonstrate the understanding of the interfaces. The first example was to demonstrate simple use of interface while with the second example we implemented arithmetic operations, followed by Code Interpretation and output screenshot.

The above is the detailed content of C# Interface. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:C# DelegatesNext article:C# Delegates