0

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?

3
  • 3
    varTest is not a compliant name for a property. Consider renaming it to VarTest (note capitalization). Commented Jan 2, 2018 at 17:32
  • 1
    @dasblinkenlight That's just a convention. It can vary from place to place and has nothing to do with the correctness of a program. Commented Jan 2, 2018 at 17:34
  • @JoelCoehoorn That's why I posted this as a comment, not as an answer. Commented Jan 2, 2018 at 17:36

3 Answers 3

4

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;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.