Posted by Simplify DotNet on December 26, 2020 in C#, class, interfaces, use of interfaces | No comments
Interfaces
Interfaces in C# are like pure abstract class. Any method in an interface can not have implementation and we can only provide the declaration of those methods. All the methods in an interface are by default marked as abstract and public and we need not to mention that. Using interface we can also achieve multiple inheritance in C#. We also can not create an object of interface and to use the data-members and methods, and to use the data members and methods of the interface we need to implement that interface using a class.
Interfaces in C# can be declared as below.
public interface Itest
{
}
It is not compulsory but the name of an interface should start with 'I' as per the naming convention as shown above. Any class that implements an interface needs to implement all the methods present in the interface.
Let us look at a simple example of an interface below.
public interface Itest
{
string A { get; set;}
int foo();
}
public class Test1 : Itest
{
public int foo()
{
// Provide the implementation here
}
public string A { get ; set ; }
}
As shown in the above example we have created one interface as Itest and that interface has been implemented by class Test1.
A class can inherit from more than one interface and hence we can achieve multiple inheritance in C# using interfaces. If both the interfaces contain method with a same name, number of parameters in return type then we need to implement the methods in the class explicitly. Let us look at the explicit implementation of the interface below.
public interface Itest1
{
void foo();
}
public interface Itest2
{
void foo();
}
public class Test1 : Itest1, Itest2
{
public void Itest1. foo()
{
Console.Writeline("in method Itest1 foo");
}
public void Itest2. foo()
{
Console.Writeline("in method Itest2 foo");
}
}
public class Main
{
Itest1 I1; // Variable of Interface Itest1
Itest2 I2; // Variable of Interface Itest2
I1 = new Test1(); // Object which is referencing to Class Test1
I2 = new Test2(); // Object which is referencing to Class Test2
}
As shown above if we are inheriting from more than one interfaces and if all the interfaces contain a method with the same name then we need to explicitly mention which method we are implementing in the class.
So today we have seen how we can use interfaces in C#. and their importance.
Thank You...….
For any issues related to C#, .NET, jQuery or to give any feedback please write to me on below mail id.
Email id : prson94@gmail.com
0 comments:
Post a Comment