When should I use property in C# Interface? - c#

I'm new to C# interfaces, I know that inside Interfaces we can put some property like
int speed{ get; set; }
but things is that, the reason property exists is to achieve encapsulation, which provides access to private members, however in interfaces everything is public. Then does it make sense to use property in Interfaces? Or it's just because interfaces are "contracts" so this is sort of normal?

You can use properties in interfaces as public members that are part of your “contract”
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field c# programming guide
So the backing field is private but the property is public. Therefore it can form part of the interface.

You don't have to use properties. You can use methods too, like this:
public int GetSpeed();
public void SetSpeed(int n);
However, people seem to prefer using a property, and its get and set methods, because it is easier to read and use, and it encapsulates the getter and setter in one place.

Related

C# private properties - are they used/make sense?

I'm starting out as a C# enthusiast and it seems to me that properties should always be public. Private property wouldn't make sense. Would it?
Would this:
private string propertyOne {get; set;}
be equivalent to this:
public string propertyOne {private get; private set;}
Yes, private properties can make sense, particularly in cases where you have logic you want to implement in the getters/setters. You may only want these accessible within the class (hence they're private) but you still want to encapsulate the getter/setter logic in one place.
There is a difference between the two lines of code you printed. Someone reflecting over public properties won't see the first one but they will see the second, even if they can't invoke the getter/setter.
The idea of using a Property is to encapsulate rather than just present a raw variable to the 'outside world'. That way you can also have an extra logic in your accessors.
So No, a purely private property wouldn't be the usual use case.
It's not uncommon to see public properties with a private setter though.
Yes, those two bits of code are equivalent. I've never created a private property with an auto getter/setter. Doesn't seem very useful. I have used private properties with an actual implementation for the getter. A private get method (or property getter) can be useful.
In your question, yes the latter would equal the former in functionality but would make no sense to implement it as such.
I tend to use
public string propertyOne {get; private set;}
As sometimes I want it publicly available but only the class it exists in able to set the value. But mostly its also when you want to encapsulate other logic into the getters an setters to perform other functions.
But more often than not they are public properties, to encapsulate other functionality.

Do I need to use { get; set; } with c# fields that have no special actions when getting and setting

I have been coding classes like this:
public class ReportViewModel
{
public string Status;
public string DataSource;
public String DataStore { get; set; }
public PageMeta PageMeta { get; set; }
public ICollection<Question> List { get; set; }
}
Note that most of the fields use { get; set; } except the first two which I let Visual Studio add for me.
What I am wondering is do I really need to use { get; set; }. It seems to me that VS2010 does not automatically add this so do I need it?
You've created a class with two public fields (Status and DataSource) and three public properties (DataStore, PageMeta and List). I would advise against having public fields - and you should actually consider whether you really need all of these to be mutable properties at all.
There are various advantages to using properties over public fields, but the main one in my mind is that a property is logically part of the API of a class, whereas a field is logically an implementation detail. The property says what callers can do - a field says how a value is stored.
{ get; set; } indicate autoimplemented properties. In .NET there is a difference between properties and fields. Normally fields should be private. They are used for some specific implementation and should in most cases be internal to the class. Properties on the other hand are used to encapsulate behavior that is exposed to the consumers.
If you want them properly exposed as properties, yes.
They are different: your first two members are fields - not properties. The others are properties with auto-implemented accessors.
When you don't add the get and set you are using a field rather than a property. Which in many cases won't make a lot of difference. However, you can't databind to a field like you can with a Property. So you would lose that.
At all depends on how this class will be used.
If this is in your code, just used in your current product, then there isn't really much difference between fields (no {get;set;}) and properties (with the {get;set;}).
However in that case they probably shouldn't be public, make them internal or private instead so that it's clear that external code shouldn't use them.
If your class is going to be used by other assemblies then you should always convert public fields to properties.
The reason is that if you want to extend properties later on (i.e. add a body to the set) then your users can just get the new DLL from you. However if you've used fields then converting them to a property will look the same in the IDE, but require your users to recompile when they get the altered DLL.
Being public tells consumers that they can rely on that member being present, being a property gives you more control of how you deliver it to them.
There is a difference. The first two are fields and the remainder are auto-properties.
The second one, the compiler generates a private backing field and some boiler-plate get/set methods. These then allow you to access the properties like they were fields, but with the advantages only available to properties.
It is always recommended to hide fields behind properties, by either making them private and writing your own property around it or using an auto-property.
There's some advantages to properties. One being that properties can be made read-only, or even write-only, or read-only with an internal write-only, etc. Since they act just like methods, you can execute any arbitrary code inside of them. This is useful for when you need to implement things like INotifyPropertyChanged or if the property is actually calculated from several fields behind it.
The other advantage is encapsulation. You aren't tying yourself directly to the fields of the class, but rather the property. So if some detail about the field changes (say it goes away and becomes calculated), by using the property you are insulating yourself from those implementation details.
You should certainly look at using properties (for now adding the { get; set; }) for all cases. They are good practice in that they provide a level of encapsulation that shields the user from implementation specific details.
You do not have to, but this just coding stundart, with its pros and cons.
Consider this link for more resources:
Property Acessors

Restricting access property in subclass

I have a class with a public property, that I want to restrict access to _for_some_modules_.
(The modules that use this class reside in different assemblies, so internal does not help.)
My first thought was to subclass, and make the derived property accessor private or protected, but this is not possible. The derived property has to have the same access rights. (See http://msdn.microsoft.com/en-us/library/75e8y5dd.aspx)
Any suggestions? I assume it is a common task to make a more restricted variant of a class?
Thanks!
You can use the InternalsVisibleToAttribute to make the internal members of the class visible to other assemblies (as many as you like). The documentation page has an example.
I assume it is a common task to make a
more restricted variant of a class?
This is not a common task since it violates the Liskov substitution principle - you can't use the sub class the same way as you would use the base class in regards to the property you restrict access to. You should consider refactoring your class hierarchy.
You could solve the problem through composition - make the class A internal only and write a public wrapper class that has a member of type A and delegates and controls access to the A's properties / methods.
Making more restricted subclasses is actually not common because it would break consumers of the base class that assumed they had access to the public members. In general, your classes should start out restrictive and get less so as they specialize, not vice-versa.
The concept you're looking for is called a "friend" class in other languages, but C# (purposely) doesn't implement them. The InternalsVisibleToAttribte is as close as it gets, but that is applied at the assembly level, so it may not work for you.
Without more information on why you are trying to restrict access this way, it's hard to give any good general-purpose alternatives. The access modifiers like public/private/etc aren't designed to be a security mechanism, since Reflection will get you access to read/write everything regardless. They're more of a hint to the consumers as to what is safe to use -- public members will usually remain stable across new versions, while private (implementation-detail) members are more likely to change.
You can always do something like this:
class MyBaseClass
{
protected string MyRestrictedProperty { get; set; }
}
class MyClass : MyBaseClass
{
public string MyPublicProperty
{
get { return MyRestrictedProperty; }
set { MyRestrictedProperty = value; }
}
}

Private Set or Private member?

I was wondering what's considered the C# best practice, private/protected members with public getters, or public getters with private/protected setters?
public int PublicGetPrivateSetter
{
get;
private set;
}
private int _privateMember;
public int PublicGetPrivateMember
{
get { return _privateMember; }
}
I feel that using a private member is more explicit in your code that it's a private setter (using naming conventions).
On the other hand using private setters gives you an option to use virtual (protected), write less code, has less room for mistakes and can give you an option to add a side effect later on if you need to.
I couldn't find what's considered a best practice, or even if one is considered better than the other. From what I've seen usually 80% of the time (from code that I'VE seen) people DONT use private setters... I'm not sure if this is because people don't know about private setters, or because it's considered better to actually use private members.
EDIT:
Indeed, other benefits which I forgot about when using private members is default values and the use of readonly.
I prefer to use auto-implemented properties unless the default implementation doesn't do what I want. So in this case, since the auto-implemented property does what you need, just use that:
public int Foo { get; private set; }
However another situation is if you want to make the field readonly (meaning that the only place where the field can be set is in the constructor). Then you need to define the backing field and mark it readonly as this isn't supported by auto-implemented properties:
private readonly int foo;
public int Foo
{
get { return foo; }
}
There is no best practice I'm aware of. I know automatic properties were mainly to make things easier even more easier for code generation and LINQ related stuff.
For me, I start with automatic properties and refactor later if needed. Depending on the need I may change something to virtual or protected as you mentioned, or maybe refactor to use a variable (When I want to refactor the set accessor to have some logic.
Its the same thing. In the first example, the compiler generates the backing store. In the second, you generated the backing store. Since the implementation is internal to the class, refactoring one into the other is not a big deal. Tools like Resharper make that trivial. The reason you probably haven't seen private setters that much is that its a C# 3.0 feature.
There's nothing wrong with private setters. In most case, it's used with auto properties to make the property readonly outside the object's scope.
Conceptualy speaking, it doesn't change anything. It's mostly a matter of taste.
I personnally use the private setter because I'm lazy and use the propg snippet a lot. (propg tab tab)
Also, most of the time I end up setting dirty flags and binding events to those properties, so I might as well do a part of the work right now. If you ever need to add a setter later, it's much easier if the code is written without using the member behind since the beggining as it will be less code to change.
There is no good answer to this question. the best pratice is to follow our compagnie nomenclature and if your alone then the way you prefer
In my opinion there is no best practice and very little (if any) difference in the resulting compiled code, it really just depends on your needs or own likes/dislikes. If you're following your group's naming standards and meeting requirements (e.g. don't need to propagate a change notification) then it shouldn't matter.
An advantage of private fields is that you can define a default value in the same place as your declaration. In an auto-implemented property you'll have do define the default in the constructor if it's not null or the type's default value.
However, I still like private setters. But we usually don't use auto-implemented properties since our setters usually have a richer functionality - e.g. property update notifications, logging, etc.

When should we use private variables and when should we use properties. Do Backing Fields should be used in same class?

In most of the cases we usually creates a private variable and its corresponding public properties and uses them for performing our functionalities.
Everyone has different approach like some people uses properties every where and some uses private variables within a same class as they are private and opens it to be used by external environment by using properties.
Suppose I takes a scenario say insertion in a database.
I creates some parameters that need to be initialized.
I creates 10 private variables and their corresp public properties
which are given as
private string name;
public string Name
{
get{return name;}
set{name=value;}
}
and so on. In these cases mentioned above, what should be used internal variables or properties.
And in those cases like
public string Name
{
get{return name;}
set{name=value>5?5:0;} //or any action can be done. this is just an eg.
}
In such cases what should be done.
What is the conclusion
I actually meant to ask this.
Should we use variables within that class or not or should we use properties everywhere within same class as well.
If you use auto-implemented properties, then the field will be hidden, so you are forced to use the property, even in the class where the property is defined. Auto-implemented properties are a good idea, unless you need to add some logic to the getter/setter.
If the only use for the private variable is as a storage container, you might use:
public string Name {get; set;}
IMHO one should never make variables public - always use properties so you can add constraints or change behaviours later on whitout changing the interface.
Made things more readable:
I expose my data always through properties.
If I do not need additional logic (e.g. validation) I use implicit properties. This way there is no backing field and I cannot access it by accident. If I need to add some additional logic I can easily change the implicit property to a "traditional" one. As I use the property everywhere I do not have to worry that my extra logic is not called.
If I need something extra (like validation) then I have a private backing field, but I access this field only in the property body (get/set accessors). Again I do not need to worry if I change something in the property: My code will always use the same logic.
The only reason for not calling the property in my opinion would be if for some reason I really do not want any additional logic to be called, but this seems a dangerous thing so I rather avoid it...
I never expose public variables. Why? Because I can't lay constraints on them, whereas I can when I'm using properties. I can first check the value if it meets my constraints (e.g. an email address) and then I save it. Otherwise I throw an Exception.
You should never expose public variables without a very good reason. It is tough to say never, because if you trying to interop with comm type components you might be required too.
Anything publicly exposed should be a property. Why is that?
The reason is if you need to change the source of the value, or add some business logic checking if it is a public member you are going to require anything using the code to change. If it is a property you can change the internal logic and not require anybody using it to change the code.
I personally use properties and only create members variables when I want a property to do more than getting or setting (since this is easy with C# 3.0 with shortcut properties).
If I want to keep a property from being publicly exposed I make it as private, and only expose it when I have too.
We require explicit private variables in some situation like validation before set.Sometime we also need to conversion of input, for instance , formatting the input.

Categories

Resources