Home > Enterprise >  Class attributes not found in the interface that is implemented by this class
Class attributes not found in the interface that is implemented by this class

Time:01-29

My question may be complicated , but I will try to explain it . Suppose that I have a Interface called IA and class called A ,

Interface IA:

  public interface IA
    {
       public void Test();
    }

Class A

  public class A : IA
    {
       public string Name { get; set; }

       public A()
          {
          }
    }

When I'm trying to use Dependency injection :

Main Class :

 public class MainClass
    {
      IA objectA = new A();
      objectA.Name = "test A"; // Not working , I didn't get this Name and I can't find it .
    }

IA does not contains a definition for Name ...

What's the reason of this problem?

CodePudding user response:

I have created a Gist https://gist.github.com/ian-bowyer/f1a57a5fc8e4df41cc63d9816276d708 with the code on.

I changed IA to IApple and A to Apple.

The reason is that you have created an variable of type IApple (which then does not have the Name Property in it)

IA objectA = new A();

This says create me a variable called objectA of this interface IA using the constructor A(). The objectA will have the shape of the interface (IA) and not your A (object).

If you are wanting to have Name using the code then perhaps add it to the interface to make it available.

CodePudding user response:

Why do you create a Instance of interface class? Try to create Instance of Class A like:

 public class MainClass
    {
      A objectA = new A();
      objectA.Name = "test A"; 
    }

So you can get your Test() Method and Name Property.

Or you put Name Property in Interface Class IA and all classes inherited from this Interface have Name Property.

  •  Tags:  
  • Related