Property set method without private variable - c#

I got the simplest property like
public bool Something { get; set; }
But in almost every one of them I need to call some method after set, so one line became
private bool _something;
public bool Something {
get{
return _something;
}
set{
_something = value;
CallMethod();
}
}
But it's broke all visual side of code.
So my question is if I can call setter method and stay with clear code?

As far I know, the simple answer is no. When you create your property with just a get and set, it's referred to as an auto-property. The compiler still creates the full code with the backing private variable.
What you have would be considered standard coding practice. It's a few extra lines of code, but easily readable.

Related

Purpose of property with empty set get

Can someone tell me, what is the porpose of using a public property for a private class member but not implementing anything in the set and get part? I know that it could be just for examples and that later on you can implement something but I don't know if there is any meaning using it like that
I am going to assume you know there is a private field generated by the C# compiler as the field backing up this property. It is syntactic sugar. I am also going to assume you know this is an auto-implemented property. So what is the point of a property if it public with no logic in the get or set. In other words, any class can access it and set its value. So why choose this property over a public field?
Purpose of it is:
Today the get and set is empty but it may need code in the future. To avoid breaking a contract in the future, you use an empty get and set.
Most .NET databinding can be done against properties but not fields. So although it is empty, it still serves a far greater purpose.
The get and set can have access modifiers. For example, you can say set is private but get is public.
A field cannot be used in interfaces but properties can.
This is an "auto-implemented" property in C#. In effect, the property acts as a full property, i.e.:
This:
public int Number { get; set; }
Is equivalent to:
private int _number;
public int Number
{
get
{
return this._number;
}
set
{
this._number = value;
}
}
This prevents you from having to type out the full property declaration. This is useful when you don't have any additional logic in the getter and/or setter.
If you're creating simple data mapping and transfer classes, auto-implementing properties can make the class definition far more concise.
When you see
public int Count { get; set; }
as a member of a class, that is not nothing. You're just deferring to the default implementation of auto-properties. It's roughly,
private int _count;
public int get__Count()
{
return _count;
}
public void set__Count(int value)
{
_count = value;
}
You just have syntactic sugar in C# to use these methods roughly like a field, i.e.
instanceOfObject.Count = 42; // Not a field access, but behind the scenes a method call.

Setting variables in constructor vs definition

