Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call explicit interface implementation methods internally without explicit casting?

Tags:

c#

.net

If I have

public class AImplementation:IAInterface {    void IAInterface.AInterfaceMethod()    {    }     void AnotherMethod()    {       ((IAInterface)this).AInterfaceMethod();    } } 

How to call AInterfaceMethod() from AnotherMethod() without explicit casting?

like image 587
Jader Dias Avatar asked Dec 08 '09 18:12

Jader Dias


People also ask

How do you call an explicit interface?

The following is an example of how to call "Explicit Interface Method" in the same class using class methods. Output: Class1 Display Method. Iinterface_1 Method Explicit interface implementation. Iinterface_1 Method Implicit interface implementation.

Can we override interface methods in C#?

An implementing class is free to mark any or all of the methods that implement the interface as virtual. Derived classes can override or provide new implementations.

How do you call an interface method in C#?

In order to call the methods using interface reference(here r is interface reference), you have to assign to class object to it. Like if you are assigning Person1's object obj1 to r i.e. r = obj1; then you call the Speed() and Distance() methods that are implemented by the Person1 class.

What is implicit and explicit implementation of interface?

Resolving conflicts here ..... "Implicit Implementation" - means just simple implementation of a particular method having same name and same signature which belongs to the same class itself, where as "Explicit Implementation" - means implementation of a method using their Interface name having same name and signature ...


2 Answers

A number of answers say that you cannot. They are incorrect. There are lots of ways of doing this without using the cast operator.

Technique #1: Use "as" operator instead of cast operator.

void AnotherMethod()    {           (this as IAInterface).AInterfaceMethod();  // no cast here } 

Technique #2: use an implicit conversion via a local variable.

void AnotherMethod()    {           IAInterface ia = this;     ia.AInterfaceMethod();  // no cast here either } 

Technique #3: write an extension method:

static class Extensions {     public static void DoIt(this IAInterface ia)     {         ia.AInterfaceMethod(); // no cast here!     } } ... void AnotherMethod()    {           this.DoIt();  // no cast here either! } 

Technique #4: Introduce a helper:

private IAInterface AsIA => this; void AnotherMethod()    {           this.AsIA.IAInterfaceMethod();  // no casts here! } 
like image 117
Eric Lippert Avatar answered Sep 22 '22 14:09

Eric Lippert


You can introduce a helper private property:

private IAInterface IAInterface => this;  void IAInterface.AInterfaceMethod() { }  void AnotherMethod() {    IAInterface.AInterfaceMethod(); } 
like image 25
Pavel Minaev Avatar answered Sep 21 '22 14:09

Pavel Minaev