Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properties in an Interface

In my interface, I have declared a property with setter and getter.

public interface ITestInterface
{
   string AProperty { get; set; }
}

When I code my class which inherit that interface, why I need to define these two properties again?

public sealed class MyClass: ITestInterface
{
   public string AProperty { get; set; }
}
like image 334
michael Avatar asked Feb 09 '23 20:02

michael


1 Answers

Because you are not inheriting from an interface, you are implementing the interface. (although they both share same syntax :)

public class MyClass : IMyInterface { ... } //interface implementing
public class MyClass : MyBaseClass { ... } //inheriting from a class

Assume you are inheriting a candy box (not from your ancestors, in programming manner), it is something (not exactly) like you put the candy box in another box, now the outer box (the derived class, the inherited one) is inherited from candy box and have all the things candy box have, but if you want to implement (make) a candy box yourself you must build a box and put some candy in it. This is the way interfaces work.

like image 97
Hamid Pourjam Avatar answered Feb 12 '23 10:02

Hamid Pourjam