What is Interface?
An interface is collection of methods, properties, indexers and events with only signatures. Means In interface Methods, properties, indexers and events do not have their definition. So an Interface allows you to define behavioral characteristics and apply those behaviours to Class that implements this Interface. Example
public interface IHoliDay List<DateTime> GetListOfHoliday(); List<DateTime> GetListOfHoliday(); If you use public List<DateTime> GetListOfHoliday() an error occurred. Error 1 The modifier 'public' is not valid for this item . So there is no need of modifiers for Interface members. Interface members are automatically public and cannot be static.
Why Interface is came in existence?
Interface is mainly used for two reasons
· C# does not support multiple inheritances, so by using Interface, A class can implement multiple interfaces to achieve multiple inheritances.
public class HoliDay : Class1, Interface1,Interface2,Interface3 · Data Hiding
You can call class members using Interface.
static void Main(string[] args) //Hiding the Holiday class object IHolidayii = new Holiday(); Console.WriteLine(ii.val); public interface IHoliday List<DateTime> GetHoliDayList(); public class Holiday : IHoliday public String val{ get; set;} List<DateTime> hlist = newList<DateTime>(); public List<DateTime> GetHoliDayList() Console.WriteLine("Calling by interface"); Interface also used to make your code more reusable, maintainable, and scalable and provides the concept of component based programming.
Suppose you have two interfaces with method with same name. How to implement both in same class?
User Intafacename.MethodName()
{
}
Example:
static void Main(string[] args) //Hiding the Holiday class object IOfficeHoliday iioffice = newHoliday(); iioffice.GetHoliDayList(); IGuzzatedHoliday iiGuzzated = new Holiday(); iiGuzzated.GetHoliDayList(); //Console.WriteLine(ii.val); public interface IOfficeHoliday List<DateTime> GetHoliDayList(); public interface IGuzzatedHoliday List<DateTime> GetHoliDayList(); public class Holiday : IOfficeHoliday, IGuzzatedHoliday List<DateTime> hlist = new List<DateTime>(); //Method definintion for first interface List<DateTime> IGuzzatedHoliday.GetHoliDayList() Console.WriteLine("IGuzzatedHoliday Method"); //Method definintion for second interface List<DateTime> IOfficeHoliday.GetHoliDayList() Console.WriteLine("IOfficeHoliday Method"); //here if you use public with method definition in class that implements both of interfaces, an error occurred.
What is the use of is and as operator with respect to Interface concept?
The is and as operators can be used to determine whether an interface is implemented by an object.
Holiday hh = new Holiday(); IHoliday iholiday = hh asIHoliday; Console.WriteLine("Holiday class implemented IHoilday"); Comments if you have other possible interview FAQ for Interface in C#.