search

C# Interface

Sep 03, 2024 pm 03:30 PM
c#c# tutorial

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.
}</name_for_interface>

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
Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!