You are on page 1of 24

http://www.vidyanidhi.

com/
ketkiacharya.net@gmail.com

Ketki Acharya
From: SM VITA ATC of CDAC
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Interface
• It says I know what to do but I don’t know how to do.So it has only
declaration of abstract method.
Eg. IMessage Interface may have method send_message. It knows that
send message method is required but how to send, it is not aware of.
Class SMS implement IMessage and provide concrete method public void
send_message and write code for send message through SMS
Class Email implement Imessage and provide concrete method public
send_message and write code for send message through email.
• A class can implement multiple interface.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Interface
C# allows you to fully utilize the one interface, multiple methods” aspect of polymorphism.
An interface has the following properties:
 An interface is like an abstract base class. Any class or struct that implements the interface must implement
all its members.
 An interface can't be instantiated directly. Its members are implemented by any class or struct that
implements the interface.
 Interfaces can contain events, methods and properties.
 Interfaces contain no implementation of methods.
 A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one
or more interfaces.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


• To implement an interface member, the corresponding member of the implementing class must be public,
non-static, and have the same name and signature as the interface member

• Interfaces declared directly within a namespace can be declared as public or internal and, just like classes
and structs, interfaces default to internal access.

• Interface members are always public because the purpose of an interface is to enable other types to access
a class or struct. No access modifiers can be applied to interface members.

Lets see example


