Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

Understanding C# Interfaces: Definition, Example, and Practical Use

What is a C# Interface?

An interface in C# is a contract that defines a set of members—methods, properties, events, or indexers—that a class or struct must implement. It specifies the what but not the how, allowing different types to expose the same set of operations while keeping implementation details hidden.

Interfaces promote loose coupling, enable polymorphism, and support multiple inheritance of type definitions, which is essential for writing testable, maintainable code.

Concrete Example

Below is a minimal console program that demonstrates how an interface is declared, implemented, and used.

using System;
namespace DemoApplication
{
    // 1. Declare the contract
    interface IGuru99Interface
    {
        void SetTutorial(int id, string name);
        string GetTutorial();
    }

    // 2. Implement the contract
    class Guru99Tutorial : IGuru99Interface
    {
        private int tutorialId;
        private string tutorialName;

        public void SetTutorial(int id, string name)
        {
            tutorialId = id;
            tutorialName = name;
        }

        public string GetTutorial() => tutorialName;

        static void Main(string[] args)
        {
            var tutor = new Guru99Tutorial();
            tutor.SetTutorial(1, ".Net by Guru99");
            Console.WriteLine(tutor.GetTutorial());
            Console.ReadKey();
        }
    }
}

Understanding C# Interfaces: Definition, Example, and Practical Use

Key takeaways:

  1. Interfaces are declared with the interface keyword.
  2. They contain only signatures; implementation is provided by the class.
  3. A class that implements an interface must define all its members, ensuring compliance with the contract.

Why Use Interfaces?

Summary

An interface specifies the operations a type must support. By implementing an interface, a class guarantees adherence to that contract, facilitating clean architecture and scalable design.

C Language

  1. C++ Operators Explained: Types, Examples, and Sample Programs
  2. C++ Classes & Objects: A Practical Guide with Code Examples
  3. C# Abstract Classes: A Practical Tutorial with Code Examples
  4. C# Serialization & Deserialization: A Practical Example
  5. Understanding Java Classes and Objects: Clear Concepts, Practical Examples
  6. Polymorphism in Java: A Comprehensive Guide with Practical Examples
  7. Java Abstraction: Mastering Abstract Classes, Methods, and Practical Examples
  8. Java Interfaces Explained: How to Define and Implement Them with Practical Examples
  9. Interface vs Abstract Class in Java: How to Choose the Right Abstraction
  10. Master Java Reflection API: A Practical Guide with Code Examples