why we need accessor in autoimplemented property in c#? - c#

I have some doubts on the auto-implemented property. Why do we first get, and then set the value?

What you've have posted is not an auto property.
Below is an example class that contains 1 auto property and a custom property similar to what you have done.
public class MyPropertyClass
{
public MyPropertyClass(bool affectLogic)
{
_affectLogic = affectLogic;
}
private readonly bool _affectLogic;
public string MyAutoProperty { get; set; }
private string _myPropertyWithLogic;
public string MyPropertyWithLogic
{
get
{
if (_affectLogic)
_myPropertyWithLogic = "Some value";
return _myPropertyWithLogic;
}
set
{
if (_affectLogic)
{
_myPropertyWithLogic = "Some value";
}
else
{
_myPropertyWithLogic = value;
}
}
}
}
The autoproperty "MyAutoProperty" provides a mechanism for simply getting and setting property values.
What you have posted in a standard property that allows you to perhaps manipulate or return the property value based upon certain conditions. In your post you are checking to see if the value posted in is null before setting.
If you do not need to access the property outside of the class then you do not need to have the get method. If you remove the get then you are creating a "WriteOnly" property which is bad practice.
Create a public method on the class that accepts the "Alert" value. If you dont need to access the property outside of the class then dont create a property at all.
public void SetMyProperty(string value)
{
_myPropertyWithLogic = value;
}

Related

How to add a property to represent a sample name that may not be changed once initialized?

I am trying to make a property in my class. What would I need to do where once the property is initialized, it cannot be changed?
These are the actual instructions:
Create a class in the existing namespace, either in an existing code
file or in a new file, to represent the amount in pounds of dirt
sample. In this class (a) do not create constructors. (b) inherit the
sand class (to make use of the sand property). (c) add a property to
represent the sample name. This property may not be changed once
initialized. (d) add a property to represent and process assignments
the quantity of clay, with a minimum value of 0. (e) add methods to
return the weight of the sample, the percentage of sand in the sample
and the percentage of clay in the sample.
I am on part (c). I have tried to exclude setters. Then, I've tried to use readonly, but it cannot work because my class cannot have constructors.
public class AmountSand //parent class
{
public class AmountSand {
private double quantity;
public double Sand {
get {
return quantity;
}
set {
if (value >= 0) quantity = value;
}
}
}
public class AmountDirt: AmountSand { //part (b): inherited the parent class, AmountSand
private string name = null;
private double clay;
public string Name { //here is where the specific property starts
get {
return name;
}
set {
if (name == null)
name = value;
}
} //ends
public double Clay {
get {
return clay;
}
set {
if (value >= 0) clay = value;
}
}
Depends on from where you would like it to be initialized.
EDIT: sorry, i didn't read that your class could have ctors, but i'll keep this in for completeness. It seems kinda weird that your class can't have ctors. May I ask why?
From the ctor:
class MyClass
{
public MyClass()
{
Name = "Muhammed";
}
public MyClass(string newName)
{
Name = newName;
}
public string Name{get;}
}
If you'd like it to be initialized from outside the class, your code is not too far off. You could even remove the backing property. I'd use
if(string.IsNullOrEmpty(Name))
rather than comparing to null.
if you'd like it to be set from a method inside your class:
public string Name{get; private set;}
Strings are already immutable by nature, so you need to clarify what you're trying to accomplish.
However, if you simply don't want anything else to be able to set the value other than the class itself, then you can make the set accessor private.

Accessing the private field of an auto-implemented property

Below, when I attempt to use the _currentTemp variable, that was supposed to be auto-generated via the auto properties functionality, I get a variable not found message:
The name _currentTemp does not exist in the current context.
Using { get; set; } should automatically create this private variable (_currentTemp), right?
public class DogTemperature
{
public double CurrentTemp { get; set; }
public DogTemperature(double dCurrentTemp)
{
_currentTemp = dCurrentTemp; //***this line***
}
}
Backing fields created by auto-properties are not available for you to interact with in your source code, as it is generated by the compiler.
If you want to interact with the backing field, you'll need to create your properties the verbose way.
In my opinion defining a property like this is complely pointless if all you want to do is store a value.
double _currentTemp;
public double CurrentTemp
{
get { return _currentTemp; }
set { _currentTemp = value; }
}
All you're doing here is giving the private context two ways to set the same value. You can set the _currentTemp field directly or you can set the CurrentTemp property which sets the _currentTemp field. If you are not doing anything with the property then just use the default get/set like this:
public double CurrentTemp { get; set; }
If you need to do more complex work in the property then go ahead and define a field like this. More complex work such as conditions, calculations or raising events:
double _currentTempFarenheit;
double _currentTempCelcius;
public double CurrentTemp
{
get
{
if(UseFarenheit)
return _currentTempFarenheit;
else
return _currentTempCelcius;
}
set
{
if(UseFarenheit)
_currentTempFarenheit = value;
else
currentTempCelcius = value;
}
}
Furthermore if you only want the value of your property to be set by the constructor of your DogTemperature class then you should make the setter private. This will only allow the property to be publically read.
public double CurrentTemp { get; private set; }
Based on #Alex Gravely's answer...
If I'm understanding your necessity for a full property: you can create full properties and backing fields like this:
private double _currentTemp;
public double CurrentTemp
{
get { return _currentTemp; }
set { _currentTemp = value; }
}
Then in your constructor for DogTemperature, you just need to set the CurrentTemp to the double you passed in:
public void DogTemperature(double temp)
{
DogTemperature = temp;
}
Depending on what usage you want to get out of the CurrentTemp property - i.e. to display in a View and updating it; you may want to read into implementing INotifyPropertyChanged. Here's a link: https://msdn.microsoft.com/en-us/library/ms229614(v=vs.100).aspx
If it is just a plain old property, and not used for anything special (such as in a model, for example); then the
public double DogTemperature { get; set; }
property will suffice; setting it in the constructor as above.
Hope this helps!

Tackling properties in the programming

I am asking a beginner level question. Though I am working in MVC but I am really confused with a simple concept and that is "Properties". There are lot of questions that
I have already gone through but there is surely a doubt in mind and did'nt able to clear it up.
Actually c# properties used for getting and setting the value to the private fields.
Like
Public class MyClass
{
private int number;
public int Number{
get{ return this.number;}
set{ number=Value }
}
}
class Program
{
static void Main()
{
MyClass example = new MyClass();
example.Number = 5; // set { }
Console.WriteLine(example.Number); // get { }
}
}
Now , the value is assigned to property also and to the variable also. Right?
Now , here is my doubt::
When we create property in model for MVc structure, we only have
public int Number{get;set;}
If this is okay to work with then why we are creating unnecessorily one more field of private access specifier. If encapsulation is the reason for that or hiding the data then why not in model in MVC?
Actually, in the above class example can I only use
Console.WriteLine(example.number);
after declaring it public?
Then what's the use of creating property over here?
Properties can be used to a store and retrieve values from a backing field (number in your case) directly as in your first sample. But property getters and setters are ordinary blocks of code that you can use as you want. So you don't have to assign a backing field, but can derive the value of a property also from another property in a getter, e.g.
public int NumberTimesTwo
{
get
{
return Number * 2;
}
}
However, as a common scenario is to have a property retrieve and assign the value of a backing field, there is a shortcut that you can use:
public int Number { get; set; }
In this case, the compiler automatically creates a private backing field that the property retrieves in the getter and assigns in the setter, so the code is equivalent to the following, but less to type:
private int _number;
public into Number
{
get
{
return _number;
}
set
{
_number = value;
}
}
As the backing field is also private, you cannot access it from outside of the class directly.
private int myVar;
public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
You are implementing Encapsulation by using MyProperty, which is public to access myVar which is private and is accessible only in the block where defined, that is, your class and not outside it.
Btw, in what way does this QA not answer your question? Try going through this for further reference.

c# property setter body without declaring a class-level property variable

Do I need to declare a class-level variable to hold a property, or can I just refer to self.{propertyname} in the getter/setter?
In other words, can I do this? (where I haven't defined mongoFormId anywhere):
public string mongoFormId
{
get
{
return this.mongoFormId;
}
set
{
this.mongoFormId = value;
revalidateTransformation();
}
}
You can either use automatic accessors or implement your own. If you use automatic accessors, the C# compiler will generate a backing field for you, but if you implement your own you must manually provide a backing field (or handle the value some other way).
private string _mongoFormId;
public string mongoFormId
{
get { return this._mongoFormId; }
set
{
this._mongoFormId = value;
revalidateTransformation();
}
}
UPDATE: Since this question was asked, C# 6.0 has been released. However, even with the new syntax options, there is still no way to provide a custom setter body without the need to explicitly declare a backing field.
You need to set a field variable and store the value there, if you're going to use custom getter and setter.
With the code you have right now you will be running into a stack overflow exception. When you assign something to mongoFormId, you'll execute the line this.MongoFormId = value;. This is an assignment to mongoFormId, resulting in executing the line this.MongoFormId = value;, and so on. It won't ever stop.
The correct way is a field:
private string _mongoFormId;
public string mongoFormId {
get { return this._mongoFormId; }
set {
this._mongoFormId = value;
revalidateTransformation();
}
}
You should have a backing variable. Take a closer look:
get { return this.mongoFormId; }
Is going to call the getter on mongoFormId, which will call that code again, and again, and again! Defining a backing variable will avoid the infinite recursive call.
Check MSDN Properties Overview
While a property definition generally includes a private data member,
this is not required. The get accessor could return a value without
accessing a private data member. One example is a property whose get
method returns the system time. Properties enable data hiding, the
accessor methods hide the implementation of the property.
You can do it both the ways.
If you want to have a class level member variable then do it this way -
public class sampleClass
{
private string _mongoFormId;
public string mongoFormId {
get { return _mongoFormId; }
set {
_mongoFormId = value;
revalidateTransformation();
}
}
}
Or do this simple in class, if no need for revalidateTransformation() execution call there
public class sampleClass
{
public string mongoFormId {get; set;}
}
This won't work since you get a recursive call to the property.
If I'm not mistaken, the result will be a StackOverflowException.
You must use a variable.
private string mongoFormId;
public string MongoFormId
{
get
{
return this.mongoFormId;
}
set
{
this.mongoFormId = value;
revalidateTransformation();
}
}
If you don't have to execute revalidateTransformation, you can use the auto-property.
This will create a backingfiled for you behind the scene.
public string MongoFormId { get; set; }
With the code you wrote, you are creating a recursive endless loop on both the get and set. The this keyword refer to the current class, not the property you are in.
So yes, you need to declare a private field. And to avoid confusion, create properties following the MSDN Naming Guideline (Use Pascal case for properties, camel case for private fields). And please do the same for your methods, it should be RevalidateTransformation instead of revalidateTransformation if you follow the C# convention instead of java's.
private string mongoFormId;
public string MongoFormId
{
get
{
return mongoFormId;
}
set
{
mongoFormId = value;
RevalidateTransformation();
}
}
public string mongoFormId {
get {
return this.mongoFormId;
}
set {
this.mongoFormId = value;
revalidateTransformation();
}
}
this way you have the Function recursive on all paths
The only way i see is to use a private data member. As other boys tells.

How to handle properties with dynamic defaults

I often have a situation like this when creating simple data objects. I have a property called Label that should have a default based on the Name of the object. So if no label is set then the Name is used otherwise use the set Label. A simple example in C#
public class FooBat {
public string Name { get; set; }
public string Label {
get {
if (_label == null) return Name;
return _label;
}
set { _label = value; }
}
}
Now the problem is if you want to edit this object you can't just bind to the Label property or you will get the default value and it will look as if there is a value there when there really isn't. So what I end up doing is create another, read-only property that does the defaulting and I use that is all instances except for when the base object is being edited. This leads to many extra properties with weird names like LabelWithDefault. Another alternative I've tried is to make Label handle the defaulting and make a new property called RealLabel that is used for editing the base object. This is just as bad.
I've thought of moving the defaulting code somewhere else but I haven't found a good place for it in any "normal" model that does not replicate the defaulting code many times.
What I have started to do now is initialize the Label field when the Name field is set (and the Label field is not) and then treat the Label field as a normal field. This works but now the code for defaulting is tied to the wrong property. Why should the Name know that the Label field cares about it? So this is also not "right."
Does anyone have any better ways of handling this problem?
I think there is a little confusion about what I'm asking for. Basically I need two different views to the same object for two different uses. In the first is the editing of the object itself where I want unset fields to show as empty (unset). The second is for all other cases (including when the object is the value of a field of another object) where I want to show each field with its dynamically determined default. Just setting the default the first time doesn't no help because if the (in this case) Name field changes then the Label field must also change until the Label field is set.
The answers are getting closer but I still think that they are too targeted to the example I gave. I was trying to give a concrete example for expository purposes but in reality this is more of a best-practices issue. The example I gave was C# and for a string property but I have the same problem with most languages and systems that I use that have frameworks where the data access and data display are handled for you as well as for data types other than strings. Changing the object that is queried from the data source is possible but often tricky and knowing when to make the change (use a sublclass in this case but not in that one) is particularly difficult.
public class FooBat {
public string Name { get; set; }
public string Label {
get {
if (_label == null)
_label = Name;
return _label;
}
set { _label = value; }
}
}
Regarding your update:
You could subclass your object. The base-class would return null if the field has not been set and the sub-class would return your default value. Thus if you need to query if a value has been set, you would cast to the base-class.
Deleted previous answers/updates for brevity.
Update 2:
I would have to say the best way is to track whether the property has been set or not with an IsPropertySet bool. The Getter for the property would check that value to see if it should be returning its own value or the default value. And the setter for the property would set the IsPropertySet according to the set value (true if the value is not null, false if it is). The code that is using the class could then look at the IsPropertySet value to determine if it is receiving a set value or the default when it calls the Property's Getter.
public class FooBat {
public string Name { get; set; }
public bool IsLabelSet { get; set; }
public string Label {
get {
if (IsLabelSet)
return _label;
else
return Name;
}
set {
IsLabelSet = value != null;
_label = value;
}
}
}
I use a Nameable interface a lot (with getName()). Before I start, I'll suggest that you don't want to do this at all. It should be the domain of your display logic, not your domain objects. Usually it's the code consuming the FooBat that is able to make this decision in a better way than the object itself. That aside...
public interface Label{
string getLabel();
boolean isDefault(); //or isValued() or use instanceof expressions
}
public interface Nameable{
string getName();
}
public class FooBat implements Nameable {
public string Name { get; set; }
public Label Label {
get {
if (_label == null) {
_label = new DefaultLabel(this);
}
return _label;
}
set { _label = value; }
}
}
public class DefaultLabel implements Label{
public DefaultCharSequence(Nameable named){
this.named = named;
}
public string getLabel(){
return named.getName();
}
public boolean isDefault(){ return true; }
}
public class StringLabel implements Label {
...
}
It all essentially boils down to returning a better class for your label object.

Categories