Start C# here

Study C#.. Go ahead ! !

Monday, July 6, 2009

C# Interface

An interface is Created using the interface Keyword.
Here is an example for the Interface program.

----------------------------------------

interface IStudent
{
int RollNo
{
get;
set;
}
string Name
{
get;
set;
}

void DispDetails();

}
-----------------------------------------

The above one is an interface named IStudent. In this there are two Properties namely RollNo and Name. There is also a Method named DispDetails(). If you look at the codes... we don't have any definitions for these properties and Method(s).

Now, we will check how we can implement these codes inside a Class.

Exaple for C# Interface:-
-----------------------------------------
//Inheriting interface IStudent to class MySchool
class MySchool : IStudent
{
int iRollNo = 0;
string sName = "";]

//Definition for Property Declared inside the Interface
public int RollNo
{
get { return iRollNo; }
set { iRollNo = value; }
}
public string Name
{
get { return sName; }
set { sName = value; }
}
//Definition for Method Declared inside the Interface.
public void DispDetails()
{
Console.WriteLine("The RollNo is:{0} and the Name is {1}", iRollNo, sName);
}

static void Main(string[] args)
{
MySchool sObj = new MySchool();
sObj.RollNo = 12500;
sObj.Name = "SMILU";

sObj.DispDetails();
}
}

--------------------------------------------

In the above class MySchool we have Inherited the IStudent interface. So it's mandatory that we must write the Definitions for those methods and Properties declared inside the Interface.
Now, If in case we don't give a definition for any method or property declared inside the Interface, it will throw Error(s) and we will not be able to execute the program.

So, its necessary that there must be definition for all the methods and Properties which we have inside our Interface.

No comments: