Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# properties on Interface [closed]

Tags:

c#

.net

Could anyone please help me out whether it's a best practice to include properties on Interface or Abstract Class?

I would imagine an Interface should only have method signatures?

like image 946
Nil Pun Avatar asked Dec 15 '11 01:12

Nil Pun


3 Answers

Properties are syntactic sugar for methods. Consider this:

I have a property:

String PropertyA { get; set; } 

At runtime this becomes something like this:

String get_PropertyA() { ... }
void set_PropertyA(String value) { ... }

Note that the "..." indicates code that would be put there by the code generator. Effectively what I am saying is that properties don't really exist beyond C#, as they compile down to methods using a convetion indicated in my example. To confirm what I am saying you can use reflection and have a look at what the reflected code looks like.

It can be bad practice however to put properties on an interface if they do something that is non trivial in the implementation. For example, if I want to set a variable and that updates other variables, or setting a property might deny my property assignment because of an internal condition, then a property shouldn't be used. I think that is a general rule that would apply beyond interfaces.

like image 145
Dessus Avatar answered Oct 04 '22 10:10

Dessus


It is perfectly acceptable to have properties in an interface. I do it all the time.

like image 43
Daniel A. White Avatar answered Oct 04 '22 08:10

Daniel A. White


Properties are fine in an interface

See:

http://msdn.microsoft.com/en-us/library/ms173156.aspx

Interfaces consist of methods, properties, events, indexers, or any combination of those four member types. An interface cannot contain constants, fields, operators, instance constructors, destructors, or types. It cannot contain static members. Interfaces members are automatically public, and they cannot include any access modifiers.

like image 45
bryanmac Avatar answered Oct 04 '22 08:10

bryanmac