What is the meaning of "get"? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In C# what does this code with “get” mean?
I'm using open source project. In this project there is function.
public virtual ICollection<Customer> AffiliatedCustomers
{
get
{
return _affiliatedCustomers ?? (_affiliatedCustomers = new List<Customer>());
}
protected set { _affiliatedCustomers = value; }
}
I don't understand what is the meaning of "get".
Can you please explain this function.

AffiliatedCustomers is a property.
The get defines the property getter, which is a method used internally to return the value by the property. It allows you to use this given an instance of the class like so:
var customers = theClass.AffiliatedCustomers; // Looks like a field, but is a property
Properties can also have a set section, as well, as this one does (protected set { _affiliatedCustomers = value; }), which gives you control over what happens when you set the value via the Property.
For details, see Properties in C#.

This is not a function. It is a property. A property is basically a fancy wrapper for some variable. For example, declaring the following property:
public string SomeProperty { get; set; }
will actually compile to something like this:
private string backing_SomeProperty;
public void set_SomeProperty(string value)
{
backing_SomeProperty = value;
}
public int get_SomeProperty()
{
return backing_SomeProperty;
}
That's an example of an automatic property. Of course, you can also define the getter and setter methods yourself like this:
public string SomeProperty
{
get
{
// some logic code here
// then return some value
}
set
{
// some logic code here
// then set some value
}
}

This is a property,
Quoted by msdn:
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.
Please refer to this link for more:
http://msdn.microsoft.com/en-us/library/x9fsa0sw(v=vs.80).aspx

Properties have a getter and a setter - their purpose is obvious (to get and set the value of the property).
When you use auto properties, there is still a get and a set, but the backing variable is automatically implemented for you. In the example you have given the author of the code has chosen to have their own implementation of the get - in this case to automatically initialise the member variable the first time the property is accessed.

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.

What is the purpose of the "get" and "set" properties in C#

