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

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.

Related

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.

Understanding different ways of using accessors

For an object sellprint declared as static in the class
private static string sellprint = "";
public string Sellprint
{
get { return sellprint; }
}
public void SetSellprint(string x)
{
sellprint = x;
}
How is this
different from
public string Sellprint
{
get; set;
}
internally.
I could not find any examples of code 1 on msdn. what does it translate into?
The compiler creates a getter method for your property in the first code that returns the value of sellprint field because you implement only the getter method.In the second code, both getter and setter methods creating by compiler and also the backing-field.That's the difference.
You can verify that using ILDASM.exe:
First, consider this code:
class Foo
{
private string _value;
public string Value
{
get { return _value; }
}
public void SetValue(string str)
{
_value = str;
}
}
As you can see there is only one method generated by compiler which is get_Value.
If we change it like this and make the Value an auto-implemented property:
class Foo
{
public string Value { get; set; }
}
You can see that compiler creates both getter (get_Value) and setter (set_Value) method and also create a private backing field for the property.
There is no pros or cons about the functionality except in the second code you are doing the same work with less code.
1) should not work because there is no sellprint - assuming you have a field named sellprint and just forgot in your code snippet, you provide a get accessors and a method instead of the set accessors, which is kinda strange.
2) will create the field required automatically (and will not tell you the name, so you cannot accidentally use it)
There is not difference between those two though.

Auto-implemented properties and additional function

