Is it possible to call a method in an implementation class that is not defined in its interface using an interface variable?

Is it possible to call a method in an implementation class of an interface that is not defined in the interface using the interface variable, as shown below:

interface ILookup { public void someInterfaceMethod1(); public void someInterfaceMethod2(); } 

... and implementation class:

 public class extendedLookUpImplementor: ILookup { //constructor LookUpImplementor(){ } public void someInterfaceMethod1(){ // Implementation Code here. } public void someInterfaceMethod2(){ // Implementation Code here. } public void ExtendedMethod(){ // Implementation Code here. } } 

In the client code:

 ILookup lookupVar = new LookUpImplementor(); lookupVar -> someInterfaceMethod1(); // i know it will work. lookupVar -> someInterfaceMethod2(); // i know it will work. 

My question is: can I call ExtendedMethod using lookupVar as shown below:

 lookupVar -> ExtendedMethod(); // Note again that ExtendedMethod() is not defined in Ilookup interface/contract. 
+4
source share
2 answers

Just by casting lookupVar, like extendedLookUpImplementor, or by reflection, I think.

+3
source

First of all, as Ian1971 said, yes, you can, dropping it to a certain type, say

 ILookup lookupVar = new LookUpImplementor(); ((extendedLookUpImplementor)lookupVar).ExtendedMethod(); //this should work 

or alternatively using dynamic / reflection.

Having said that, I really don't think this is a good way to do this, because it would violate one of the goals of the contract / interface.

For example, if we have an ILookup variable "lookupVar"

 dynamic lookup = lookupVar; lookup.ExtendedMethod(); //this would work 

At any point in time, code using the lookupVar object does not guarantee that the ExtendedMethod method will exist and may throw an exception at run time.

My real question for you would be why you want to add a method that cannot be added to the contract, what is your goal here. If the method extends the class, try switching to the C # extension method , which may fit your scenario.

0
source

Source: https://habr.com/ru/post/1500713/


All Articles