Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast to not explicitly implemented interface?

Tags:

c#

Let's say you define some arbitrary interface:

public interface IInterface {
    void SomeMethod();
}

And let's say there are some classes that happen to have a matching public interface, even though they do not "implement IInterface". IE:

public class SomeClass {
    public void SomeMethod() {
       // some code
    }
}

Is there nevertheless a way to get an IInterface reference to a SomeClass instance? IE:

SomeClass myInstance = new SomeClass();
IInterface myInterfaceReference = (IInterface)myInstance;
like image 815
Dave Cousineau Avatar asked Oct 10 '11 22:10

Dave Cousineau


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 a class be cast to an interface?

Yes, you can. If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference.

CAN interface have unimplemented methods?

Interfaces in javaThese contracts are essentially unimplemented methods. Java already has a keyword for unimplemented methods i.e. abstract. Java has the provision where any class can implement any interface, so all the methods declared in interfaces need to be public only.

Can we override interface methods in C#?

A method override in an interface must use the explicit interface implementation syntax. It is an error to declare a class type, struct type, or enum type within the scope of a type parameter that was declared with a variance_annotation. For example, the declaration of C below is an error.


1 Answers

No there is no way to do this. If the type doesn't implement the interface then there is no way to cast to it. The best way to achieve behavior similar to the one you want is to create a wrapper type which provides an implementation of IInterface for SomeClass.

public static class Extensions {
  private sealed class SomeClassWrapper : IInterface {
    private readonly SomeClass _someClass;

    internal SomeClassWrapper(SomeClass someClass) {
      _someClass = someClass;
    }

    public void SomeMethod() {
      _someClass.SomeMethod();
    }
  }

  public static IInterface AsIInterface(this SomeClass someClass) {
    return new SomeClassWrapper(someClass);
  }
}

Then you can make the following call

SomeClass myInstance = new SomeClass();
IInterface myInterface = myInstance.AsIInterface();
like image 128
JaredPar Avatar answered Oct 12 '22 23:10

JaredPar