Observe the following...
//pattern 1
public class Cheesesteak
{
public string bread {get; private set}
public string cheese {get; private set}
public Cheesesteak()
{
bread = "Amoroso";
cheese = "Cheez Whiz";
}
}
//pattern 2
public class Cheesesteak
{
public string bread
{
get {return bread;}
set
{
bread = "Amoroso";
}
}
public string cheese
{
get {return cheese;}
set
{
cheese = "Cheez Whiz";
}
}
public Cheesesteak() {}
}
This is a curiosity question. Is there any advantage or particular reason that you would set the variables in the definition of the "set" versus declaring them in the constructor? My initial guess is pattern 1 is shorter, but less efficient during compile.
Is there any advantage or particular reason that you would set the variables in the definition of the "set" versus declaring them in the constructor?
No, and in fact, this is probably not what you want at all. This will make it impossible to set "break" or "cheese", as any call, such as bread = "rye";, would set it to "Amoroso" (if it worked, but will cause a StackOverflowException). Also note that trying to retrieve the value in your code will cause a StackOverflowException, and the property getter returns the property and not a backing field value.
You were likely thinking of this:
public class Cheesesteak
{
private string bread = "Amoroso";
public string Bread
{
get {return bread;}
set
{
bread = value;
}
}
// ...
The only advantage here is you're setting the "default" value where the field is defined, which can help with maintainability or readability in some cases, and even potentially eliminate the need for a defined constructor, which might reduce the overall length of code.
My initial guess is pattern 1 is shorter, but less efficient during compile.
In general, setting the fields inline vs. setting them in a constructor does not make this less efficient. The compiler will cause the type's actual constructor to set the fields first then run the constructor code, so both versions end up (for practical purposes) the same in terms of the compiled IL. This isn't a matter of efficiency, but rather of code readability and maintainability.
Note that, if you wanted the property to always be a constant (ie: Bread should always return "Amoroso"), you can just make the property have a getter and no setter:
public string Bread { get { return "Amoroso"; } }
I suspect this is not the case, but I thought I'd mention it as an option just in case it's what you intended.
Well the second option will result in a StackOverflowException whenever a user tries to assign or access the properties, versus the first which will only allow private access to them.
You maybe meant something like:
private string bread = "Amaroso";
public string Bread
{
get { return bread; }
private set
{
bread = value;
}
}
Which will initialize the property with "Amaroso" but will not allow it to be set publicly.
No, they are completely different. The get and set blocks are actually methods that get executed when the property is read from or written to. Nether of them have anything to do with initialization.
var x = thing.Property; // Property's "get" accessor method is executed
thing.Property = x; // Property's "set" accessor method is executed
In your second example, both property accessors will infinitely recurse on themselves and you will get a StackOverflowException.

Why access modifier in property accessors should be more restrictive than the property itself?

While developing my application, I sometimes come to the point that I need a property that is currently, say private, but maybe later while we need to handle new scenarios, we may need to make it, say public. But, even if that is going to happen, I always want the setter to remain private. I want to write code like this:
private int A
{
get{return _a;}
private set {_a = value;}
}
The compilers complains that the access modifier on setter should be more restrictive than the property. Well I need to remove the access modifier on set, but if later I need to promote the property to public, I'll expose its setter as well.
Don't you think that this was better as a warning instead of an error?
If you are changing the code to say public you can also change the code to say private set at the same time.
As for this being a warning, I can see it making some sense - I don't think anything would fail to work for only having specified private twice (though it is obviously pointless). That said, I very rarely run into this compiler error and when I do I spent the 5 seconds it takes to fix it and move on.
The irony of the situation being that both of us have now spent longer on this question and answer than we likely ever have with this error and it's effects :-)
Don't you think that this was better as a warning instead of an error?
No, I think you'd better use private variables (private int _a;) and only promote it to a property with the appropriate modifers when that is required.
Of course, without having a setter, you can't use validation like this:
private int _a;
public int A
{
get { return _a; }
private set {
if (value < 0 || value > 10)
{
throw new ArgumentOutOfRangeException("A");
}
_a = value;
}
}
But on the other hand, it doesn't hurt to mark the property being public in the first place, does it?
Changing both modifiers is perfectly valid, so I would not bother much about the privat setter:
public int A
{
get{return _a;}
private set {_a = value;}
}
This is just my guess that the warning comes from the way the compiler re-writes the properties into IL code. The properties will be written as each a getter and setter method with the same modifier as the property itself.
If you now try to define a private setter of a private property, this would translate into:
private private get_A()
{
return _a;
}
And this doubled private modifier would clearly not compile.
The code in your example doesn't make sense. The setter is private as well if your property is private. you only need to specify the access modifier on the setter, if the setter has to have another access modifier then the getter.
I think you are wanting to do the following...
private int _a;
public int A
{
get { return _a; }
private set { _a = value; }
}
This makes the get accessor public but the set private.

Getters, setters, and properties best practices. Java vs. C#

I'm taking a C# class right now and I'm trying to find out the best way of doing things. I come from a Java background and so I'm only familiar with Java best-practices; I'm a C# novice!
In Java if I have a private property, I do this;
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
In C#, I see that there are many ways of doing this.
I can do it like Java:
private string name;
public void setName(string name) {
this.name = name;
}
public string getName() {
return this.name;
}
Or I can do it this way:
private string name;
public string Name {
get { return name; }
set { name = value; }
}
Or:
public string Name { get; set; }
Which one should I use, and what are the caveats or subtleties involved with each approach? When creating classes, I am following general best-practices that I know from Java (especially reading Effective Java). So for example, I am favoring immutability (providing setters only when necessary). I'm just curious to see how these practices fit in with the various ways of providing setters and getters in C#; essentially, how would I translate best-practices from the Java world into C#?
EDIT
I was posting this as a comment to Jon Skeet's answer but then it got long:
What about a non-trivial property (i.e., with significant processing and validation perhaps)? Could I still expose it via a public property but with the logic encapsulated in get and set? Why would/should I do this over having dedicated setter and getter methods (with associated processing and validation logic).
Pre-C# 6
I'd use the last of these, for a trivial property. Note that I'd call this a public property as both the getters and setters are public.
Immutability is a bit of a pain with automatically implemented properties - you can't write an auto-property which only has a getter; the closest you can come is:
public string Foo { get; private set; }
which isn't really immutable... just immutable outside your class. So you may wish to use a real read-only property instead:
private readonly string foo;
public string Foo { get { return foo; } }
You definitely don't want to write getName() and setName(). In some cases it makes sense to write Get/Set methods rather than using properties, particularly if they could be expensive and you wish to emphasize that. However, you'd want to follow the .NET naming convention of PascalCase for methods, and you wouldn't want a trivial property like this to be implemented with normal methods anyway - a property is much more idiomatic here.
C# 6
Hooray, we finally have proper read-only automatically implemented properties:
// This can only be assigned to within the constructor
public string Foo { get; }
Likewise for read-only properties which do need to do some work, you can use member-bodied properties:
public double Area => height * width;
If all you need is a variable to store some data:
public string Name { get; set; }
Want to make it appear read-only?
public string Name { get; private set; }
Or even better...
private readonly string _name;
...
public string Name { get { return _name; } }
Want to do some value checking before assigning the property?
public string Name
{
get { return m_name; }
set
{
if (value == null)
throw new ArgumentNullException("value");
m_name = value;
}
}
In general, the GetXyz() and SetXyz() are only used in certain cases, and you just have to use your gut on when it feels right. In general, I would say that I expect most get/set properties to not contain a lot of logic and have very few, if any, unexpected side effects. If reading a property value requires invoking a service or getting input from a user in order to build the object that I'm requesting, then I would wrap it into a method, and call it something like BuildXyz(), rather than GetXyz().
Use properties in C#, not get/set methods. They are there for your convenience and it is idiomatic.
As for your two C# examples, one is simply syntactic sugar for the other. Use the auto property if all you need is a simple wrapper around an instance variable, use the full version when you need to add logic in the getter and/or setter.
In C# favor properties for exposing private fields for get and/or set. The thie form you mention is an autoproperty where the get and set automatically generate a hidden pivot backing field for you.
I favor auto properties when possible but you should never do a set/get method pair in C#.
public string Name { get; set; }
This is simply a auto-implemented property, and is technically the same as a normal property. A backing field will be created when compiling.
All properties are eventually converted to functions, so the actual compiled implementation in the end is the same as you are used to in Java.
Use auto-implemented properties when you don't have to do specific operations on the backing field. Use a ordinary property otherwise. Use get and set functions when the operation has side effects or is computationally expensive, use properties otherwise.
Regardless of which way you choose in C# the end result is the same. You will get a backinng variable with separate getter and setter methods. By using properties you are following best practices and so it's a matter of how verbose you want to get.
Personally I would choose auto-properties, the last version: public string Name { get; set; }, since they take up the least amount of space. And you can always expand these in the future if you need add something like validation.
Whenever possible I prefer public string Name { get; set; } as it's terse and easily readable. However, there may be times when this one is necessary
private string name;
public string Name {
get { return name; }
set { name = value; }
}
In C# the preferred way is through properties rather than getX() and setX() methods. Also, note that C# does not require that properties have both a get and a set - you can have get-only properties and set-only properties.
public boolean MyProperty
{
get { return something; }
}
public boolean MyProperty
{
set { this.something = value; }
}
First let me try to explain what you wrote:
// private member -- not a property
private string name;
/// public method -- not a property
public void setName(string name) {
this.name = name;
}
/// public method -- not a property
public string getName() {
return this.name;
}
// yes it is property structure before .Net 3.0
private string name;
public string Name {
get { return name; }
set { name = value; }
}
This structure is also used nowadays but it is most suitable if you want to do some extra functionality, for instance when a value is set you can it to parse to capitalize it and save it in private member for alter internal use.
With .net framework 3.0
// this style is introduced, which is more common, and suppose to be best
public string Name { get; set; }
//You can more customize it
public string Name
{
get;
private set; // means value could be set internally, and accessed through out
}
Wish you better luck in C#
As mentioned, all of these approaches result in the same outcome. The most important thing is that you pick a convention and stick with it. I prefer using the last two property examples.
like most of the answers here, use Automatic properties. Intuitive, less lines of code and it is more clean. If you should serialize your class, mark the class [Serializable]/ with [DataConract] attribute. And if you are using [DataContract] mark the member with
[DataMember(Name="aMoreFriendlyName")]
public string Name { get; set; }
Private or public setter depends on your preference.
Also note that automatic properties require both getters and setters(public or private).
/*this is invalid*/
public string Name
{
get;
/* setter omitted to prove the point*/
}
Alternatively, if you only want get/set, create a backing field yourself
Which one should I use, and what are the caveats or subtleties involved with each approach?
When going with properties there is one caveat that has not been mentioned yet: With properties you cannot have any parametrization of your getters or setters.
For example imagine you want to retrieve a list items and want to also apply a filter at the same time. With a get-method you could write something like:
obj.getItems(filter);
In contrast, with a property you are forced to first return all items
obj.items
and then apply the filter in the next step or you have to add dedicated properties that expose items filtered by different criteria, which soon bloats your API:
obj.itemsFilteredByX
obj.itemsFilteredByY
What sometimes can be a nuisance is when you started with a property, e.g. obj.items and then later discovered that getter- or setter-parametrization is needed or would make things easier for the class-API user. You would now need to either rewrite your API and modify all those places in your code that access this property or find an alternative solution. In contrast, with a get-method, e.g. obj.getItems(), you can simply extend your method's signature to accept an optional "configuration" object e.g. obj.getItems(options) without having to rewrite all those places that call your method.
That being said, (auto-implemented) properties in C# are still very useful shortcuts (for the various reasons mentioned here) since most of the time parametrization may not be needed – but this caveat stands.

Accessing members in your own class: use (auto)properties or not?

I've created this "question" as a community-wiki, because there is no right or wrong answer. I only would like to know how the community feels about this specific issue.
When you have a class with instance variables, and you also created properties that are simply getters and setters for these instance variables, should you use the properties inside your own class, or should you always use the instance variable?
Having auto-properties in C# 3.0 made this an even harder decision.
Using properties:
public class MyClass
{
private string _name;
// could be an auto-property of-course
public string Name { get { return _name; } set { _name = value; } }
public void Action()
{
string localVar = Name;
// ...
Name = "someValue";
// ...
}
}
Using instance variables:
public class MyClass
{
private string _name;
public string Name { get { return _name; } set { _name = value; } }
public void Action()
{
string localVar = _name;
// ...
_name = "someValue";
// ...
}
}
(for those who hate member prefixes, I apologize)
Personally, I always use the latter (instance variables), because I feel that properties should only be used by other classes, not yourself. That's why I mostly stay away from auto-properties as well.
Of course, things change when the property setter (or getter) does a little more than just wrapping the instance variable.
Are there compelling reasons to pick one or the other?
I always use instance variables as well. The reason is because properties might be doing stuff like validating arguments (like in a setter) for not null or not empty. If you're using the variable inside your class code, there's no need to go through the extra overhead of those checks (assuming you know the variable value is valid). The properties could be doing other things as well (logging, for example), that are important for the public API, but not for internal usage, so again, it's better to avoid the overhead and just use the instance variable in my opinion.
I think it becomes more difficult to change the internal implementation if the code uses its own public interface.
Difficult to explain but consider these expressions:
mTotalPrice = mPrice * mQuantity;
mTotalPrice = Price * Quantity;
What to do in the second expression if I need to change the internals to express all prices in € instead of $ (without affecting the public interface which still uses $)?
One solution is to make the expression more complex by adding the opposite of the change in the property.
mTotalPrice = Price / Rate * Quantity
The other solution is to start to use the private field instead.
mTotalPrice = mPrice * Quantity
In the end you get a mix of private and public use. The only way to get consistent use is to always use the private field.
I don't like prefixing members either, but actually I find I can write something like this accidently and not spot it until run time. Which kinda tempts me to avoid using properties where they're not necessary... but I still do, currently!
Public String MyString
{
{ get { return this.MyString; } } //<== Stack Overflow
{ set { this.myString = value; } }
}
private String myString;
I think that there is no difference between these two approaches.
Auto-implemented properties is just a quick way to access private members which are created any way.
Example from MSDN:
class Customer
{
// Auto-Impl Properties for trivial get and set
public double TotalPurchases { get; set; }
public string Name { get; set; }
public int CustomerID { get; set; }
// Constructor
public Customer(double purchases, string name, int ID)
{
TotalPurchases = purchases;
Name = name;
CustomerID = ID;
}
// Methods
public string GetContactInfo() {return "ContactInfo";}
public string GetTransactionHistory() {return "History";}
// .. Additional methods, events, etc.
}
99% of the time I use the property rather then the instance variable. In the past, I've worked with a lot of code that used the instance variable and when there was a bug associated with that variable, I had to put a breakpoint on every line of code that referenced it.
I decided to use properties instead, either public or private, to wrap around the instance variable. Doing this means that I only have to put a breakpoint in the getter/setter of the property if I need to debug an issue with the instance variable, rather then having (potentially) a lot of breakpoints scattered all over the code.

Categories

Resources