Thundter
Thundter

Reputation: 580

Accessing Implemented Interface Methods in other classes

I'm a C# newbie and am trying to implement an interface. I know I can't put access modiefiers onto interface methods so how do I get access to 'TestValue' in the public static 'Create' method of 'TestClass2' below? the error I get is...

'TestClass1' does not contain a definition for 'TestValue' and no extension method 'TestValue' accepting a first argument of type 'TestClass1' could be found

public interface IParent
{
    string TestValue { get; }
}

public class TestClass1 : IParent
{
    string IParent.TestValue
    {
        get { return "hello"; }
    }
}

public class TestClass2
{
    private string _testValue;

    public static TestClass2 Create(TestClass1 input)
    {
        TestClass2 output = new TestClass2();
        output._testValue = input.TestValue;
        return output;
    }
}

Upvotes: 2

Views: 6380

Answers (3)

Thundter
Thundter

Reputation: 580

I tried converting the object into the interface to get the solution like so

public class TestClass2
{
    private string _testValue;

    public static TestClass2 Create(TestClass1 input)
    {
        TestClass2 output = new TestClass2();
        output._testValue =  ((ITestInterface)input).TestValue;
        return output;
    }
}

This works too but I prefer the simpler solution.

Upvotes: 0

Jason Larke
Jason Larke

Reputation: 5609

You don't need access modifiers in the interface declaration because the point of an interface is to define the publicly accessible contract for any class implementing the interface. Essentially, although you don't specify an access modifier in the definition, all methods/properties are taken to be public.

This means that when you implement the interface, you're contractually bound to provide a public method/property that matches the interface's method/property signature.

In a nutshell, add the public access modifier to your concrete classes implementations and you'll be sweet.

Upvotes: 0

ken2k
ken2k

Reputation: 48985

Add the public access modifier in your concrete implementation:

public class TestClass1 : IParent
{
    private TestClass1 _testValue; 

    public string TestValue
    {
        get { return "hello"; }
    }
}

EDIT: as you actually wrote an explicit interface implementation, I recommend you to see the following SO question: C# Interfaces. Implicit implementation versus Explicit implementation

Upvotes: 6

Related Questions