Dragonblf
Dragonblf

Reputation: 115

How to implement an interface member with my own class in another class in c#?

I just wondering how to implement an interface member with my own class in another class. Here is an example to illustrate my question:

// --- Both files are in the same namespace --- //
// --- OwnClassA is in another namespace --- //

// --- First file --- //
// OwnClassA is importet
public interface ITest {
    OwnClassA varTest {get;}
}


// --- Second file --- //
// OwnClassA is importet
public class Test : ITest {
    public readonly OwnClassA varTest;
}

Visual Studio Code says: 'Test' does not implement interface member 'ITest.varTest' [Assembly-CSharp]

What I'm doing wrong here?

Upvotes: 0

Views: 219

Answers (3)

John Wu
John Wu

Reputation: 52290

Interface members must be exposed as properties or methods, and the implementation has to match. The original interface member is a property. You have created a field. Make it an autoproperty instead and you should be good to go.

// --- Second file --- //
public class Test : ITest {
    public OwnClassA varTest { get; set; }
}

Or (if you want it to be 'read only' outside of the class)

// --- Second file --- //
public class Test : ITest {
    public OwnClassA varTest { get; private set; }
}

If you wish to use the readonly keyword (and thereby enforce that varTest can only be initialized in the constructor), you will have to use a fully-implemented property:

// --- Second file --- //
public class Test : ITest {
    private readonly OwnClassA _varTest;

    public Test()
    {
        _varTest = new OwnClassA();
    }

    public varTest
    {
        get
        {
            return _varTest;
        }
    }
}

Upvotes: 4

Eric Lippert
Eric Lippert

Reputation: 660493

The interface implementation needs to match the interface:

public class Test : ITest {
  public OwnClassA varTest { get; }
}

A field is not the same thing as a property; there is no way to say in an interface that an implementation must have a field.

Upvotes: 3

Joel Coehoorn
Joel Coehoorn

Reputation: 416131

The interface uses a property; the attempted implementation in Test uses a field. Those are treated very differently by the compiler and are not at all the same thing. Your Test class needs to define varTest as a property.

Upvotes: 3

Related Questions