Monday, September 14, 2009

Passing Interface & object to Method in .Net

in this post i will illustrate the difference between passing object and interface to method, suppose that we have currency class and implement the interface ICurrency ...... Let's go through the code to discover the difference

public static decimal ExchangeRate(ICurrency FromCurrency, ICurrency targetCurrency)

{

}

public static decimal ExchangeRate(Currency FromCurrency, Currency targetCurrency)

{

}

the difference is so simple -->Using ICurrency in the method signature will allow you to pass any object of a class that implements ICurrency, while using Currency in the method signature will only allow you to pass a Currency object.

For example: If you only want the method signature to accept a System.Data.SqlClient.SqlDataReader object, then you would use that. However, if you wanted it to accept any DataReader object you would use System.Data.IDataReader since all DataReader classes implement System.Data.IDataReader. That is one of the nice things about interfaces