I saw some get set method to set values. Can anyone tell me the purpose of this?
public string HTTP_USER_NAME
{
get
{
return UserName;
}
set
{
UserName = value;
}
}
public string HTTP_USER_PASSWORD
{
get
{
return UserPwd;
}
set
{
UserPwd = value;
}
}
Actually why use these things. For global access, or is there some other reason for this type of thing?
They are just accessors and mutators. That's how properties are implemented in C#
In C# 3 you can use auto-implemented properties like this:
public int MyProperty { get; set; }
This code is automatically translated by the compiler to code similar to the one you posted, with this code is easier to declare properties and they are ideal if you don't want to implement custom logic inside the set or get methods, you can even use a different accessor for the set method making the property immutable
public int MyProperty { get; private set; }
In the previous sample the MyProperty will be read only outside the class where it was declared, the only way to mutate it is by exposing a method to do it or just through the constructor of the class. This is useful when you want to control and make explicit the state change of your entity
When you want to add some logic to the properties then you need to write the properties manually implementing the get and set methods just like you posted:
Example implementing custom logic
private int myProperty;
public int MyProperty
{
get
{
return this.myProperty;
}
set
{
if(this.myProperty <=5)
throw new ArgumentOutOfRangeException("bad user");
this.myProperty = value;
}
}
It seems as though you understand the functionality of getters and setters, and others answered that question. "Normal" class variables (without getters and setters) are called "fields", and "properties" (which have the getters and setters) encapsulate fields.
The purpose of properties is to control outside access to fields. If you want a variable to be read-only to outside logic, you can omit the setters, like so:
private int dataID;
public int DataID {
get { return dataID; }
}
You can also make the setter private and achieve the same read-only functionality.
If an object has a chance of being null (for whatever reason), you can guarantee an instance always exists like this:
private Object instance;
public Object Instance {
get {
if (instance == null)
instance = new Object();
return instance;
}
}
Another use for properties is defining indexers.
//in class named DataSet
private List<int> members;
public int this[int index] {
get { return members[index]; }
}
With that indexer defined, you can access an instance of DataSet like this:
int member = dataSet[3];
Check these links,.. they gives clear explanation.
http://www.dotnetperls.com/property
http://code.anjanesh.net/2008/02/property-getters-setters.html
if UserName and UserPwd are class variables, better to use like this
_userName
_userPwd
Standard way to implement properties in C#. UserName and UserPwd are private member variables (string type) of the class where these 2 methods are defined.
HTTP_USER_NAME and HTTP_USER_PASSWORD are the public properties of your class. UserName and UserPwd could be your private field. And you are allowing other people to set or get the values via these public properties. No direct accesss to private propeties. Also you can do some logic inside the get method of the property.Ex : you will have a public property called Age and in the get method of that, you may read the value of your private field called "dateOfBirth" and do some calculation ( CurrentYear-dateOfBirth) and return that as the Age.
Properties are just accessors over fields. They allow to do certain operations (if needed), and provide controlled access to fields.
If you want to know when to use Properties, and when to use Only fields, Check the link Properties vs Fields – Why Does it Matter? (Jonathan Aneja)
From Properties (C# Programming Guide)
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
In this example, the TimePeriod class stores a time period. Internally the class stores the time in seconds, but a property named Hours enables a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.
Example
class TimePeriod
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
class Program
{
static void Main()
{
TimePeriod t = new TimePeriod();
// Assigning the Hours property causes the 'set' accessor to be called.
t.Hours = 24;
// Evaluating the Hours property causes the 'get' accessor to be called.
System.Console.WriteLine("Time in hours: " + t.Hours);
}
}
// Output: Time in hours: 24
Properties Overview
Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.
A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. For more information, see Restricting Accessor Accessibility (C# Programming Guide).
The value keyword is used to define the value being assigned by the set accessor.
Properties that do not implement a set accessor are read only.
For simple properties that require no custom accessor code, consider the option of using auto-implemented properties. For more information, see Auto-Implemented Properties (C# Programming Guide).

Honestly, what's the difference between public variable and public property accessor? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
What is the difference between a field and a property in C#
Should I use public properties and private fields or public fields for data?
What is the difference between:
public string varA;
and
public string varA { get; set; }
The public property accessor gives you more flexibility in the future.
If you want to add validation to setting the value, you simply write a non-default setter. None of your other code would have to be modified.
There could also be reasons you'd want to replace the default getter with code. That can be a real pain with a public variable.
In addition to the other answers, you can also use a property to make the value read-only or even set-only:
public int Item { get; private set; } // read-only outside the class. Can only be set privately.
I have also run into situations where I later decide I want to proxy an object, or add AOP, which basically requires properties.
Public property accesses fields and internal class code through exposed getter and setter methods. A public field acesses the field directly.
Using propertys offers the potential to provide a layer of abstraction and design (ability to make set accessor protected, private).
When a property is specified and no body present an underlying private field is created by the compiler that is used to store the value against. Essentially:
private int item = 0;
public int Item {
get { return item; }
set {item = value; }
}
In general I tend to use properties for public exposed variables and fields for private. I might consider using a field if that field was accessed many times and speed was a crucial design requirement.

c# what is the point of using SET?

why do we do this:
private string StatusText
{
set { toolStripStatusLabel1.Text = value; }
}
instead of just this?
private string StatusText
{
toolStripStatusLabel1.Text = value;
}
i do not understand the point of using set?
These are two completely different things.
This is a method:
private string StatusText()
{
toolStripStatusLabel1.Text = value;
}
which is called like this:
StatusText();
(and which will not compile, because the local variable value cannot be found). To make it work, you would need to write it like this:
private string StatusText(string value)
{
toolStripStatusLabel1.Text = value;
}
and call it like this:
StatusText("bla");
On the other hand, this is the definition of a property:
private string StatusText
{
set { toolStripStatusLabel1.Text = value; }
}
whose setter (hence the keyword set) is called like this:
StatusText = "bla";
Because there could also be a get:
get { return toolStripStatusLabel1.Text; }
Properties are syntactic sugar. When compiled you will have two methods get_[property name] and set_[property name]. If you only have the set method, only the set_[propety name] will be in the IL.
In a little more detail, since the OP has said she doesn't understand gets and sets:
The get and set keywords are used to define a "property". A property is a pair of methods - a "getter" and "setter" - that are used behind the scenes when the property is used or written to by other code. The advantage of a property over explicitly defining getter and setter methods is that you can use the property as if it were a "field" (a simple, publicly-visible member variable). The advantage of using a property instead of a field is that a property allows you to customize the behavior of assigning or using a variable. You can create "calculated fields" that are evaluated when needed based on other data in the object, or include basic validation or other business logic when reading or writing a value.
To define a property, you start by declaring it like you would a field, but then add a code block with get and set sub-blocks. You then define its read behavior in the get block, and the write behavior in the set block. You can choose to define only one accessor (making a "read-only" or "write-only" property), or you can define more limited visibility for one function or the other; for instance, you can make the getter public but the setter protected, so everyone can examine the property's value but only the class's other members and derived types can set its value.
The most common property implementation uses a "backing field", a private variable that acts as the store for the value exposed by the property. To streamline this implementation, .NET 3.0 included the concept of an "auto-property"; if you didn't define the code bodies of the getter and setter, the compiler would generate a basic implementation using a backing field.
First will not compile for value isn't valid unless you have set.
private string StatusText
{
toolStripStatusLabel1.Text = value;
}
Check out MSDN on Accessors here.
Setting and Getting fields and properties...
Example:
private string statusText;
public string StatusText
{
get { return this.statusText;}
set { this.statusText = value;
toolStripStatusLabel1.Text = this.statusText;
}
}
private String StatusText
{
get { ... }
set { ... }
}
The get/set tokens are to distinguish between the get and set accessors.
The latter wouldn't compile. The set part shows that it's the setter part of a property.
An alternative is to just write a method:
private void SetStatusText(string value)
{
toolStripStatusLabel1.Text = value;
}
To enable you to apply more complex logic, when the need will arise.

Acessing the backing field in an auto property

Is there any way to access the backing field for a property in order to do validation, change tracking etc.?
Is something like the following possible? If not is there any plans to have it in .NET 4 / C# 4?
public string Name
{
get;
set
{
if (value != <Keyword>)
{
RaiseEvent();
}
<Keyword> = value;
}
}
The main issue I have is that using auto properties doesn't allow for the same flexibility in validation etc. that a property with a explicit backing field does. However an explicit backing field has the disadvantage in some situations of allowing the class it is contained in to access the backing field when it should be accessing and reusing the validation, change tracking etc. of the property just like any other class that may be accessing the property externally.
In the example above access to the backing field would be scoped to the property thus preventing circumvention of the property validation, change tracking etc.
Edit: I've changed < Backing Field > to < Keyword >. I would propose a new keyword similar to value. field would do nicely although I'm sure it's being used in a lot of existing code.
No there isn't. If you want to access the backing field, then don't use auto properties and roll your own.
I agree that it would be great to have a field that was only accessible by the property and not by the rest of the class. I would use that all the time.
As the MSDN states:
"In C# 3.0 and later, auto-implemented
properties make property-declaration
more concise when no additional logic
is required in the property accessors.
They also enable client code to create
objects When you declare a property as
shown in the following example, the
compiler creates a private, anonymous
backing field can only be accessed
through the property's get and set
accessors."
Since you have additional logic in you accessors, the use of auto-implemented properties is not appropriate in your scenario.
While the backing field does exist, it is given a mangled name to stop you referencing it easily - the idea is that you never reference the field directly. For interests sake, you can use Reflector to disassemble your code and discover the field name, but I would recommend you not use the field directly as this name may indeed be volatile, so your code could break at any time.
Having read your comments in Mehrdad's answer, I think I understand your problem a bit better.
It appears that you are concerned about the ability of the developer to access private state in the class they are writing, bypassing your validation logic, etc. This suggests that the state should not be contained in the class at all.
I would suggest the following strategy. Write a generic class that represents a ValidatedValue. This class holds only the backing value and only allows access/mutation via get and set methods. A delegate is passed to the ValidatedValue to represent the validation logic:
public class ValidatedValue< T >
{
private T m_val;
public ValidationFn m_validationFn;
public delegate bool ValidationFn( T fn );
public ValidatedValue( ValidationFn validationFn )
{
m_validationFn = validationFn;
}
public T get()
{
return m_val;
}
public void set(T v)
{
if (m_validationFn(v))
{
m_val = v;
}
}
}
You could, of course, add more delegates as required (eg, to support pre/post change notification).
Your class would now use the ValidatedValue in place of a backing store for your property.
The example below shows a class, MyClass, with an integer that is validated to be less than 100. Note that the logic to throw an exception is in MyClass, not the ValidatedValue. This allows you to do complex validation rules that depend on other state contained in MyClass. Lambda notation was used to construct the validation delegate - you could have bound to a member function instead.
public partial class MyClass
{
private ValidatedValue<int> m_foo;
public MyClass()
{
m_foo = new ValidatedValue<int>(
v =>
{
if (v >= 100) RaiseError();
return true;
}
);
}
private void RaiseError()
{
// Put your logic here....
throw new NotImplementedException();
}
public int Foo
{
get { return m_foo.get(); }
set { m_foo.set(value); }
}
}
Hope that helps - somewhat off the original topic, but I think it's more inline with your actual concerns. What we have done is taken the validation logic away from the property and put it on the data, which is exactly where you wanted it.
No, but you can in a subclass:
public class Base
{
public string Name
{
get;
virtual set;
}
}
public class Subclass : Base
{
// FIXME Unsure as to the exact syntax.
public string Name
{
override set
{
if (value != base.Name)
{
RaiseEvent();
}
base.Name = value;
}
}
}
If you're gonna do so, why you are using auto properties?!
A simple property has done it way back in 1.0. I don't think it makes sense to add complexity to the language for every special case. You either need the property to do plain store/retrieve model or need more than that. In the latter case, a normal property will do.
You can't do this I'm afraid. That's one of the reasons I started writing MoXAML Power Toys, to provide the ability to convert automatic properties into Notify properties.

Categories

Resources