Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# | Type.GetInterfaces() Method
Next article icon

C# | How to use Interface References

Last Updated : 11 Jun, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
In C#, you are allowed to create a reference variable of an interface type or in other words, you are allowed to create an interface reference variable. Such kind of variable can refer to any object that implements its interface. An interface reference variable only knows that methods which are declared by its interface declaration. It does not allow accessing any other variables or methods that might be supported by the objects. This concept is similar when you use a parent class reference to access a child class object. Below are the examples to illustrate the concept of Interface References: Example 1: CSharp
// C# program to illustrate the  // concept of Interface References using System;  // interface declaration public interface Race {          // declaration of abstract methods of     // interface that will be implemented      // by the class which inherits the interface     void Speed(int s);     void Distance(int d); }  // class implementing interface public class Person1 : Race {          int sp1, di1;          // abstract method of      // Race interface     public void Speed(int p1s) {                  sp1 = p1s;         Console.WriteLine("Speed Method implemented by Person1");              }          // abstract method of      // Race interface     public void Distance(int p1d) {                  di1 = p1d;         Console.WriteLine("Distance Method implemented by Person1");              }          // method of class Person1     public void display1() {                  Console.WriteLine("The Speed of 1st person is: "+sp1);         Console.WriteLine("The distance covered by 1st person is: "+di1);              }      }  // class implementing interface public class Person2 : Race {          int sp2, di2;          // abstract method of      // Race interface     public void Speed(int p2s) {                  sp2 = p2s;         Console.WriteLine("Speed Method implemented by Person2");              }          // abstract method of      // Race interface     public void Distance(int p2d) {                  di2 = p2d;         Console.WriteLine("Distance Method implemented by Person2");              }          // method of class Person2     public void display2() {                  Console.WriteLine("The Speed of 2nd person is: "+sp2);         Console.WriteLine("The distance covered by 2nd person is: "+di2);              }      }  // Driver Class public class GFG {          // Main method     public static void Main(String []args) {                  // creating an instance of Person1 class         Person1 obj1 = new Person1();                  // creating an instance of Person2 class         Person2 obj2 = new Person2();                  // creating an Reference          // of interface Race         Race r;                  // ----- For Person1 Class ----------                  // assigning Person1 object 'obj1'         // to interface Reference 'r'         r = obj1;                  // Now you can access the abstract method         // of Race interface which are implemented         // by class Person1         r.Speed(10);         r.Distance(50);          // if you will try to call display1()          // method using 'r' it will give error         //r.display1();                  // calling the display1()          // method of Person1 Class         obj1.display1();                  // ----- For Person2 Class ----------                  // assigning Person2 object 'obj2'         // to interface Reference 'r'         r = obj2;                  // Now you can access the abstract method         // of Race interface which are implemented         // by class Person2         r.Speed(15);         r.Distance(45);          // if you will try to call display2()          // method using 'r' it will give error         //r.display2();                  // calling the display1()          // method of Person1 Class         obj2.display2();              }      } 
Output:
  Speed Method implemented by Person1  Distance Method implemented by Person1  The Speed of 1st person is: 10  The distance covered by 1st person is: 50  Speed Method implemented by Person2  Distance Method implemented by Person2  The Speed of 2nd person is: 15  The distance covered by 2nd person is: 45  
