Home > other >  Can these class interfaces be implemented?
Can these class interfaces be implemented?

Time:10-09

Suppose we have the following definition in c#:

interface I1
{
    int num { get; set; }
    string name { get; set; }
}

interface I2
{
    I1 GetValue();
}

If the interfaces are implemented like this:

public class C1 : I1
{
    public int num { get; set; }
    public string name { get; set; }
}

public class C2 : I2
{
    public C1 GetValue()
    {
        C1 c1 = new C1();
        c1.num = 2;
        c1.name = "AnyName";

        return c1;
    }
}

There will be a Compiler Error CS0738: 'C2' does not implement interface member 'I2.GetValue()'. 'C2.GetValue()' cannot implement 'I2.GetValue()' because it does not have the matching return type of 'I1'

In another word, Compiler doesn't regard C2 is implementing I2.GetValue() because C2.GetValue() returns C1 data type rather than I1.

Then, how to implement GetValue() of I2 interface?

CodePudding user response:

You need an explicit implementation. It is fairly simple to do

public class C2 : I2
{
    public C1 GetValue()
    {
        C1 c1 = new C1();
        c1.num = 2;
        c1.name = "AnyName";

        return c1;
    }

    I1 I2.GetValue() => GetValue();
}

This tells the compiler that GetValue() actually implements the interface in C2.

CodePudding user response:

The error and its documentation are pretty clear: change the return type of C2's GetValue() method to return I1 instead of C1. Example.

  • Related