Console C#.Net Tutorial

Visual Studio.NET IDE

Define C#.NET

C# Comment

C# Variables

C# Data Types

C# Escape Sequence

C# Operators

Format String

Operator Precedence

C# Keywords

Constant Variable

Type Conversion

Flow Control

C# Arrays

C# Character

C# Strings

User-Define Methods

Variable Scope

C# Enumerations

C# Structure

C# Exception Handling

Object Oriented Programming

C# Classes

Constructor & Destructor

C# Inheritance

C# Polymorphism

C# Operator Overloading

C# Method Overriding

C# Interface

Abstract Classes & Methods

Sealed Classes, Methods

C# Properties

C# Indexer

C# Delegates

C# Generics

C# Collection

C# ArrayList

C# Stack

C# Queue

C# HashTable

C# SortedList

Page Stats

Visitor: 254

C#.Net Interface

C# interface contains only the declaration of the methods, properties, and events, but not the implementation, it is the responsibility of the class that implements the interface and define all the members of the interface. Interfaces are declared in a same way as class declaration, but a few differences:

  1. Interface is declared with the keyword interface.
  2. Interface can't be instantiated as a class.
  3. Interface can't contain any code that implements its member.
  4. An Interface cannot include private members.
  5. An Interface cannot be abstract and sealed as a class.

A class can support multiple interfaces and multiple classes can support the same interface. If a class implements an interface it has to define all its members otherwise class has to be declared as abstract.

Syntax: Interface declaration

interface IMyInterface
{
	// interface members1;
	// interface members2;
}

Interface inheritance is also possible like class inheritance.

Example 1: Implements a interface in a class.

interface circle
{
    float area(float r);
}
class example : circle
{
    public float area(float r)
    {
        float a = 3.14f * r * r;
        return a;
    }
}
class Program
{
    static void Main(string[] args)
    {
        example ex = new example();
        circle cir=ex;
        float f = cir.area(5.0f);
        Console.WriteLine(f);
        Console.Read();
    }
}

Example 2: To implements multiple interfaces

interface ICircle
{
    float circle(float r); //abstract method declaration to find area of circle
}
interface IRectangle
{
	int rectangle(int l, int b); //abstract method declaration to find area of rectangle
}
class Area : ICircle, IRectangle
{
	public float circle(float r) //define
	{
		float a = 3.14f * r * r;
		return a;
	}
	public int rectangle(int l, int b)
	{
		int a = l * b;
		return a;
	}
}
class Program
{
	static void Main(string[] args)
	{
		Area obj = new Area();
		ICircle cir = obj;
		//float a = obj.area(5.5f);
		float a = cir.circle(5.5f);
		Console.WriteLine("Area of circle = " + a);

		IRectangle rec = obj;
		int a2 = rec.rectangle(10, 20);
		Console.WriteLine("Area of rectangle = " + a2);

		Console.Read();
	}
}
Advertisement