Is there a way to do something like this in C#:
public class Class2 {
public string PropertyName1 { get
{
return this; //i mean "PropertyName1"
}
set {
this = value;
DoAdditionalFunction();
}
}
Because I need to call additional function in the "set" I need to have an extra private field like
private string _propertyName1;
public string PropertyName1 { get
{
return _propertyName1;
}
set {
_propertyName1= value;
DoAdditionalFunction();
}
I don't want to use additional property like _propertyName1. Is there a way to accomplish this or any best practices?
No - if you need any behaviour other than the most trivial "set a field, return the field value", you need to write "full" properties. Automatically implemented properties are only a shorthand for trivial properties.
Note that you haven't really got an "extra" private field, in terms of the actual contents of an object - it's just that you're explicitly declaring the private field instead of letting the compiler do it for you as part of the automatically implemented property.
(It's not clear what your first property is trying to do - setting this in a class is invalid, and you can't return this from a property of type string unless you've got a conversion to string...)

Basic C# property question

In C# do properties need to reference private member variables, or can I just declare the properties and use them directly in the class code?
If the former is the best practice, then does that rule out using C# property short-hand? I.e.
public string FirstName { get; set; }
Properties, when implemented like this:
public string FirstName { get; set; }
Automatically create a private member variable (the compiler does this for you), so you don't have to worry about it. This will behave exactly the same as if you do:
private string firstName;
public string FirstName {
get { return firstName; }
set { firstName = value; }
}
There is no reason not to use the automatic properties ( { get; set; } ). The provide the same advantages as making your own private member variable.
In addition, if you later decide you need to do extra processing (for example, if you decide to implement INotifyPropertyChanged in your property setter), you can add this without changing your public API, but putting a backing field in manually.
You don't need properties to access private fields but in general it is considered best practice.
And you can use auto-properties (short hand) untill you need to add more functionality to a property, like validation. Changing it to a 'real' property is always a non-breaking change.
Properties created like this
public String Caption{ get; set; }
this will be compiled as
[CompilerGenerated]
private string <Caption>k__BackingField;
public string Caption
{
[CompilerGenerated]
get
{
return this.<Caption>k__BackingField;
}
[CompilerGenerated]
set
{
this.<Caption>k__BackingField = value;
}
}
The above code is extracted after compilation using reflector tool.
They do not need to reference private member variables. You can use them directly in the class.
Properties do not need to reference private member variables. It is best practice, though, to have them do so. You can think of properties as methods if it makes it easier to understand. You can run code inside of them. You can return whatever you want. You can call methods and use private member variables. You can even simply return a constant.
I use private member variables in almost all cases. It allows me to create a readonly property, or to provide some rules to those outside my class of getting or setting properties that my class doesn't have to follow.
To add on to Reed's answer, inside of your code (within the class itself) the member functions should adhere to this and actually use the Property rather then the actual private member. For instance if you had this:
public string FirstName { get; set; }
And you had a strange method called public char GetFirstLetter() that returned the first letter in a person's first name you'd want to do it like this:
public char GetFirstLetter()
{
return FirstName[0];
}
Instead of actually using your private variable. When you set a property a programmer may have written code to set it in a particular manner. So it only makes sense to simply use that property within your class methods.
C# can reference private variables as in:
public class A
{
private string _b;
public string B
{
get { return _b; }
set { _b = value; }
}
}
The get;set; designation is automatic properties which when compiled will generate the private variable for you, as a way to make it easy to setup your code.
Using properties is the best way to provide a method of control and security to the attributes in a class, always keep the attributes private if possible.
if you use like
public string FirstName { get; set; }
compiler will automatically adds getters and setters for this property automatically.it not a bad practice.
Here is the proof
if you declare
private string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
like this also compiler will takes it as
so its not ruled out... :)

When should you use a field rather than a property?

Can anyone clearly articulate when you use a field and when to use a property in class design?
Consider:
public string Name;
Or:
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
I realize that the second method is more proper and flexible, so that's what I try to use, generally.
But then why do I see people use the first method? Are they just lazy, or is there some specific situation where it's the correct choice? Is it just a matter of preference?
Well in C# 3.0 you can actually write:
public string Name {get; set;}
Which allows you to be proper and lazy.
Generally speaking, with properties, you get proper encapsulation. You have the choice to allow setting a value, or getting it, or both. Using a public member, you don't have that option.
It's probably one-part preference, and one-part how your team decides to handle quick and dirty class definitions, but I would say, use properties for get/sets.
To answer
Can anyone clearly articulate when you use an attribute and when to use a property in class design?
You shouldn't ever use a public attribute. You should always use a property instead. It's safer and more flexible. That said, people will be lazy, and just use a public member. However, with C# 3.0 you can use a more terse syntax to define properties, which should satisfy your inner laziness.
Simply type prop and hit <tab> to expedite the laziness in adding a property.
Just some additional information to Alan's reply:
public string Name {get; set;}
is the same as
private string _Name;
public string Name{
get { return _Name; }
set { _Name = value; }
}
If you want to disallow the set function of Name, you can have
public string Name {get; private set;}
Properties are more maintainable than fields, you can encapsulate logic in your setters/getters, allowing you to hide the implementation.
They also make refactoring easier.
More information:
Property Usage Guidelines
Field Usage Guidelines
Using properties you can control it's security:
public string Foo { protected get; private set; }
Properties gives easy way to raise events:
public string Foo
{
get { return _foo; }
}
set
{
bool cancel = false;
if(BeforeEvent != null) // EventHandler<CancelEventArgs> BeforeEvent
{
CancelEventArgs e = new CancelEventArgs();
BeforeEvent(this, e);
cancel = e.Cancel;
}
if(!cancel)
{
_foo = value;
if(AfterEvent != null) // EventHandler<EventArgs> AfterEvent
{
AfterEvent(this, new EventArgs());
}
}
}
Also I often use code like this:
string Foo
{
set
{
IsFooSet = value != null;
}
}
bool IsFooSet
{
get { return _isFoo; }
set
{
_isFoo = value;
if(value) // some event raise or controls on form change
}
}
When you make the field public, you allow the user to do whatever they want to do to the field. They can assign unexpected values, invalid values, values that can cause overflow, etc.
With the property, you have control over whether to allow the setting of new values to the field, massaging the value before storing it, notifying interested parties about the change of the field's value, etc. And the same idea for returning value through the getter. For .NET framework from 2.0 up, you can set the accessor for the getter, setter. Say, you only want the user to only have read access to the field, then you make the getter public, but the setter private or protected.
In addition to the already-given reasons for preferring properties, there's also lots of cool stuff in System.ComponentModel to do with data binding and change notification that only works with properties, rather than fields. For example, look at the documentation around PropertyChangedHandler.
A property like defined above acts like a getter and setter. The only benefits of using a property is that you can treat it like a variable with access restriction.
public string Name { get; private set; }
This property can be accessed publicly, but can only be set privately. (You wouldn't want anyone changing your name with out your consent now would you! ;) )

Categories