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

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.

Related

When should I use property in C# Interface?

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.

Using a private auto property instead of a simple variable for a programming standard

In a discussion with a peer, it was brought up that we should consider using auto properties for all class level variables... including private ones.
So in addition to a public property like so:
public int MyProperty1 { get; set; }
Our private class-level variables would look like this:
private int MyProperty2 { get; set; }
Instead of:
private int _myProperty2;
I'm on the fence about why someone would want to do this but I can't decide if my reluctance to accept this is because of my own internal brainwashing with how I write my code to the same programming standards and naming conventions I've used for 10 years or because I've never seen this before (for a reason).
I realize it's extra code to type but to be honest, when using auto-properties, I don't think I've ever typed it out due to the 'prop' and 'propg' snippets so it'd be very simple to set up a new snippet to create a private auto property so the extra code doesn't bother me too much since I never have to type it.
Other than aesthetics which may just be my subconscious, are there any issues that could result from using fully private auto properties? Are there any good reasons to do this or not to do it? I've seen a lot of code in my day on stackoverflow, codeplex, codeproject, etc. and I've never seen anyone use this standard.... is there a reason why?
Private auto-properties are completely pointless, in my opinion. What value does a private auto-property provide that a plain field doesn't?
(It's different when the auto-property is only partially private -- eg, a public/protected getter with a private setter -- or when you use a private non-automatic property to enable you to wrap additional code around the getter/setter.)
This does not make too much sense.
I can think of a 'benefit':
you can later add logic to the getter and/or setter and be sure it is always passed
but frankly your classes should not become so big that this is useful.
"are there any issues" ?
Your properties won't work as arguments to ref or out parameters.
It's not nearly as useful for privates as for publics.
Suppose you took your automatic private property and later built some logic into it (being able to do that without breaking anything is the whole point of auto props)...
This would require you to create a private backing member for the property to wrap.
So now you've got two different private ways (member and property) of doing the same thing though one has hidden side effects (the property) and you've now also got the problem of ensuring none of your other methods in the class access that member directly.
Ends up being much more of a headache than just using a private member from the beginning.
What this strategy will do for you is provide an opportunity to put any future changes into the previously autogenerated private property without affecting any of the other code that gets or sets your private property. I personally haven't used this much but it can be beneficial in a case where changes to handling may occur. It also standardizes the code so that fields are always accessed by properties. There are no real drawbacks but it is not really much benefit in most situations either. I think style is really the biggest driver in most situations.
In a discussion with a peer, it was
brought up that we should consider
using auto properties for all class
level variables... including private
ones.
This will not be useful, In case you don't have any logic to write in your properties for retrieving and returning values.
Besides point 1, you have read only property
So you can directly go with
public int MyProperty1 { get; set; }
Moreover it reduces your line of code and Quick Implementation
I'm a firm believer in KISS. I never use a property when a field will do, and I see very little reason to use private accessors (get).
The primary purpose of a property is to be a public accessor for private data. So for simple propreties that do nothing but set or get a value, private accessors and setters make no sense.
Having said that, when you need to transform the data as it's being read, or when you need to perform a side effect when updating the value, you should use a field. Does changing your value raise an event? Then a field is a no-brainer. But then, that's not an auto field that you're declaring with {get; set;}

What is the difference between public int i and public int i {get; set;} (what is the difference between automatic property and a public member?) [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
c#: why have empty get set properties instead of using a public member variable?
C#: Public Fields versus Automatic Properties
I am using "automatic" properties in my code,
and I wonder what is the actual difference between
this code:
public class foo{
public int i;
}
and
public class foo{
public int i {get; set;}
}
I know there is a difference, as sine 3rd parties that I've used missed the public members but found them once adding the {get; set;}.
AS there is no private field behind that, what is going behind the scene ?
A private field gets generated by the compiler when using automatic properties.
When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
In regards to the difference between the two examples - the first one exposes the field directly for manipulation. This is considered bad practice (think information hiding, loss of encapsulation).
With the second example, you must use the getter and setter and you can add any kind of validation and other logic around these actions.
See this blog post:
If I have a field with no special behavior, should I write a "just in case" property (with trivial get/set), or should I expose a public field?
The reason that the library design guidelines suggest you write a property here is that it is important that libraries be easily versioned. If you put a property in there ahead of time, you can change the property implementation without requiring users to recompile their code.
The first is a field and could be described as POD. The second is a property and allow for derived classes to overload and Shadow while the first does not. Also the second is a nicety since the complier silently creates a backing store.
That's an auto property, not an anonymous property. There is, in fact, a private backing field for it, it's just generated automatically by the compiler and isn't available to you at compile time. If you run your class through something like Reflector (or examine it at runtime with reflection), you'll see the backing field.
To answer your question of "What's the difference?", the obvious answer is that one is a field, whereas one is a property. The advantage to using auto properties is that it gives you the flexibility to move to traditional properties later, should the need arise, without changing your API. As far as third party code being able to "reach" one but not the other, that would be a question best answered by the other developer. That being said, most API's are designed to work on properties, not fields (since conventional wisdom is that you do not expose fields outside of the declaring class). If the third-party library is reflectively scanning your class, then it's likely only looking for properties.
The important thing to remember is that:
private string backingField;
public string Data
{
get { return backingField; }
set { backingField = value; }
}
and
public string Data { get; set; }
Are compiled to essentially the same code. The only substantive difference is the name of the backing field.

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