This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you give a C# Auto-Property a default value?
Is there any nice way to provide a default value for an automatic property?
public int HowHigh { get; set; } // defaults to 0
If not explicitly set anywhere, I want it to be 5. Do you know a simple way for it? E.g. I could set it in constructor or something, but that's not elegant.
UPDATE: C# 6 has got it: http://geekswithblogs.net/WinAZ/archive/2015/06/30/whatrsquos-new-in-c-6.0-auto-property-initializers.aspx
No, there isn't any nice way of doing this - basically you have to set it in the constructor, which isn't pleasant.
There are various limitations to automatic properties like this - my biggest gripe is that there isn't a way to create a read-only automatic property which can be set in the constructor but nowhere else (and backed by a readonly field).
Best you can do is set it in the constructor, you cannot make changes within automatic properties, you will need a backing field and implement the setter/getter yourself otherwise.
Using a backing field you can write something like this:
private int _howHigh = 0;
public int HowHigh { get {return _howHigh; } set { _howHigh = value; } }
If the default value for the type is not sufficient, then the only way to do it is via a constructor.
In a word: No.
Automatic properties are a one trick pony, as soon as you need something extra (like a reasonable default value) you should revert to the backing field regular properties.
I'm a Resharper user, and it makes going from automatic to backed properties a breeze.
The constructor is NOT the only option you have.
I believe this is best:
private int m_HowHigh = 5;
public int HowHigh {
get { return m_HowHigh; }
set { m_HowHigh = value; }
}
I prefer this for readability purposes more than the ctor().
This is NOT what you want:
[DefaultValue(5)]
public int HowHigh { get; set; }
Reference: http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx#Y2248
Because this is only a decoration and does not set the value (in C#4).
Related
This question already has answers here:
Difference between Property and Field in C# 3.0+
(10 answers)
Closed 9 years ago.
why to use accessors in c#.net while we can use simple assignment like
public string name = "Haymen";
instead of doing this:
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
and how this property gonna set or return something since it don't have any way to set anything apparently ?
public class Movie
{
public int ID { get; set; }
}
Skeet has » an article about just that! Your case is covered by automatic properties, so you don't have all the writing work.
It depends on what your trying to do, you use accessors for a variety of reasons, one of which is to ensure that class properties are kept private and can only be directly manipulated internally.
An example :-
private int _myAge {get; set;}
public int MyAge
{
get
{
if(_myAge == null)
{
_myAge == GetMyAge();
}
return _myAge;
}
}
Use
public string name = "Haymen";
If you know for sure you will never need to debug the access to that variable (i.e. set a breakpoint when somebody reads/writes it).
If you know changing it will never effect the internal state of your object (i.e. side effect that you depend on or expect).
You want to have less lines to look at and you have met the above.
You want a "data only class" for XML Serialization and you don't want to create a lot of code to do the conversion for private methods (at least as of C# 3.5).
NOTE That being said, in general, you should not be exposing fields as public members. See here.
This question already has answers here:
Any reason to use auto-implemented properties over manual implemented properties?
(7 answers)
Closed 9 years ago.
What is more "true": use properties with or without private fields.
I.e.
1.
class A
{
int _field;
public int Field
{
get{ return _field;}
set{_field = value;}
}
}
2.
class A
{
public int Field{get;private set;}
}
Number 2 creates a backing field automatically, so you always have a private field "behind the scenes" (although not directly accessible in the latter case).
when you create anonymous property compiler creates corresponding field for you, so it's pretty much the same, but you can access autocreated field only via property
It makes no difference - the compiler generates the property implementation for you in exactly the same way that it generates a default constructor or the code for a using statement. These two classes are nearly 100% equivalent which you can see if you decompile an auto-property (the only difference is the name of the generated backing field that the compiler uses)
class A
{
public int Field {get; private set;}
}
class A
{
int _field;
public int Field
{
get { return _field; }
private set {_field = value; }
}
}
Its completely down to your personal preference.
As has already been stated, the second creates the backing field at compile time. You would typically define a backing field your self if you wanted the property to act as a public accessor to the field, where you can add custom logic or prevent the value being modified (using the private keyword on the setter).
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.
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.
In much of the code I have seen (on SO, thecodeproject.com and I tend to do this in my own code), I have seen public properties being created for every single private field that a class contains, even if they are the most basic type of get; set; like:
private int myInt;
public int MyInt
{
get { return myInt; }
set { myInt = value }
}
My question is: how does this differ from:
public int MyInt;
and if we should use properties instead of public fields why should we use them in this specific case? (I am not talking about more complex examples where the getters and setters actually do something special or there is only one get or set (read/write only) rather than just returning/setting a value of a private field). It does not seem to add any extra encapsulation, only give a nice icon in IntelliSense and be placed in a special section in class diagrams!
See this article http://blog.codinghorror.com/properties-vs-public-variables/
Specifically
Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
You can't databind against a variable.
Changing a variable to a property is a breaking change.
Three reasons:
You cannot override fields in subclasses like you can properties.
You may eventually need a more complex getter or setter, but if it's a field, changing it would break the API.
Convention. That's just the way it's done.
I'm sure there are more reasons that I'm just not thinking of.
In .Net 3.x you can use automatic properties like this:
public int Age { get; set; }
instead of the old school way with declaring your private fields yourself like this:
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
This makes it as simple as creating a field, but without the breaking change issue (among other things).
When you create private field name and a simple public property Name that actually gets and sets the name field value
public string Name
{
get { return name; }
}
and you use this property everywhere outside your class and some day you decide that the Name property of this class will actually refer to the lastName field (or that you want to return a string "My name: "+name), you simply change the code inside the property:
public string Name
{
get { return lastName; //return "My name: "+name; }
}
If you were using public field name everywhere in the outside code then you would have to change name to lastName everywhere you used it.
Well it does make a difference. Public data can be changed without the object instance knowing about it. Using getters and setters the object is always aware that a change has been made.
Remember that encapsulating the data is only the first step towards a better structured design, it's not an end-goal in itself.
You have to use properties in the following cases:
When you need to serialize data in the property to some format.
When you need to override properties in derived class.
When you implement get and set methods with some logic. For example, when you implement Singleton pattern.
When you're derived from interface, where property was declared.
When you have specific issues related to Reflection.
It... depends?
I always use getters & setters, since they created this shortcut:
public int Foo { get; set; }
At compile time it is translated. Now you can't get fancy with it, but it is there, and if you need to get fancy you just spell it out later.
However public, private, protected... it's all a matter of who you want to be able to tweak the data. We use inheritance a lot and this is a very common method for us, so that only chidren can edit certain properties.
protected _foo;
public Foo
{
get { return _foo; }
} //lack of set intentional.
I can't believe that with 11 answers, nobody has said this:
Not all private fields should be exposed as public properties. You should certainly use properties for anything that needs to be non-private, but you should keep as much of your class private as possible.
There are many reasons why.
Mainly:
You can do some other functions when the variable is set
You can prevent setting and provide only get
Some 'things' only work on properties (DataBinding, for example)
You can hide the implementation of the property [perhaps it is a ViewState variable, in ASP.NET).
The point is - what if further down the line you want to make sure that every time myInt is referenced something special happens (a log file is written to, it's changed to 42 etc)? You can't do that without getters and setters. Sometimes it's wise to program for what you might need, not what you need right now.
Actually, if you're using Silverlight, you'll realise that fields cannot be set a static resources and thus you'll have to use a property (even to access a const).
I've realised that when I tried to federate the region names I use in Composite Guidance (PRISM).
However, that's just a language limitations and apart from static/const fields I alsways use properties.
The idea is you should not accidentally/unintentionally change the value of a class private field outside.
When you use get and set, that means you are changing the class private field intentionally and knowingly.
Setting a value into a private field only changes that field,but making them in property you can handle another arguments for example,you can call a method after setting a value
private string _email;
public string Email
{
get
{
return this._email;
}
set
{
this._email = value;
ReplaceList(); //**
}
}
In simpler words, answer to your question is the access modifiers i.e. public and private.
If you use:
public int myInt;
public int MyInt
{
get { return myInt; }
set { myInt = value }
}
then both MyInt property and myInt variable is available in the project to be modified.
Means, if your class suppose A is inherited by class suppose B,
then myInt and MyInt both are available for modification and no check can be applied.
Suppose you want myInt value can be set in derive class if some particular condition pass.
This can be achieved only by making field private and property to be public.
So that only property is available and conditions can be set based on that.