Wednesday, November 19, 2008

Interface Definition with Example

Definition:

  • An Interface is a reference type and it contains only abstract members.
  • Interface's members can be Events,Methods,Properties and Indexers.But the Interface contains only declaration for its members.
  • Any implementation must be placed in class that realizes them.
  • All member declaration inside interface are implicitly public.

Limitations:
  • The Interface can't contain constants, data fields, constructors, destructors and static members.
  • A very important point to be remembered about c# interfaces is, if some interface is inherited, the program must implement all its declared members. Otherwise the c# compiler throws an error.
Example:

using System;
using System.Collections.Generic;
using System.Text;

namespace Interface
{
interface Maths
{
int Add
{
get;
set;
}
string Concatenate
{
get;
set;
}
}
class Program:Maths
{
public int Add
{
get
{
return c=a+b;
}
set
{
c = value ;
}

}
public int c ;
public int a = 12;
public int b = 23;
public string Concatenate
{
get
{
return Total=s+g ;
}
set
{
Total = value ;
}
}
public string Total;
public string s = "Hem";
public string g = "nath";

static void Main(string[] args)
{
Maths mat;
mat = new Program();
Console.WriteLine(mat.Add);
Console.WriteLine(mat.Concatenate);
Console.ReadLine();

}
}
}

Now the above code has created a c# class Program(Class) that inherits from Maths (Interface) c# interface and implement all its members.


No comments: