Which interface's method Add2values(param 1, param 2) will be called?
// interface 1
public interface IStudents
{
public int Add2values(int a, int b);
}
// interface 2
public interface IStudents2
{
public int Add2values(int a, int b);
}
//class inherit 2 interfaces
public class Students : IStudents, IStudenst2
{
public int Add2values(int a, int b)
{
return a+b;
}
}
// in home controller
public IActionResult Index()
{
Students students = new Students();
int res = students.Add2values(20, 30);
return View();
}
// the question is interface IStudensts or IStudenst2 will be called to calculate the sum?
Thanks and will be appreciated?
Jayraj ChhayaPosted Dec 8, 2023, 9:55 AM
the class
Studentsinherits from two interfaces:IStudentsandIStudents2. Both interfaces have a method namedAdd2valueswith the same signature.However, when the
Add2valuesmethod is called on an instance of theStudentsclass, the method from the interfaceIStudentswill be called to calculate the sum.This is because the
Studentsclass explicitly implements theAdd2valuesmethod from theIStudentsinterface. By doing so, it indicates that it intends to use the implementation provided by theIStudentsinterface.If the
Studentsclass wanted to use the implementation from theIStudents2interface instead, it would need to explicitly implement that interface'sAdd2valuesmethod.Therefore, in the given code snippet, the interface
IStudentswill be called to calculate the sum.I hope this clarifies which interface's method will be called in the given scenario. Let me know if you have any further questions!
Jignesh KumarPosted Dec 6, 2023, 6:25 PM
It will not call any of interface. You have created object of Students class and class have same method implementation so it will direct refer class method.
Incase more then one interface have method with same name then you have to call explicit interface to call specific method. please refer this link
https://www.c-sharpcorner.com/UploadFile/8911c4/implicit-and-explicit-interface-examples/