• Interface Imessageservice has method sendmessage but it does not know how to send. Class
implementing this interface will decide how to perform task. Class Email can implement interface and
give body to sendmessage method of interface and will send message through Email. Same way class
Sms can implement interface and give body to sendmessage method of interface and will send message
through SMS. Thus Interface Know What to do. But do not know How to do. Class implementing this
interface will decide how to do.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Can we use interface reference to point to object of using System;
a class which has implemented interface? namespace InterfaceDemo
{//default it is internal
Yes. interface ImessageService
This is one more example of polymorphism. {//by default it is public
void SendMessage(string address);
using System; This will also resolves at runtime. }
namespace InterfaceDemo class Email : ImessageService
{//default it is internal {
interface ImessageService public void SendMessage(string address)
{//by default it is public {
void SendMessage(string address); Console.WriteLine("Sending Email to {0}",address);
} }
class Email : ImessageService }
{ class Sms : ImessageService
public void SendMessage(string address) {
{ public void SendMessage(string address)
Console.WriteLine("Sending Email to {0}", address); {
} Console.WriteLine("Sending Sms to {0}", address);
} }
abstract class Sms : ImessageService }
{ class Program
public abstract void SendMessage(string address); {
static void Main(string[] args)
} {
class Program Sms sobj=new Sms ();
{ Email eobj=new Email ();
static void Main(string[] args) sobj.SendMessage("Dac");
{ eobj.SendMessage("DBDA");
Email eobj = new Email();
eobj.SendMessage("DBDA"); ImessageService s1 = new Sms();
ImessageService s1 = new Email(); s1.SendMessage("Vita");
s1.SendMessage("Vita");
}
} }
}
USM’s Shriram Mantri Vidyanidhi
} Info Tech Academy
using System;
namespace InterfaceDemo
{
interface ImessageService
{
class Program void SendMessage(string address);
{ }
static void Main(string[] args)
class Email : ImessageService
{
{
Sms sobj=new Sms (); public void SendMessage(string address)
Email eobj=new Email (); {
Console.WriteLine("Sending Email to {0}",address);
Messageprovider.Send(sobj, "Vita"); }
Messageprovider.Send(eobj, "Vita"); }

} class Sms : ImessageService


{
}
public void SendMessage(string address)
} {
Observe static class Messageprovider Console.WriteLine("Sending Sms to {0}", address);
}
has method Send, this method says my job is to call method }
which method will get called will be decided at runtime
depending on what is being passed. If you pass Sms object it static class Messageprovider
will call SendMessage method of Sms class and if you pass {
object of Email class it will call SendMessage method of Email
class. public static void Send(ImessageService s, string add)
So this is polymprphism –many forms. {
s.SendMessage(add);

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


What if parent class method and child class implemented method name is same
using System;
namespace InterfaceDemo
{ //default it is internal
interface ImessageService
{ //by default it is public
void SendMessage(string address); warning CS0108:
} 'InterfaceDemo.Email.SendMess
class parent
{ public void SendMessage(string address) age(string)' hides inherited
{ Console.WriteLine("parent send message"); member
} 'InterfaceDemo.parent.SendMes
}
class Email :parent, ImessageService
sage(string)'. Use the new
{ keyword if hiding was
public void SendMessage(string address) intended.
{
Console.WriteLine("Sending Email to
{0}", address);
}
}
class Program
{
static void Main(string[] args)
{ Email eobj = new Email();
eobj.SendMessage("DBDA");
eobj.SendMessage("pp");
}
}
} USM’s Shriram Mantri Vidyanidhi Info Tech Academy
using System;
namespace InterfaceDemo
{ //default it is internal
interface ImessageService
{ //by default it is public
void SendMessage(string address);
}
class parent
{ public void SendMessage(string address)
{ Console.WriteLine("parent send message"); }
}
class Email :parent, ImessageService
{
//observeno implementation of SendMessag() still compile
}
Because same method is there in parent class
class Program
{
static void Main(string[] args)
{ Email eobj = new Email();
eobj.SendMessage("DBDA");
eobj.SendMessage("pp");
}
}
}
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
using System;

interface I1
{
void A();
}
interface I2
{
void A();
}

class C : I1, I2
{
public void chk()
{
I1 idemo = new C();
idemo.A();
}
public void A() //observe it is public and member of class
{
Console.WriteLine("C.A()");
}

void I1.A() //observe private and not member of class


{
Console.WriteLine("I1.A()");
}
}
class demo : C {

}
public class program
{
public static void Main()
{
C c = new C();
I1 i1 = c; //even if do not type cast will it work???? yes
I2 i2 = c;

i1.A(); //this will call private method void I1.A()


i2.A();
c.A();
I1 i3 = c;
i3.A();
demo d = new demo();
I1 i4 = d;

}
}
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Public and private implementation of interface
• One challenge with interfaces is that they may include methods that have the same signatures as existing class
members or members of other interfaces. Explicit interface implementations can be used to disambiguate
class and interface methods that would otherwise conflict. Explicit interfaces can also be used to hide the
details of an interface that the class developer considers private.

interface I1 This works fine if you want A() to do the


{ public class program
{ same thing in both interfaces. In most cases,
void A();
public static void Main()
} {
however, methods in different interfaces
interface I2 C c = new C(); have distinct purposes requiring wholly
{ I1 i1 = c;
void A(); I2 i2 = c; different implementations. This is where
} explicit interface implementations come in
i1.A();
class C : I1, I2
{
i2.A(); handy. To explicitly implement an interface
c.A();
public void A() } member, just use its fully qualified name in
{ }
Console.WriteLine("C.A()");You can call method through interface the declaration. A fully qualified interface
reference also.
}
Here class is aware of implementation of
name takes the form
} interface method. It is public
implementation of interface InterfaceName.MemberName

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


public class program
Explicitly implementation of interface {
public static void Main()
{
C c = new C();
interface I1
I1 i1 = c; //even if do not type cast will it work???? yes
{ void A(); I2 i2 = c;

} i1.A(); //this will call private method void I1.A()


i2.A();
interface I2 c.A();
{ void A(); }
}
}
i1.A();
class C : I1, I2
{
public void A() //observe it is public and member of class this will call private method void I1.A() and
{
Console.WriteLine("C.A()"); you can call only through interface reference
} only.
void I1.A() //observe private and not member of class If you try to call with class reference it will
{ able to call only public method public void A()
Console.WriteLine("I1.A()");
} As class is not aware of private void I1.A()
} method. This is called private implementation of
interface. This feature help us to solve
Output
situation where two interface has same method
I1.A() name. you can have different behavior for each
C.A() of this method by distinguishing public and
private implementation so there is no conflict.
C.A() USM’s Shriram Mantri Vidyanidhi Info Tech Academy
So in above example
When an interface method is explicitly implemented, it is no longer visible as a public member of the class. The only way to access it is through the interface. As
an example, suppose we deleted the implicit implementation of A() as shown in example
shown in Listing 4:

Listing 4. Class C does not implicitly implement A()

class C : I1,I2

{ void I1.A()

{ Console.WriteLine("I1.A()");

In this case we would get a compile error saying that C fails to implement I2.A(). We could fix this error by changing the first line to

class C : I1

but we'd get another compile error when trying to invoke A() as a member of C:

C c = new C();

c.A();

This time the compiler would report that class C does not contain a definition for method A(). We get the error because the explicit implementation of I1.A()
hides A() from the class. The only way to call I1.A() now is through C's I1 interface:

C c = new C();

I1 i1 = c;

i1.A();

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Following are some of the interface available in .net frame work
1. Icloneable with Clone() abstract method

2. Icomparable with abstract method public int CompareTo(object obj)


3. Icomparer with abstract method int Compare(object o1, object o2);
4. Ienumerable with abstract ,method GetEnumerator()
5. Ienumerator with three abstract method
1. object Current { get; },
2. bool MoveNext();
3.void Reset();

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Memberwise clone class Program
{
public class Point : ICloneable static void Main( string[] args )
{ public int X { get; set; } {
public int Y { get; set; }
Console.WriteLine("***** Fun with Object
public Point( int xPos, int yPos ) Cloning *****\n");
{ Console.WriteLine("Cloned p3 and stored new
X = xPos; Y = yPos; Point in p4");
} Point p3 = new Point(100, 100);
public Point() { } Point p4 = (Point)p3.Clone();
// Override Object.ToString().
public override string ToString()
{ return string.Format("X = {0} Y = {1} ",X, Y); Console.WriteLine("Before modification:");
} Console.WriteLine("p3: {0}", p3);
// Return a copy of the current object. Console.WriteLine("p4: {0}", p4);
// Now we need to adjust for the PointDescription Console.WriteLine("p3: {0}", p3.GetHashCode());
member. Console.WriteLine("p4: {0}", p4.GetHashCode());
public object Clone()
{ return this.MemberwiseClone();
p4.X = 99;
} p4.Y = 99;
} p3 Console.WriteLine("After modification:");
X=100 Console.WriteLine("p3: {0}", p3);
Console.WriteLine("p4: {0}", p4);
Y=100
Console.ReadLine();
p4 }
}
X=100 99
Y=100 99

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


p3
Member wise
X=100
clone is shallow copy
Jane public class program
Y=100 {
public static void Main()
desc hello
{
Console.WriteLine("***** Fun with Object Cloning *****\n");
Console.WriteLine("Cloned p3 and stored new Point in p4");
p4 X=100 99 Point p3 = new Point(100, 100,"Jane");
Point p4 = (Point)p3.Clone();
Y=100 99
desc Console.WriteLine("Before modification:");
Console.WriteLine("p3: {0}", p3);//100 100 Jane
// The Point now supports "clone-ability."
public class Point : ICloneable Console.WriteLine("p4: {0}", p4);//100 100 Jane
{ Console.WriteLine("p3: {0}", p3.GetHashCode());
public int X { get; set; }
Console.WriteLine("p4: {0}", p4.GetHashCode());
public int Y { get; set; }
public PointDescription desc = new PointDescription();
p4.X = 99;
public Point( int xPos, int yPos, string petName ) p4.Y = 99;
{ p4.desc.PetName ="hello";
X = xPos; Y = yPos;
desc.PetName = petName;
Console.WriteLine("After modification:");
} Console.WriteLine("p3: {0}", p3); //100 100 hello
Console.WriteLine("p4: {0}", p4);//99 99 hello
// Override Object.ToString().
public override string ToString()
Console.ReadLine();
{
return string.Format("X = {0}; Y = {1}; Name = {2};\n", X, Y, //this will give error as class is not aware of I1.A since it
desc.PetName); is explicit implimentation
} }
// Return a copy of the current object. // This class describes a point.
}
// Now we need to adjust for the PointDescription member. public class PointDescription
public object Clone() {
{ public string PetName { get; set; }
// First get a shallow copy.

return this.MemberwiseClone();
public PointDescription()
} {
}
PetName = "No-name";
}
USM’s Shriram Mantri Vidyanidhi Info Tech
} Academy
How to achieve deep copy

public object Clone()


{ p3
// First get a shallow copy.
X=100
Point newPoint = (Point)this.MemberwiseClone();
Y=100 Jane
// Then fill in the gaps.
desc
PointDescription currentDesc = new PointDescription();
currentDesc.PetName = this.desc.PetName;
newPoint X=100 99
newPoint.desc = currentDesc;
Y=100 99 "No-name"
desc
return newPoint;
Jane
hello
} currentDesc

Point p4 = (Point)p3.Clone();

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


using System;
namespace ICloneableExample Install-Package System.Data.SqlClient -Version 4.8.3
{
class Program
{
static void Main( string[] args )
{
Console.WriteLine("***** A First Look at Interfaces *****\n");

// All of these classes support the ICloneable interface.


string myStr = "Hello";
Console.WriteLine(myStr.GetHashCode());
OperatingSystem unixOS = new OperatingSystem(PlatformID.Unix, new Version());
Console.WriteLine(unixOS.GetHashCode());
System.Data.SqlClient.SqlConnection sqlCnn = new System.Data.SqlClient.SqlConnection();
Console.WriteLine(sqlCnn.GetHashCode());
// Therefore, they can all be passed into a method taking ICloneable.
CloneMe(myStr);
CloneMe(unixOS);
CloneMe(sqlCnn);
Console.ReadLine();
}

private static void CloneMe( ICloneable c )


{
// Clone whatever we get and print out the name.
object theClone = c.Clone();
Console.WriteLine(theClone.GetHashCode());
Console.WriteLine("Your clone is a: {0}", theClone.GetType().Name);
}
} USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Icomparer===public int Compare(object x, object y)
Public static void sort( Object [] a, IComparer
{
using System.Text;
public class employee Int a=comparer. Compare( a[0],a[1] );
namespace sort_obj
{ if(a>0)
{ public string Name { get; set;{ }
class Program public float Salary { get; set; }
Swap(x,y);
{ }
static void Main(string[] args) }
{
employee[] p=new employee [5];
p[0] = new employee() { Name = "Raj", Salary = System.Collections;
50000 }; class Data_sort:IComparer }
p[1] = new employee() {Name="Anita",Salary =80000 }; {
p[2] = new employee() {Name="Mona",Salary =30000 }; // Test the pet name of each object.
public int Compare(object x, object y)
p[3] = new employee() { Name = "Geeta", Salary =
90000 }; {
p[4] = new employee() { Name = "Ravi", Salary =
70000 }; employee t1 = x as employee;
employee t2 = y as employee;
if (t1 != null && t2 != null)
Array.Sort(p,new Data_sort()); return String.Compare(t1.Name, t2.Name);
else
foreach (employee e in p) throw new ArgumentException("Parameter is not a Emp!");
Console.WriteLine("{0}", e.Name);
}
Console.ReadKey(); } Ankita
}
} Anita
} A A B
-A -B - A
0 -1 1
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
Icomparable=== public int CompareTo(object obj)
Public void Sort(Object[] obj)
public class employee:IComparable
using System;
{ {
namespace sort_obj
public string Name { get; set; }
{ class Program public float Salary { get; set; } obj[0].CompatrTo(obj[1])
{
public int CompareTo(object obj)
static void Main(string[] args) {

{ employee
if (temp
temp = obj as employee;
!= null)
}
employee[] p=new employee [5]; {
p[0] = new employee() { Name = "Raj", Salary = //if (this.Salary > temp.Salary)
50000 }; // return 1;
//if (this.Salary < temp.Salary)
p[1] = new employee() {Name="Anita",Salary =80000 }; // return -1;
// else
p[2] = new employee() {Name="Mona",Salary =30000 };
// return 0;
p[3] = new employee() { Name = "Geeta", Salary = return this.Salary.CompareTo(temp.Salary);
90000 }; }
else
p[4] = new employee() { Name = "Ravi", Salary = 70000 }; throw new ArgumentException("Parameter is not a employee!");
// throw new NotImplementedException();
Array.Sort(p);

foreach (employee e in p) }

Console.WriteLine("{0} {1}", e.Salary, /*public int CompareTo(object obj)


e.Name ); {
employee temp = obj as employee;
Console.ReadKey(); if (temp != null)
{
} return this.Name.CompareTo(temp.Name);
}
else
throw new ArgumentException("Parameter is not a employee!");
}
}*/
}
}

USM’s Shriram Mantri


} Vidyanidhi Info Tech Academy
Ienumerable=== public IEnumerator GetEnumerator()
class Program
{ static void Main(string[] args)
{ public class employee
company cp = new company(); {
public string Name { get; set; }
foreach (employee ep in cp) public float Salary { get; set; }
Console.WriteLine(ep.Name); }
public class company:IEnumerable
Console.ReadKey(); {
employee[] e=new employee[5];
// Manually work with IEnumerator.
IEnumerator i = cp.GetEnumerator(); public company ()
i.MoveNext(); {
employee emp = (employee )i.Current; e[0] = new employee() { Name = "Raj", Salary = 50000 };
e[1] = new employee() { Name = "Anita", Salary = 80000 };
Console.WriteLine("{0} is getting sal of rs{1} ", e[2] = new employee() { Name = "Mona", Salary = 30000 };
emp.Name, emp.Salary ); e[3] = new employee() { Name = "Geeta", Salary = 90000 };
e[4] = new employee() { Name = "Ravi", Salary = 70000 };
Console.ReadKey();
}
while (i.MoveNext())
{ public IEnumerator GetEnumerator()
{
employee myemp = (employee)i.Current; return e.GetEnumerator();
//throw new NotImplementedException();
Console.WriteLine("{0} sal {1}",myemp.Name, }
myemp.Salary);
} }
Console.ReadLine();
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
New Company()

cp
e 0 1 2 3 4

Name = "Raj",
Salary = 50000

Name = Name =
"Anita", "Mona",
Salary = Salary =
80000 30000

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


using System;
using System.Collections;
class ProductEnumerator : IEnumerator
{
namespace IEnumerableAndIEnumerator int index = -1;
{ string[] ProductList;
class Product : IEnumerable
{ public ProductEnumerator(ref string[] productList)
{
public string[] ProductList = new string[5]; ProductList = productList;
int index = 0; }

public void AddProduct(string product) public object Current


{ {
ProductList[index++] = product; get { return ProductList[index]; }
}
}
public void RemoveProduct(int index) public bool MoveNext()
{ {
ProductList[index] = ""; index++;
} return index >= ProductList.Length ? false : true;
}
public IEnumerator GetEnumerator()
public void Reset()
{
{
return new ProductEnumerator(ref ProductList); index = -1;
} }
class Program }
{ }
static void Main(string[] args)
{
Product product = new Product();
product.AddProduct("Product A");
product.AddProduct("Product B");
product.AddProduct("Product C");

foreach (string iteration in product)


{
Console.WriteLine(iteration);
}

Console.ReadKey(); USM’s Shriram Mantri Vidyanidhi Info Tech Academy


0 1 2 3 4
New Product:IEnumerable Product A Product B Product c

ProductList ProductEnumerator : IEnumerator


product
Index=0 GetEnumerator ProductList
public object Curre
AddProduct Index=-1

public bool MoveNex

REmoveProduct

public void Reset()

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


using System;
using System.Collections;

public class employee


{
public string Name { get; set; }
public float Salary { get; set; }
}
public class contractor
{
public int id { get; set; }
public float Salary { get; set; }
}

public class company : IEnumerable


{
public employee[] e = new employee[5];
public contractor[] c = new contractor[2];
public company()
{
e[0] = new employee() { Name = "Raj", Salary = 50000 };
e[1] = new employee() { Name = "Anita", Salary = 80000 };
e[2] = new employee() { Name = "Mona", Salary = 30000 };
e[3] = new employee() { Name = "Geeta", Salary = 90000 };
e[4] = new employee() { Name = "Ravi", Salary = 70000 };
c[0] = new contractor() { id = 1, Salary = 70000 };
c[1] = new contractor() { id = 2, Salary = 70000 };

public IEnumerator GetEnumerator()


{
return GetEnumerator();
//throw new NotImplementedException();
}

class Program
{
static void Main(string[] args)
{
company cp = new company();

foreach (employee ep in cp.e)


Console.WriteLine(ep.Name);
foreach (contractor ep in cp.c)
Console.WriteLine(ep.id);
Console.ReadKey(); USM’s Shriram Mantri Vidyanidhi Info Tech Academy

You might also like