Explanation: In above example, we have an interface named Race an two classes Person1 and Person2 which are implementing the methods of the interface. The Person1 class has its own method named display1() and similar Person2 class its own method display2() which cannot be called by using interface reference. In order to call the methods using interface reference(here r is interface reference), you have to assign to class object to it. Like if you are assigning Person1's object obj1 to r i.e. r = obj1; then you call the Speed() and Distance() methods that are implemented by the Person1 class. In order to call display1() method, you must have to use obj1. Similarly using r = obj2; we are calling methods of Person2 class. Example 2: CSharp
// C# program to illustrate the  // concept of Interface References using System;  // interface declaration interface Vehicle {      // all are the abstract methods.     void changeGear(int a);     void speedUp(int a);     void applyBrakes(int a);     void printStates(); }  // class implements interface class Bicycle : Vehicle {      int speed;     int gear;      // to change gear     public void changeGear(int newGear)     {          gear = newGear;     }      // to increase speed     public void speedUp(int increment)     {          speed = speed + increment;     }      // to decrease speed     public void applyBrakes(int decrement)     {          speed = speed - decrement;     }      public void printStates()     {         Console.WriteLine("speed: " + speed + " gear: " + gear);     } }  // Driver Class class GFG {      // Main Method     public static void Main(String[] args)     {          // creating an instance of Bicycle         Bicycle bicycle = new Bicycle();          // Creating interface references         Vehicle obj;          // assigning Bicycle object 'bicycle'         // to interface Reference 'obj'         obj = bicycle;          // calling the abstract methods          // implemented by class Bicycle         obj.changeGear(4);         obj.speedUp(5);         obj.applyBrakes(2);          Console.WriteLine("Bicycle Present State:");          // calling the method of class Bicycle          obj.printStates();     } } 
Output:
  Bicycle Present State:  speed: 3 gear: 4  
Explanation: In the above example, Vehicle is an interface and Bicycle class implements this interface. Here obj is declared to be a reference to Vehicle interface in the Main() method. Now this obj is used to refer the object bicycle of the Bicycle class.

Next Article
C# | Type.GetInterfaces() Method
author
ankita_saini
Improve
Article Tags :
  • C#
  • CSharp-OOP
  • CSharp-Interfaces

Similar Reads

  • C# | Type.GetInterface() Method
    Type.GetInterface() Method is used to gets a specific interface implemented or inherited by the current Type. GetInterface(String) Method This method is used to search for the interface with the specified name. Syntax: public Type GetInterface (string name); Here, it takes the string containing the
    4 min read
  • C# | Type.GetInterfaces() Method
    Type.GetInterfaces() Method is used to get all the interfaces implemented or inherited by the current Type when overridden in a derived class. Syntax: public abstract Type[] GetInterfaces ();Return Value: This method returns an array of Type objects representing all the interfaces implemented or inh
    2 min read
  • C# | Multiple inheritance using interfaces
    Introduction:Multiple inheritance refers to the ability of a class to inherit from multiple base classes. C# does not support multiple inheritance of classes, but it does supportmultiple inheritance using interfaces. An interface is a collection of abstract methods that a class can implement to prov
    7 min read
  • Demonstrating Transactions Using Interface Through C#
    The interface is a special class in which we can declare all of our methods. Here in this problem, we are going to create an interface in which we are going to declare all of the required implementations which is necessary for transaction management. Here in this article, we are going to see how rea
    2 min read
  • C# | Inheritance in interfaces
    C# allows the user to inherit one interface into another interface. When a class implements the inherited interface then it must provide the implementation of all the members that are defined within the interface inheritance chain.Important Points: If a class implements an interface, then it is nece
    3 min read
  • C# | How to Implement Multiple Interfaces Having Same Method Name
    Like a class, Interface can have methods, properties, events, and indexers as its members. But interface will contain only the declaration of the members. The implementation of interface's members will be given by the class who implements the interface implicitly or explicitly. C# allows the impleme
    4 min read
  • Default Interface Methods in C# 8.0
    Before C# 8.0 interfaces only contain the declaration of the members(methods, properties, events, and indexers), but from C# 8.0 it is allowed to add members as well as their implementation to the interface. Now you are allowed to add a method with their implementation to the interface without break
    5 min read
  • C# Interface
    An interface is defined using the interface keyword, similar to a class. An Interface is a blueprint that outlines a group of methods, properties, events, or indexers that a class or struct must implement. Unlike classes, it contains only the declaration of the members. The implementation of the int
    3 min read
  • C# Program To Implement IDisposable Interface
    IDisposable is an interface defined in the System namespace. It is used to release managed and unmanaged resources. Implementing IDisposable interface compels us to implement 2 methods and 1 boolean variable -  Public Dispose() : This method will be called by the consumer of the object when resource
    4 min read
  • Delegates vs Interfaces in C#
    A Delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered. Example: C/C+
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences