I'm a C# beginner, so easy explanations are greatly appreciated.
I was learning about properties, and got this question: properties give custom access logic to fields, but why can't the field itself contain its getter/setter? In other words, is there a reason why we can't get rid of Example and write custom get/setters under example(field)?
I could not find other posts that answer my question.
class MyClass
{
private int example = 5;
public int Example
{
get;
private set;
}
// here, this Example property only acts as a gateway for example.
// why is it not possible for the field 'example' to contain the
// get/set?
}
Property is an interface to Class, and not always is about storing data, you can always make the variable public member and will work perfectly like property, but the property has its own main job to work as an interface for that value with other classes.
While in many cases the property just works as public parameters, it is not always meant to be used in that way.
Related
This question already has answers here:
Auto-implemented getters and setters vs. public fields
(17 answers)
Closed 8 years ago.
I have looked at at least 10 SO questions on get/set but cannot find mine. So I hope this is not a duplicate.
public class myint
{
public int value{get;set;}
}
vs
public class myint
{
public int value;
}
The above 2 codes look the same to me. If I want to use the myint class, I just write the code below and it can run on either class.
myint A;
A.value=10;
So what is the get/set use for?
You're asking what the difference is between using a public instance variable vs. getter/setter properties I assume.
Properties allow you to further encapsulate logic around getting or setting a variable, for example adding simple validation logic. You could throw an exception if someone sets your value to less than zero for example. You could also add further logic in the getter/setter to for example synchronize a specific field.
A few other differences:
Properties can be used for data binding easily in most .NET UI frameworks.
Reflection works differently.
Differing access levels for get/set vs. for example your instance variable you can choose between readonly, private, protected, static, etc. as a whole.
There is more overhead accessing a property. This is usually unimportant in most use cases other than games and highly performance sensitive situations.
http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx
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.
Here are few things off the top of my head that differentiate a public {get;set;} vs a public member variable:
Properties are needed for data binding.
get and set can have different accessors (e.g. public int Value {get; protected set;}
get;set; can be part of a interface e.g. interface IHasValueGetter { public int Value {get;}}
What is the difference between a Field and a Property in C#?
here is when do we use get set
According to the Property Usage Guidelines on MSDN:
Use a property when the member is a logical data member. In the following member declarations, Name is a property because it is a
logical member of the class.
Use a method when:
The operation is a conversion, such as Object.ToString.
The operation is expensive enough that you want to communicate to the user that they should consider caching the result.
Obtaining a property value using the get accessor would have an observable side effect.
Calling the member twice in succession produces different results.
The order of execution is important. Note that a type's properties should be able to be set and retrieved in any order.
The member is static but returns a value that can be changed.
The member returns an array. Properties that return arrays can be very misleading. Usually it is necessary to return a copy of the
internal array so that the user cannot change internal state. This,
coupled with the fact that a user can easily assume it is an indexed
property, leads to inefficient code. In the following code example,
each call to the Methods property creates a copy of the array. As a
result, 2n+1 copies of the array will be created in the following
loop.
you can remove get and set it will not affect the code and working due to the reason that you have defined a variable of type int with the Access type of public so that properties are mostly used to access the private members of class which is in your case do not exist so go on and remove it how ever if in top most class you define a variable with Private modifier the to access it get and set are necessary properties!
// This is an example of property...
public class myint
{
public int value{get;set;}
}
// This is an example of field...
public class myint
{
public int value;
}
The difference:
Databinding techniques only works on properties, and not on fields
Fields may be used as input to out/ref arguments. Properties may not.
Properties may throw exceptions - fields will never do that
Example:
class Person
{
private string _name;
public string FirstName
{
get
{
return _name ?? string.Empty;
}
set
{
if (value == null)
throw new System.ArgumentNullException("value");
_name = value;
}
}
}
Properties support different accessibility for getters/setters - fields do not (but fields can be made readonly)
I've been agaonizing about this problem for some days:
I have a class Info
public class Info
{
private int _no;
public int No
{
get
{
return _no;
}
set
{
_no = value;
}
}
}
That class can be used anywhere in any classes (inherited or as property). The property can be considered as security relevant or not. That information is known at design time and needs to be stored for that particular property.
So for some classes which uses that class as property I want the member "No" to be set accordingly.
public class IsRelevant
{
private Info _prop = new Info();
public Info Prop { get { return _prop; } set { _prop = value; } }
}
public class IsNotRelevant
{
private Info _prop = new Info();
public Info Prop { get { return _prop; } set { _prop = value; } }
}
For a first try I was thinking about introducing an custom attribute like this:
[SecurityRelevant(RelevantLevel = SecurityRelevant.SecurityRelevant_Level1, IsRelevant = true)]
And then once I instanciate the class "IsRelevant", I will go through the properties and its classes and set the custom attribute as desired:
IsRelevant.Prop.No => IsRelevant = true,
eg IsNotRelevant.Prop.No => IsRelevant=false.
But as far as I understood the meta information (attributes) for a class is an instance created once for each type. So if I change the values of the custom attribute I will change it for all instances of that class (because it's bound to that type!?)
Edit: This can't be done as stated here: Change Attribute's parameter at runtime Everytime you access the custom attributes, a new instance with the default values will be created. Changes to that attribute won't be stored there.
A second approach was to store that information in an external class and save all the model paths etc. I don't like that because the information belongs to a specific class.
The third approach was to implement an interface which holds a dictionary which stores that information:
public interface ISecRelevant
{
Dictionary<PropertyInfo, bool> SecInfo { get; set; }
}
and then every class which has a security relevant property would need to implement it.
On every instantiation of that class, the information needs to be added in the dicationary. This is the best solution I came up with yet. The class which holds the information doesn't necessarily needs to be a dictionary because in a second step I want to ask an instance with a potential security relevant property if it really is relevant. So I could just pass that property in a method of that "security relevant information container" and ask if the property is relevant.
So I'm basically asking if someone has a better idea to store that information or to access it, because somehow I still don't like the solution.
So here are some general conclusions about that problem:
The information whether a property is security relevant is not really a runtime information, but available upfront. So ideally I would like to store it in a "static" way
The information is best to be attached to the property, at least to the parent class, because only it should know about that information, not any other class which uses that Info class to avoid coupling
There are many more security relevant properties which are scatterd over a lot more classes. These are also used in a more deeper and complex object hierarchy, but I thought it basically comes down to the problem I described here.
Edit: Since I did not come up with a better idea, I implemented the third solution, but with a string for the property name. But then I stumbled into another problem when using Lists. What happens if you have a List as property with a type that has a sec-relevant property? The List would have to know where it is sitting to enable adding the information to every instance which is inserted in the List...
While searching I found another post, basicallay asks for the same thing: C# - add some meta data associated to a particular field when I am assigning a value to the field of a class?
He suggests to implement a base class which hold that kind of information. This will work for "normal" properties. But not for the list-case.
Further explanation and example:
I thought the example with "security relevant" was helping you guys to understand the problem, but maybe it just confused you. Simply said: I need to attach meta information a any property of a class (and also to the items which are maybe contained in a list). Where I need to put this information is known at design-time but is dependent on the instanciation of the classes. So it DOES matter who is instanciating the class. This is also the reason why I cant use static information.
Here is an example:
Class A {
public int MetaProperty; // (this it the propert where i might want to add meta info)
}
Class B {
public A ThePropertyWithMetadata;
}
Class C{
public A TheProperty;
}
Whenever I create an instance of class B, I need to attach meta information to
InstanceOfB.ThePropertyWithMetadata.MetaProperty
On the other hand whenever I create an instance of class C, I DO NOT want to to attach any meta information to that property. I want to show that meta info in the user interface and give the user more information about that property.
So I do know when to assign the meta information, but cant put it in the classes at design time. Hope this clarifies it now :-)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between a field and a property in C#
I'm a beginning programmer and I've read all about class properties. Books state that properties allow you to indirectly access member variables. Ok, so what makes it any different than just making the field public and accessing it directly?
Here's a quote from Learning C# 3.0 by Jesse Liberty:
For example, you might want external
classes to be able to read a value, but not change it; or you might want to write
some code so that the internal field can accept only values in a certain range. If you
grant external classes free access to your member fields, you can’t control any of that.
I don't understand what he is saying here. Can someone further explain this or give an example of why I would want to use a property over making the field public. As I understand it now they would both accomplish the same exact thing...so I'm obviously missing something here.
The other answers provided so far provide details of the advantages of accessor/mutator logic, but all seem to miss out on the ideological point about object encapsulation.
You see, class member fields are an implementation detail. If you have a class that represents a collection, for example, then you could implement it as a linked list (and expose the root-node via a public field) or you could implement it as a resizable array and expose the index0 member.
The problem with revealing implementation details is that you lose any kind of defined interface between your class and its consumers. By ensuring all operations are done via defined methods (controlled by the class itself) you make it easier to work with and provide for a long-term viewpoint. For example, you are far more easily able to convert your collection implementation from one type (the linked-list) to another (the array) without breaking any contracts with your class' consumers.
Don't worry about any performance impact of trivial accessor/mutator methods: the JIT compiler will inline the property methods. If you'll run some benchmarks you'll see the performance of properties vs fields is identical.
He's saying that properties can provide a getter but not a setter, therefore making them read-only (for example)
Properties are just syntactic sugar for a method e.g.
public int SomeProperty { get; set; }
is just sugar for
private int _someProperty;
public int SomeProperty_get()
{
return _someProperty;
}
public void SomeProperty_set(int value)
{
_someProperty = value;
}
This means that property setters/getters can apply logic that a mere public field can't
Edit: I'm not exactly sure what field names the CLR gives the backing fields for auto-properties - it's just an example :)
Edit2:
An example of a read only property:
public int SomeProperty { get; }
and finally a public read - private write (for autoproperties)
public int SomeProperty { get; private set; }
Really useful when you can't be bothered to type a backing field in :)
Just remember, if there is a possibility that you wish to apply logic to a member, then a property is the way to go. This is the way a lot of frameworks work (e.g. tracking 'dirty' objects by using a property to tell some sort of object manager that something has changed, this would not be possible using a public field)
Properties can have side-effects, They provide syntactic sugar around 'getter' and 'setter' methods.
public class MyClass {
int sizeValue = 0;
public int Size {
get {
return sizeValue;
}
set {
if ( value < 10 ) throw new Exception("Size too small");
sizeValue = value;
}
}
}
Properties can also have different levels of protection for get and set, you cannot do that with fields.
public class MyOtherClass {
// only this object can set this.
public int Level {
get; private set;
}
// only things in the same assembly can set this.
public string Name {
get; internal set;
}
}
There are a number of important differences between "properties" and "member access".
The most significant is that you can, through a property, make a member read-only (you can access the state, but you cannot change it). Just like "getter()" and "setter()" methods in Java.
You can also return a computed value from a property (generate a value "on-the-fly", as though it were a variable).
Properties can be configured so that:
they are read-only, Public MyProp {get;}
they are write-only Public MyProp {set;}
they are readable by external objects, but can only be set by the class's internals
Public MyProp {get; private set;}
As others have posted, you can also put logic into your getters and setters. For example before allowing the property to bet set to a new value, you can check that the value is acceptable.
You cannot do any of that with a public field.
Basically, a public field is the dumbest sort of property that you can have. Given that .Net now allows autobacking fields for your properties. There is no good reason to use public fields any longer.
If you have Public Int MyAge
I can set it to -200 or 20,000 and there is nothing you can do about it.
If you use a property you can check that age is between 0 and 150, for example.
Edit: as per IanNorton's example (man, that was fast)
I'd like to know if this:
private List<FixedTickProvider> minorTickProviders;
public List<FixedTickProvider> MinorTickProviders { get { return minorTickProviders; } }
is equivalent to this:
public List<FixedTickProvider> MinorTickProviders { get; private set; }
the thing is: I've inherited the first piece of code, while I myself am more used to the second option. As Is was about to re-write the portion of code, I wondered if those two are exactly equivalent though.
please note that I am NOT talking about readonly Lists here. I am fully aware of the "readonly list" topic as discussed here and my question is slightly different.
NB: I am almost sure I once read an article stating that the compiler would produce the exact same code from those two extracts but I can't find it any more, nor can I find a precise answer on this subject. So please enlighten me.
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, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
So, both will have same output......
Yes, both pieces of code will achieve the same result
//here you are declaring a private field of class
private List<FixedTickProvider> minorTickProviders;
//and only exposing get to rest of the code
public List<FixedTickProvider> MinorTickProviders { get { return minorTickProviders; } }
//here you are declaring a public property which can only be set by the class which is declaring it
public List<FixedTickProvider> MinorTickProviders { get; private set; }
As far as IL is considered there will be slight difference
In case of separate field and property following IL will be generated
In case of single property without backing field
They achieve equivalent results, except that any code which assigns the value will be different between the two (the first will assign to the field, the second to the property), and so, of course, the generated IL will be slightly different also.
(Of course, in the property assignment case, it's quite likely that the method call and the eventual field assignment are simple enough to inline)
Seen a few examples of code where this happens:
public class Foo
{
string[] m_workID;
public string[] WorkID
{
get
{
return m_workID;
}
private set
{
m_workID = value;
}
}
}
What's the point of this?
Since the use m_workID unnescessary.
In general, the point is to separate implementation (the field) from API (the property).
Later on you can, should you wish, put logic, logging etc in the property without breaking either source or binary compatibility - but more importantly you're saying what your type is willing to do, rather than how it's going to do it.
I have an article giving more benefits of using properties instead of public fields.
In C# 3 you can make all of this a lot simpler with automatically implemented properties:
public class Foo
{
public string[] WorkID { get; private set; }
}
At that point you still have a public getter and a private setter, but the backing field (and property implementation) is generated for you behind the scenes. At any point you can change this to a "normal" fully-implemented property with a backing field, and you'll still have binary and source compatibility. (Compatibility of serialized objects is a different matter, mind you.)
Additionally, in this case you can't mirror the behaviour you want (the ability to read the value publicly but write it privately) with a field - you could have a readonly field, but then you could only write to it within the constructor. Personally I wish there were a similar shorthand for this:
public class Foo
{
private readonly int id;
public int Id { get { return id; } }
...
}
as I like immutable types, but that's a different matter.
In another different matter, it's generally not a good idea to expose arrays like this anyway - even though callers can't change which array WorkID refers to, they can change the contents of the array, which is probably not what you want.
In the example you've given you could get away without the property setter, just setting the field directly within the same class, but it would mean that if you ever wanted to add logging etc you'd have to find all those writes.
A property by itself doesn't provide anywhere to put the data - you need the field (m_workID) for storage, but it entirely correct to hide that behind a property for many, many reasons. In C# 3.0 you can reduce this to:
public string[] WorkID {get; private set;}
Which will do much of the same. Note that exposing an array itself may be problematic, as there is no mechanism for protecting data in an array - at least with an IList<string> you could (if needed) add extra code to sanity check things, or could make it immutable. I'm not saying this needs fixing, but it is something to watch.
In addition to the Object Oriented philosophy of data encapsulation, it helps when you need to do something every time your property is read/write.
You can have to perform a log, a validation, or any another method call later in your development.
If your property is public, you'll have to look around all your code to find and modify your code. And what if your code is used as a library by someone else ?
If your property is private with appropriate get/set methods, then you change the get/set and that's all.
You can use C# 3.0 auto properties feature to save time typing:
public class Foo
{
public string[] WorkID
{
get; private set;
}
}
In addition properties gives you lot of advantages in comparison to fields:
properties can be virtual
properties hide implementation details (not all properties are just trivial variable accessors)
properties can contain validation and logging code and raise change events
interfaces cannot contains fields but properties
A lot of times you only want to provide read access to a field. By using a property you can provide this access. As you mention you may want to perform operations before the field is accessed (lazy loading, e.g.). You have a lot of code in there that just isn't necessary anymore unless you're still working in .Net 2.0-.