Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast between interfaces whose interface signatures are same

Tags:

c#

.net

casting

Is it possible to cast from one interface to another when both interface's signatures are same? The below source is giving the Unable to cast object of type 'ConsoleApplication1.First' to type 'ConsoleApplication1.ISecond'. exception.

class Program
{
    static void Main(string[] args)
    {
        IFirst x = new First();
        ISecond y = (ISecond)x;
        y.DoSomething();
    }
}

public interface IFirst
{
    string DoSomething();
}

public class First : IFirst
{
    public string DoSomething()
    {
        return "done";
    }
}

public interface ISecond
{
    string DoSomething();
}
like image 367
Dhwanil Shah Avatar asked Dec 10 '22 02:12

Dhwanil Shah


1 Answers

Is it possible to cast from one interface to another when both interface's signatures are same?

No. They're completely different types as far as the CLR and C# are concerned.

You could create a "bridge" type which wraps an implementation of IFirst and implements ISecond by delegation, or vice versa.

like image 183
Jon Skeet Avatar answered May 10 '23 12:05

Jon Skeet