Best way of protect a backing field from mistaken use in C# - c#

I have a class (Foo) which lazy loads a property named (Bar). What is your preferred way to protect against mistaken use (due to intellisense or inexperienced staff) of the uninitialized backing field?
I can think of 3 options:
class Foo {
// option 1 - Easy to use this.bar by mistake.
string bar;
string Bar {
get {
// logic to lazy load bar
return bar;
}
}
// option 2 - Harder to use this._bar by mistake. It is more obscure.
string _bar2;
string Bar2 {
get {
// logic to lazy load bar2
return _bar2;
}
}
//option 3 - Very hard to use the backing field by mistake.
class BackingFields {
public string bar;
}
BackingFields fields = new BackingFields();
string Bar3 {
get {
// logic to lazy load bar
return fields.bar;
}
}
}
Keep in mind, the only place I want people mucking around with the backing field bar is in setter and getter of the property. Everywhere else in the class they should always use this.Bar
Update
I am currently using the following Lazy implementation (not for all properties with backing fields, but for select ones that require lazy loading, synchronization and notification). It could be extended to support futures as well (force evaluation in a separate thread in a later time)
Note My implementation locks on read, cause it supports an external set.
Also, I would like to mention that I think this is a language limitation which can be overcome in Ruby for example.
You can implement lazy in this way.
x = lazy do
puts "<<< Evaluating lazy value >>>"
"lazy value"
end
puts x
# <<< Evaluating lazy value >>>
# lazy value

How about use of ObsoleteAttribute and #pragma - hard to miss it then!
void Test1()
{
_prop = ""; // warning given
}
public string Prop
{
#pragma warning disable 0618
get { return _prop; }
set { _prop = value; }
#pragma warning restore 0618
}
[Obsolete("This is the backing field for lazy data; do not use!!")]
private string _prop;
void Test2()
{
_prop = ""; // warning given
}

Option 5
Lazy<T>
works quite nicely in several situations, though option 1 should really be just fine for most projects so long as the developers aren't idiots.
Adding [EditorBrowsable(EditorBrowsableState.Never)] to the field won't help if it is private since this logic only kicks in for intellisense generated from metadata rather than the current code (current project and anything done via project references rather than dlls).
Note: Lazy<T> is not thread safe (this is good, there's no point locking if you don't need to) if you require thread safety either use one of the thread safe ones from Joe Duffy or the Parallel Exetensions CTP

I usually go for option 2, as it is easier to spot mistakes later on, although option 1 would pass a code review. Option 3 seems convoluted and whilst it may work, it's not going to be nice code to revisit 6 months down the line whilst trying to refactor/fix a bug/etc.

Option 1, coupled with some education.
Rationale: software is meant to be read more often than written, so optimize for the common case and keep it readable.

Code reviews will catch misuse so just go with the most readable. I dislike attempts to work around bad programmers in code, because 1) they don't work, 2) they make it harder for smart programmers to get their work done, and 3) it addresses the symptom rather than the cause of the problem.

I usually just go for option 1. Because it is a private field I don't think it really an issue, and using something like the wrapper class as in your option 3 only makes code difficult to read and understand.

I would just put a large comment block on the top of the class that would look like that:
/************************************************************
* Note: When updating this class, please take care of using *
* only the accessors to access member data because of *
* ... (state the reasons / your name, so they can ask *
* questions) *
*************************************************************/
Usually, just a note like that should be enough, but if this is the same for all the classes in the project, you might prefer to put it in a simple document that you give to programmers working on the project, and everytime you see code that isn't conform, you point them to the document.

Automatic properties:
public int PropertyName { get; set; }
will prevent access to the backing field. But if you want to put code in there (e.g. for lazy loading on first access) this clearly won't help.
The simplest route is likely to be a helper type which does the lazy loading, and have an private field of that type, with the public property calling to the correct property/method of the helper type.
E.g.
public class Foo {
private class LazyLoader {
private someType theValue;
public someType Value {
get {
// Do lazy load
return theValue;
}
}
}
private LazyLoader theValue;
public someType {
get { return theValue.Value; }
}
}
This has the advantage that the backing field is harder to use than the property.
(Another case of an extra level of indirection to solve problems.)

// option 4
class Foo
{
public int PublicProperty { get; set; }
public int PrivateSetter { get; private set; }
}
C# 3.0 feature, the compiler will generate anonymous private backing fields which can't be accessed by mistake, well unless you use reflection...
EDIT: Lazy instantiation
You can have laziness like this:
// I changed this with respect to ShuggyCoUk's answer (Kudos!)
class LazyEval<T>
{
T value;
Func<T> eval;
public LazyEval(Func<T> eval) { this.eval = eval; }
public T Eval()
{
if (eval == null)
return value;
value = eval();
eval = null;
return value;
}
public static implicit operator T(LazyEval<T> lazy) // maybe explicit
{
return lazy.Eval();
}
public static implicit operator LazyEval<T>(Func<T> eval)
{
return new LazyEval(eval);
}
}
Those implicit conversion make the syntax tidy...
// option 5
class Foo
{
public LazyEval<MyClass> LazyProperty { get; private set; }
public Foo()
{
LazyProperty = () => new MyClass();
}
}
And closures can be used to carry scope:
// option 5
class Foo
{
public int PublicProperty { get; private set; }
public LazyEval<int> LazyProperty { get; private set; }
public Foo()
{
LazyProperty = () => this.PublicProperty;
}
public void DoStuff()
{
var lazy = LazyProperty; // type is inferred as LazyEval`1, no eval
PublicProperty = 7;
int i = lazy; // same as lazy.Eval()
Console.WriteLine(i); // WriteLine(7)
}
}

Currently, I'm in a similar situation.
I have a field which should only be used by its property accessor.
I can't use automatic properties, since I need to perform additional logic when the property is set. (The property is not lazy loaded as well).
Wouldn't it be great if a next version of C# would allow something like this:
public class MyClass
{
public int MyProperty
{
int _backingField;
get
{
return _backingField;
}
set
{
if( _backingField != value )
{
_backingField = value;
// Additional logic
...
}
}
}
}
With such construct, the _backingField variable's scope is limited to the property.
I would like to see a similar language construction in a next version of C# :)
But, I'm afraid this feature will never be implemented:
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=381625

This might be overly simple, but why not abstract all the lazy to a base class
public class LazyFoo{
private string bar;
public string Bar{
get{
// lazy load and return
}
set {
// set
}
}
}
public class Foo : LazyFoo{
// only access the public properties here
}
I could see the argument that it is unnecessary abstraction, but it is the simplest way I can see to eliminate all access to backing fields.

This seems like trying to design-out mistakes that might not happen in the first place, and basically it's worrying about the wrong thing.
I would go with option 1 + comments:
///<summary>use Bar property instead</summary>
string bar;
///<summary>Lazy gets the value of Bar and stores it in bar</summary>
string Bar {
get {
// logic to lazy load bar
return bar;
}
}
If you do get a developer who keeps using the backing variable then I'd worry about their technical competence.
By all means design to make your code easier to maintain, but try to keep it simple - any rule that you make for yourself here is going to be more hassle than it's worth.
And if you're still really worried about it create an FxCop (or whatever you're using) rule to check for this sort of thing.

Option 6:
Makes it very dumb indeed if you use it.
string doNotUseThisBackingField_bar6;
string Bar6 {
get {
// logic to lazy load
return doNotUseThisBackingField_bar6;
}
}

Option 4 (a new solution):
See if the question is really about how to prevent people from using an uninitialized variable then init it with an KNOWN INVALID value.
I would say something like:
string str = "SOMETHING_WRONG_HERE";
Who ever is using 'str' will have some sort of warning.
Otherwise Option 3 if preventing users from using 'str' is more important than readability etc.

Related

C# Public variables vs Properties, what's the difference? [duplicate]

In C#, what makes a field different from a property, and when should a field be used instead of a property?
Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.
public class MyClass
{
// this is a field. It is private to your class and stores the actual data.
private string _myField;
// this is a property. When accessed it uses the underlying field,
// but only exposes the contract, which will not be affected by the underlying field
public string MyProperty
{
get
{
return _myField;
}
set
{
_myField = value;
}
}
// This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
// used to generate a private field for you
public int AnotherProperty { get; set; }
}
#Kent points out that Properties are not required to encapsulate fields, they could do a calculation on other fields, or serve other purposes.
#GSS points out that you can also do other logic, such as validation, when a property is accessed, another useful feature.
Object orientated programming principles say that, the internal workings of a class should be hidden from the outside world. If you expose a field you're in essence exposing the internal implementation of the class. Therefore we wrap fields with Properties (or methods in Java's case) to give us the ability to change the implementation without breaking code depending on us. Seeing as we can put logic in the Property also allows us to perform validation logic etc if we need it.
C# 3 has the possibly confusing notion of autoproperties. This allows us to simply define the Property and the C#3 compiler will generate the private field for us.
public class Person
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public int Age{get;set;} //AutoProperty generates private field for us
}
An important difference is that interfaces can have properties but not fields. This, to me, underlines that properties should be used to define a class's public interface while fields are meant to be used in the private, internal workings of a class. As a rule I rarely create public fields and similarly I rarely create non-public properties.
I'll give you a couple examples of using properties that might get the gears turning:
Lazy Initialization: If you have a property of an object that's expensive to load, but isn't accessed all that much in normal runs of the code, you can delay its loading via the property. That way, it's just sitting there, but the first time another module tries to call that property, it checks if the underlying field is null - if it is, it goes ahead and loads it, unknown to the calling module. This can greatly speed up object initialization.
Dirty Tracking: Which I actually learned about from my own question here on StackOverflow. When I have a lot of objects which values might have changed during a run, I can use the property to track if they need to be saved back to the database or not. If not a single property of an object has changed, the IsDirty flag won't get tripped, and therefore the saving functionality will skip over it when deciding what needs to get back to the database.
Using Properties, you can raise an event, when the value of the property is changed (aka. PropertyChangedEvent) or before the value is changed to support cancellation.
This is not possible with (direct access to) fields.
public class Person {
private string _name;
public event EventHandler NameChanging;
public event EventHandler NameChanged;
public string Name{
get
{
return _name;
}
set
{
OnNameChanging();
_name = value;
OnNameChanged();
}
}
private void OnNameChanging(){
NameChanging?.Invoke(this,EventArgs.Empty);
}
private void OnNameChanged(){
NameChanged?.Invoke(this,EventArgs.Empty);
}
}
Since many of them have explained with technical pros and cons of Properties and Field, it's time to get into real time examples.
1. Properties allows you to set the read-only access level
Consider the case of dataTable.Rows.Count and dataTable.Columns[i].Caption. They come from the class DataTable and both are public to us. The difference in the access-level to them is that we cannot set value to dataTable.Rows.Count but we can read and write to dataTable.Columns[i].Caption. Is that possible through Field? No!!! This can be done with Properties only.
public class DataTable
{
public class Rows
{
private string _count;
// This Count will be accessable to us but have used only "get" ie, readonly
public int Count
{
get
{
return _count;
}
}
}
public class Columns
{
private string _caption;
// Used both "get" and "set" ie, readable and writable
public string Caption
{
get
{
return _caption;
}
set
{
_caption = value;
}
}
}
}
2. Properties in PropertyGrid
You might have worked with Button in Visual Studio. Its properties are shown in the PropertyGrid like Text,Name etc. When we drag and drop a button, and when we click the properties, it will automatically find the class Button and filters Properties and show that in PropertyGrid (where PropertyGrid won't show Field even though they are public).
public class Button
{
private string _text;
private string _name;
private string _someProperty;
public string Text
{
get
{
return _text;
}
set
{
_text = value;
}
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
[Browsable(false)]
public string SomeProperty
{
get
{
return _someProperty;
}
set
{
_someProperty= value;
}
}
In PropertyGrid, the properties Name and Text will be shown, but not SomeProperty. Why??? Because Properties can accept Attributes. It does not show in case where [Browsable(false)] is false.
3. Can execute statements inside Properties
public class Rows
{
private string _count;
public int Count
{
get
{
return CalculateNoOfRows();
}
}
public int CalculateNoOfRows()
{
// Calculation here and finally set the value to _count
return _count;
}
}
4. Only Properties can be used in Binding Source
Binding Source helps us to decrease the number of lines of code. Fields are not accepted by BindingSource. We should use Properties for that.
5. Debugging mode
Consider we are using Field to hold a value. At some point we need to debug and check where the value is getting null for that field. It will be difficult to do where the number of lines of code are more than 1000. In such situations we can use Property and can set debug mode inside Property.
public string Name
{
// Can set debug mode inside get or set
get
{
return _name;
}
set
{
_name = value;
}
}
DIFFERENCES - USES (when and why)
A field is a variable that is declared directly in a class or struct. A class or struct may have instance fields or static fields or both. Generally, you should use fields only for variables that have private or protected accessibility. Data that your class exposes to client code should be provided through methods, properties and indexers. By using these constructs for indirect access to internal fields, you can guard against invalid input values.
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.
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.
Though fields and properties look to be similar to each other, they are 2 completely different language elements.
Fields are the only mechanism how to store data on class level. Fields are conceptually variables at class scope. If you want to store some data to instances of your classes (objects) you need to use fields. There is no other choice. Properties can't store any data even though, it may look they are able to do so. See bellow.
Properties on the other hand never store data. They are just the pairs of methods (get and set) that can be syntactically called in a similar way as fields and in most cases they access (for read or write) fields, which is the source of some confusion. But because property methods are (with some limitations like fixed prototype) regular C# methods they can do whatever regular methods can do. It means they can have 1000 lines of code, they can throw exceptions, call another methods, can be even virtual, abstract or overridden. What makes properties special, is the fact that C# compiler stores some extra metadata into assemblies that can be used to search for specific properties - widely used feature.
Get and set property methods has the following prototypes.
PROPERTY_TYPE get();
void set(PROPERTY_TYPE value);
So it means that properties can be 'emulated' by defining a field and 2 corresponding methods.
class PropertyEmulation
{
private string MSomeValue;
public string GetSomeValue()
{
return(MSomeValue);
}
public void SetSomeValue(string value)
{
MSomeValue=value;
}
}
Such property emulation is typical for programming languages that don't support properties - like standard C++. In C# there you should always prefer properties as the way how to access to your fields.
Because only the fields can store a data, it means that more fields class contains, more memory objects of such class will consume. On the other hand, adding new properties into a class doesn't make objects of such class bigger. Here is the example.
class OneHundredFields
{
public int Field1;
public int Field2;
...
public int Field100;
}
OneHundredFields Instance=new OneHundredFields() // Variable 'Instance' consumes 100*sizeof(int) bytes of memory.
class OneHundredProperties
{
public int Property1
{
get
{
return(1000);
}
set
{
// Empty.
}
}
public int Property2
{
get
{
return(1000);
}
set
{
// Empty.
}
}
...
public int Property100
{
get
{
return(1000);
}
set
{
// Empty.
}
}
}
OneHundredProperties Instance=new OneHundredProperties() // !!!!! Variable 'Instance' consumes 0 bytes of memory. (In fact a some bytes are consumed becasue every object contais some auxiliarity data, but size doesn't depend on number of properties).
Though property methods can do anything, in most cases they serve as a way how to access objects' fields. If you want to make a field accessible to other classes you can do by 2 ways.
Making fields as public - not advisable.
Using properties.
Here is a class using public fields.
class Name
{
public string FullName;
public int YearOfBirth;
public int Age;
}
Name name=new Name();
name.FullName="Tim Anderson";
name.YearOfBirth=1979;
name.Age=40;
While the code is perfectly valid, from design point of view, it has several drawbacks. Because fields can be both read and written, you can't prevent user from writing to fields. You can apply readonly keyword, but in this way, you have to initialize readonly fields only in constructor. What's more, nothing prevents you to store invalid values into your fields.
name.FullName=null;
name.YearOfBirth=2200;
name.Age=-140;
The code is valid, all assignments will be executed though they are illogical. Age has a negative value, YearOfBirth is far in future and doesn't correspond to Age and FullName is null. With fields you can't prevent users of class Name to make such mistakes.
Here is a code with properties that fixes these issues.
class Name
{
private string MFullName="";
private int MYearOfBirth;
public string FullName
{
get
{
return(MFullName);
}
set
{
if (value==null)
{
throw(new InvalidOperationException("Error !"));
}
MFullName=value;
}
}
public int YearOfBirth
{
get
{
return(MYearOfBirth);
}
set
{
if (MYearOfBirth<1900 || MYearOfBirth>DateTime.Now.Year)
{
throw(new InvalidOperationException("Error !"));
}
MYearOfBirth=value;
}
}
public int Age
{
get
{
return(DateTime.Now.Year-MYearOfBirth);
}
}
public string FullNameInUppercase
{
get
{
return(MFullName.ToUpper());
}
}
}
The updated version of class has the following advantages.
FullName and YearOfBirth are checked for invalid values.
Age is not writtable. It's callculated from YearOfBirth and current year.
A new property FullNameInUppercase converts FullName to UPPER CASE. This is a little contrived example of property usage, where properties are commonly used to present field values in the format that is more appropriate for user - for instance using current locale on specific numeric of DateTime format.
Beside this, properties can be defined as virtual or overridden - simply because they are regular .NET methods. The same rules applies for such property methods as for regular methods.
C# also supports indexers which are the properties that have an index parameter in property methods. Here is the example.
class MyList
{
private string[] MBuffer;
public MyList()
{
MBuffer=new string[100];
}
public string this[int Index]
{
get
{
return(MBuffer[Index]);
}
set
{
MBuffer[Index]=value;
}
}
}
MyList List=new MyList();
List[10]="ABC";
Console.WriteLine(List[10]);
Since C# 3.0 allows you to define automatic properties. Here is the example.
class AutoProps
{
public int Value1
{
get;
set;
}
public int Value2
{
get;
set;
}
}
Even though class AutoProps contains only properties (or it looks like), it can store 2 values and size of objects of this class is equal to sizeof(Value1)+sizeof(Value2)=4+4=8 bytes.
The reason for this is simple. When you define an automatic property, C# compiler generates automatic code that contains hidden field and a property with property methods accessing this hidden field. Here is the code compiler produces.
Here is a code generated by the ILSpy from compiled assembly. Class contains generated hidden fields and properties.
internal class AutoProps
{
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int <Value1>k__BackingField;
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int <Value2>k__BackingField;
public int Value1
{
[CompilerGenerated]
get
{
return <Value1>k__BackingField;
}
[CompilerGenerated]
set
{
<Value1>k__BackingField = value;
}
}
public int Value2
{
[CompilerGenerated]
get
{
return <Value2>k__BackingField;
}
[CompilerGenerated]
set
{
<Value2>k__BackingField = value;
}
}
}
So, as you can see, the compiler still uses the fields to store the values - since fields are the only way how to store values into objects.
So as you can see, though properties and fields have similar usage syntax they are very different concepts. Even if you use automatic properties or events - hidden fields are generated by compiler where the real data are stored.
If you need to make a field value accessible to the outside world (users of your class) don't use public or protected fields. Fields always should be marked as private. Properties allow you to make value checks, formatting, conversions etc. and generally make your code safer, more readable and more extensible for future modifications.
Properties have the primary advantage of allowing you to change the way data on an object is accessed without breaking it's public interface. For example, if you need to add extra validation, or to change a stored field into a calculated you can do so easily if you initially exposed the field as a property. If you just exposed a field directly, then you would have to change the public interface of your class to add the new functionality. That change would break existing clients, requiring them to be recompiled before they could use the new version of your code.
If you write a class library designed for wide consumption (like the .NET Framework, which is used by millions of people), that can be a problem. However, if you are writing a class used internally inside a small code base (say <= 50 K lines), it's really not a big deal, because no one would be adversely affected by your changes. In that case it really just comes down to personal preference.
Properties support asymmetric access, i.e. you can have either a getter and a setter or just one of the two. Similarly properties support individual accessibility for getter/setter. Fields are always symmetric, i.e. you can always both get and set the value. Exception to this is readonly fields which obviously cannot be set after initialization.
Properties may run for a very long time, have side effects, and may even throw exceptions. Fields are fast, with no side effects, and will never throw exceptions. Due to side effects a property may return a different value for each call (as may be the case for DateTime.Now, i.e. DateTime.Now is not always equal to DateTime.Now). Fields always return the same value.
Fields may be used for out / ref parameters, properties may not.
Properties support additional logic – this could be used to implement lazy loading among other things.
Properties support a level of abstraction by encapsulating whatever it means to get/set the value.
Use properties in most / all cases, but try to avoid side effects.
In the background a property is compiled into methods. So a Name property is compiled into get_Name() and set_Name(string value). You can see this if you study the compiled code.
So there is a (very) small performance overhead when using them. Normally you will always use a Property if you expose a field to the outside, and you will often use it internally if you need to do validation of the value.
When you want your private variable(field) to be accessible to object of your class from other classes you need to create properties for those variables.
for example if I have variables named as "id" and "name" which is private
but there might be situation where this variable needed for read/write operation outside of the class. At that situation , property can help me to get that variable to read/write depending upon the get/set defined for the property. A property can be a readonly / writeonly / readwrite both.
here is the demo
class Employee
{
// Private Fields for Employee
private int id;
private string name;
//Property for id variable/field
public int EmployeeId
{
get
{
return id;
}
set
{
id = value;
}
}
//Property for name variable/field
public string EmployeeName
{
get
{
return name;
}
set
{
name = value;
}
}
}
class MyMain
{
public static void Main(string [] args)
{
Employee aEmployee = new Employee();
aEmployee.EmployeeId = 101;
aEmployee.EmployeeName = "Sundaran S";
}
}
The second question here, "when should a field be used instead of a property?", is only briefly touched on in this other answer and kinda this one too, but not really much detail.
In general, all the other answers are spot-on about good design: prefer exposing properties over exposing fields. While you probably won't regularly find yourself saying "wow, imagine how much worse things would be if I had made this a field instead of a property", it's so much more rare to think of a situation where you would say "wow, thank God I used a field here instead of a property."
But there's one advantage that fields have over properties, and that's their ability to be used as "ref" / "out" parameters. Suppose you have a method with the following signature:
public void TransformPoint(ref double x, ref double y);
and suppose that you want to use that method to transform an array created like this:
System.Windows.Point[] points = new Point[1000000];
Initialize(points);
Here's I think the fastest way to do it, since X and Y are properties:
for (int i = 0; i < points.Length; i++)
{
double x = points[i].X;
double y = points[i].Y;
TransformPoint(ref x, ref y);
points[i].X = x;
points[i].Y = y;
}
And that's going to be pretty good! Unless you have measurements that prove otherwise, there's no reason to throw a stink. But I believe it's not technically guaranteed to be as fast as this:
internal struct MyPoint
{
internal double X;
internal double Y;
}
// ...
MyPoint[] points = new MyPoint[1000000];
Initialize(points);
// ...
for (int i = 0; i < points.Length; i++)
{
TransformPoint(ref points[i].X, ref points[i].Y);
}
Doing some measurements myself, the version with fields takes about 61% of the time as the version with properties (.NET 4.6, Windows 7, x64, release mode, no debugger attached). The more expensive the TransformPoint method gets, the less pronounced that the difference becomes. To repeat this yourself, run with the first line commented-out and with it not commented-out.
Even if there were no performance benefits for the above, there are other places where being able to use ref and out parameters might be beneficial, such as when calling the Interlocked or Volatile family of methods. Note: In case this is new to you, Volatile is basically a way to get at the same behavior provided by the volatile keyword. As such, like volatile, it doesn't magically solve all thread-safety woes like its name suggests that it might.
I definitely don't want to seem like I'm advocating that you go "oh, I should start exposing fields instead of properties." The point is that if you need to regularly use these members in calls that take "ref" or "out" parameters, especially on something that might be a simple value type that's unlikely to ever need any of the value-added elements of properties, an argument can be made.
Also, properties allow you to use logic when setting values.
So you can say you only want to set a value to an integer field, if the value is greater than x, otherwise throw an exception.
Really useful feature.
(This should really be a comment, but I can't post a comment, so please excuse if it is not appropriate as a post).
I once worked at a place where the recommended practice was to use public fields instead of properties when the equivalent property def would just have been accessing a field, as in :
get { return _afield; }
set { _afield = value; }
Their reasoning was that the public field could be converted into a property later in future if required. It seemed a little strange to me at the time. Judging by these posts, it looks like not many here would agree either. What might you have said to try to change things ?
Edit : I should add that all of the code base at this place was compiled at the same time, so they might have thought that changing the public interface of classes (by changing a public field to a property) was not a problem.
Technically, i don't think that there is a difference, because properties are just wrappers around fields created by the user or automatically created by the compiler.The purpose of properties is to enforce encapsuation and to offer a lightweight method-like feature.
It's just a bad practice to declare fields as public, but it does not have any issues.
Fields are ordinary member variables or member instances of a class. Properties are an abstraction to get and set their values. Properties are also called accessors because they offer a way to change and retrieve a field if you expose a field in the class as private. Generally, you should declare your member variables private, then declare or define properties for them.
class SomeClass
{
int numbera; //Field
//Property
public static int numbera { get; set;}
}
If you are going to use thread primitives you are forced to use fields. Properties can break your threaded code. Apart from that, what cory said is correct.
My design of a field is that a field needs to be modified only by its parent, hence the class. Result the variable becomes private, then to be able to give the right to read the classes / methods outside I go through the system of property with only the Get. The field is then retrieved by the property and read-only! If you want to modify it you have to go through methods (for example the constructor) and I find that thanks to this way of making you secure, we have better control over our code because we "flange". One could very well always put everything in public so every possible case, the notion of variables / methods / classes etc ... in my opinion is just an aid to the development, maintenance of the code. For example, if a person resumes a code with public fields, he can do anything and therefore things "illogical" in relation to the objective, the logic of why the code was written. It's my point of view.
When i use a classic model private field / public readonly properties,for 10 privates fields i should write 10 publics properties! The code can be really big faster. I discover the private setter and now i only use public properties with a private setter.
The setter create in background a private field.
That why my old classic programming style was:
public class MyClass
{
private int _id;
public int ID { get { return _id; } }
public MyClass(int id)
{
_id = id;
}
}
My new programming style:
public class MyClass
{
public int ID { get; private set; }
public MyClass(int id)
{
ID = id;
}
}
Basic and general difference is:
Fields
ALWAYS give both get and set access
CAN NOT cause side effects (throwing exceptions, calling methods, changing fields except the one being got/set, etc)
Properties
NOT ALWAYS give both get and set access
CAN cause side effects
Properties encapsulate fields, thus enabling you to perform additional processing on the value to be set or retrieved. It is typically overkill to use properties if you will not be doing any pre- or postprocessing on the field value.
IMO, Properties are just the "SetXXX()" "GetXXX()" functions/methods/interfaces pairs we used before, but they are more concise and elegant.
Traditionally private fields are set via getter and setter methods. For the sake of less code you can use properties to set fields instead.
when you have a class which is "Car". The properties are color,shape..
Where as fields are variables defined within the scope of a class.
From Wikipedia -- Object-oriented programming:
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which are data structures that contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. (emphasis added)
Properties are actually part of an object's behavior, but are designed to give consumers of the object the illusion/abstraction of working with the object's data.
Properties are special kind of class member, In properties we use a predefined Set or Get method.They use accessors through which we can read, written or change the values of the private fields.
For example, let us take a class named Employee, with private fields for name, age and Employee_Id. We cannot access these fields from outside the class , but we can access these private fields through properties.
Why do we use properties?
Making the class field public & exposing it is risky, as you will not have control what gets assigned & returned.
To understand this clearly with an example lets take a student class who have ID, passmark, name. Now in this example some problem with public field
ID should not be -ve.
Name can not be set to null
Pass mark should be read only.
If student name is missing No Name should be return.
To remove this problem We use Get and set method.
// A simple example
public class student
{
public int ID;
public int passmark;
public string name;
}
public class Program
{
public static void Main(string[] args)
{
student s1 = new student();
s1.ID = -101; // here ID can't be -ve
s1.Name = null ; // here Name can't be null
}
}
Now we take an example of get and set method
public class student
{
private int _ID;
private int _passmark;
private string_name ;
// for id property
public void SetID(int ID)
{
if(ID<=0)
{
throw new exception("student ID should be greater then 0");
}
this._ID = ID;
}
public int getID()
{
return_ID;
}
}
public class programme
{
public static void main()
{
student s1 = new student ();
s1.SetID(101);
}
// Like this we also can use for Name property
public void SetName(string Name)
{
if(string.IsNullOrEmpty(Name))
{
throw new exeception("name can not be null");
}
this._Name = Name;
}
public string GetName()
{
if( string.IsNullOrEmpty(This.Name))
{
return "No Name";
}
else
{
return this._name;
}
}
// Like this we also can use for Passmark property
public int Getpassmark()
{
return this._passmark;
}
}
Additional info:
By default, get and set accessors are as accessible as the property itself.
You can control/restrict accessor accessibility individually (for get and set) by applying more restrictive access modifiers on them.
Example:
public string Name
{
get
{
return name;
}
protected set
{
name = value;
}
}
Here get is still publicly accessed (as the property is public), but set is protected (a more restricted access specifier).
Think about it : You have a room and a door to enter this room. If you want to check how who is coming in and secure your room, then you should use properties otherwise they won't be any door and every one easily come in w/o any regulation
class Room {
public string sectionOne;
public string sectionTwo;
}
Room r = new Room();
r.sectionOne = "enter";
People is getting in to sectionOne pretty easily, there wasn't any checking
class Room
{
private string sectionOne;
private string sectionTwo;
public string SectionOne
{
get
{
return sectionOne;
}
set
{
sectionOne = Check(value);
}
}
}
Room r = new Room();
r.SectionOne = "enter";
Now you checked the person and know about whether he has something evil with him
Fields are the variables in classes. Fields are the data which you can encapsulate through the use of access modifiers.
Properties are similar to Fields in that they define states and the data associated with an object.
Unlike a field a property has a special syntax that controls how a person reads the data and writes the data, these are known as the get and set operators. The set logic can often be used to do validation.
Properties are used to expose field. They use accessors(set, get) through which the values of the private fields can be read, written or manipulated.
Properties do not name the storage locations. Instead, they have accessors that read, write, or compute their values.
Using properties we can set validation on the type of data that is set on a field.
For example we have private integer field age on that we should allow positive values since age cannot be negative.
We can do this in two ways using getter and setters and using property.
Using Getter and Setter
// field
private int _age;
// setter
public void set(int age){
if (age <=0)
throw new Exception();
this._age = age;
}
// getter
public int get (){
return this._age;
}
Now using property we can do the same thing. In the value is a key word
private int _age;
public int Age{
get{
return this._age;
}
set{
if (value <= 0)
throw new Exception()
}
}
Auto Implemented property if we don't logic in get and set accessors we can use auto implemented property.
When use auto-implemented property compiles creates a private, anonymous field that can only be accessed through get and set accessors.
public int Age{get;set;}
Abstract Properties
An abstract class may have an abstract property, which should be implemented in the derived class
public abstract class Person
{
public abstract string Name
{
get;
set;
}
public abstract int Age
{
get;
set;
}
}
// overriden something like this
// Declare a Name property of type string:
public override string Name
{
get
{
return name;
}
set
{
name = value;
}
}
We can privately set a property
In this we can privately set the auto property(set with in the class)
public int MyProperty
{
get; private set;
}
You can achieve same with this code. In this property set feature is not available as we have to set value to field directly.
private int myProperty;
public int MyProperty
{
get { return myProperty; }
}

Using or not get and set methods in C# classes [duplicate]

In C#, what makes a field different from a property, and when should a field be used instead of a property?
Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.
public class MyClass
{
// this is a field. It is private to your class and stores the actual data.
private string _myField;
// this is a property. When accessed it uses the underlying field,
// but only exposes the contract, which will not be affected by the underlying field
public string MyProperty
{
get
{
return _myField;
}
set
{
_myField = value;
}
}
// This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax
// used to generate a private field for you
public int AnotherProperty { get; set; }
}
#Kent points out that Properties are not required to encapsulate fields, they could do a calculation on other fields, or serve other purposes.
#GSS points out that you can also do other logic, such as validation, when a property is accessed, another useful feature.
Object orientated programming principles say that, the internal workings of a class should be hidden from the outside world. If you expose a field you're in essence exposing the internal implementation of the class. Therefore we wrap fields with Properties (or methods in Java's case) to give us the ability to change the implementation without breaking code depending on us. Seeing as we can put logic in the Property also allows us to perform validation logic etc if we need it.
C# 3 has the possibly confusing notion of autoproperties. This allows us to simply define the Property and the C#3 compiler will generate the private field for us.
public class Person
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public int Age{get;set;} //AutoProperty generates private field for us
}
An important difference is that interfaces can have properties but not fields. This, to me, underlines that properties should be used to define a class's public interface while fields are meant to be used in the private, internal workings of a class. As a rule I rarely create public fields and similarly I rarely create non-public properties.
I'll give you a couple examples of using properties that might get the gears turning:
Lazy Initialization: If you have a property of an object that's expensive to load, but isn't accessed all that much in normal runs of the code, you can delay its loading via the property. That way, it's just sitting there, but the first time another module tries to call that property, it checks if the underlying field is null - if it is, it goes ahead and loads it, unknown to the calling module. This can greatly speed up object initialization.
Dirty Tracking: Which I actually learned about from my own question here on StackOverflow. When I have a lot of objects which values might have changed during a run, I can use the property to track if they need to be saved back to the database or not. If not a single property of an object has changed, the IsDirty flag won't get tripped, and therefore the saving functionality will skip over it when deciding what needs to get back to the database.
Using Properties, you can raise an event, when the value of the property is changed (aka. PropertyChangedEvent) or before the value is changed to support cancellation.
This is not possible with (direct access to) fields.
public class Person {
private string _name;
public event EventHandler NameChanging;
public event EventHandler NameChanged;
public string Name{
get
{
return _name;
}
set
{
OnNameChanging();
_name = value;
OnNameChanged();
}
}
private void OnNameChanging(){
NameChanging?.Invoke(this,EventArgs.Empty);
}
private void OnNameChanged(){
NameChanged?.Invoke(this,EventArgs.Empty);
}
}
Since many of them have explained with technical pros and cons of Properties and Field, it's time to get into real time examples.
1. Properties allows you to set the read-only access level
Consider the case of dataTable.Rows.Count and dataTable.Columns[i].Caption. They come from the class DataTable and both are public to us. The difference in the access-level to them is that we cannot set value to dataTable.Rows.Count but we can read and write to dataTable.Columns[i].Caption. Is that possible through Field? No!!! This can be done with Properties only.
public class DataTable
{
public class Rows
{
private string _count;
// This Count will be accessable to us but have used only "get" ie, readonly
public int Count
{
get
{
return _count;
}
}
}
public class Columns
{
private string _caption;
// Used both "get" and "set" ie, readable and writable
public string Caption
{
get
{
return _caption;
}
set
{
_caption = value;
}
}
}
}
2. Properties in PropertyGrid
You might have worked with Button in Visual Studio. Its properties are shown in the PropertyGrid like Text,Name etc. When we drag and drop a button, and when we click the properties, it will automatically find the class Button and filters Properties and show that in PropertyGrid (where PropertyGrid won't show Field even though they are public).
public class Button
{
private string _text;
private string _name;
private string _someProperty;
public string Text
{
get
{
return _text;
}
set
{
_text = value;
}
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
[Browsable(false)]
public string SomeProperty
{
get
{
return _someProperty;
}
set
{
_someProperty= value;
}
}
In PropertyGrid, the properties Name and Text will be shown, but not SomeProperty. Why??? Because Properties can accept Attributes. It does not show in case where [Browsable(false)] is false.
3. Can execute statements inside Properties
public class Rows
{
private string _count;
public int Count
{
get
{
return CalculateNoOfRows();
}
}
public int CalculateNoOfRows()
{
// Calculation here and finally set the value to _count
return _count;
}
}
4. Only Properties can be used in Binding Source
Binding Source helps us to decrease the number of lines of code. Fields are not accepted by BindingSource. We should use Properties for that.
5. Debugging mode
Consider we are using Field to hold a value. At some point we need to debug and check where the value is getting null for that field. It will be difficult to do where the number of lines of code are more than 1000. In such situations we can use Property and can set debug mode inside Property.
public string Name
{
// Can set debug mode inside get or set
get
{
return _name;
}
set
{
_name = value;
}
}
DIFFERENCES - USES (when and why)
A field is a variable that is declared directly in a class or struct. A class or struct may have instance fields or static fields or both. Generally, you should use fields only for variables that have private or protected accessibility. Data that your class exposes to client code should be provided through methods, properties and indexers. By using these constructs for indirect access to internal fields, you can guard against invalid input values.
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.
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.
Though fields and properties look to be similar to each other, they are 2 completely different language elements.
Fields are the only mechanism how to store data on class level. Fields are conceptually variables at class scope. If you want to store some data to instances of your classes (objects) you need to use fields. There is no other choice. Properties can't store any data even though, it may look they are able to do so. See bellow.
Properties on the other hand never store data. They are just the pairs of methods (get and set) that can be syntactically called in a similar way as fields and in most cases they access (for read or write) fields, which is the source of some confusion. But because property methods are (with some limitations like fixed prototype) regular C# methods they can do whatever regular methods can do. It means they can have 1000 lines of code, they can throw exceptions, call another methods, can be even virtual, abstract or overridden. What makes properties special, is the fact that C# compiler stores some extra metadata into assemblies that can be used to search for specific properties - widely used feature.
Get and set property methods has the following prototypes.
PROPERTY_TYPE get();
void set(PROPERTY_TYPE value);
So it means that properties can be 'emulated' by defining a field and 2 corresponding methods.
class PropertyEmulation
{
private string MSomeValue;
public string GetSomeValue()
{
return(MSomeValue);
}
public void SetSomeValue(string value)
{
MSomeValue=value;
}
}
Such property emulation is typical for programming languages that don't support properties - like standard C++. In C# there you should always prefer properties as the way how to access to your fields.
Because only the fields can store a data, it means that more fields class contains, more memory objects of such class will consume. On the other hand, adding new properties into a class doesn't make objects of such class bigger. Here is the example.
class OneHundredFields
{
public int Field1;
public int Field2;
...
public int Field100;
}
OneHundredFields Instance=new OneHundredFields() // Variable 'Instance' consumes 100*sizeof(int) bytes of memory.
class OneHundredProperties
{
public int Property1
{
get
{
return(1000);
}
set
{
// Empty.
}
}
public int Property2
{
get
{
return(1000);
}
set
{
// Empty.
}
}
...
public int Property100
{
get
{
return(1000);
}
set
{
// Empty.
}
}
}
OneHundredProperties Instance=new OneHundredProperties() // !!!!! Variable 'Instance' consumes 0 bytes of memory. (In fact a some bytes are consumed becasue every object contais some auxiliarity data, but size doesn't depend on number of properties).
Though property methods can do anything, in most cases they serve as a way how to access objects' fields. If you want to make a field accessible to other classes you can do by 2 ways.
Making fields as public - not advisable.
Using properties.
Here is a class using public fields.
class Name
{
public string FullName;
public int YearOfBirth;
public int Age;
}
Name name=new Name();
name.FullName="Tim Anderson";
name.YearOfBirth=1979;
name.Age=40;
While the code is perfectly valid, from design point of view, it has several drawbacks. Because fields can be both read and written, you can't prevent user from writing to fields. You can apply readonly keyword, but in this way, you have to initialize readonly fields only in constructor. What's more, nothing prevents you to store invalid values into your fields.
name.FullName=null;
name.YearOfBirth=2200;
name.Age=-140;
The code is valid, all assignments will be executed though they are illogical. Age has a negative value, YearOfBirth is far in future and doesn't correspond to Age and FullName is null. With fields you can't prevent users of class Name to make such mistakes.
Here is a code with properties that fixes these issues.
class Name
{
private string MFullName="";
private int MYearOfBirth;
public string FullName
{
get
{
return(MFullName);
}
set
{
if (value==null)
{
throw(new InvalidOperationException("Error !"));
}
MFullName=value;
}
}
public int YearOfBirth
{
get
{
return(MYearOfBirth);
}
set
{
if (MYearOfBirth<1900 || MYearOfBirth>DateTime.Now.Year)
{
throw(new InvalidOperationException("Error !"));
}
MYearOfBirth=value;
}
}
public int Age
{
get
{
return(DateTime.Now.Year-MYearOfBirth);
}
}
public string FullNameInUppercase
{
get
{
return(MFullName.ToUpper());
}
}
}
The updated version of class has the following advantages.
FullName and YearOfBirth are checked for invalid values.
Age is not writtable. It's callculated from YearOfBirth and current year.
A new property FullNameInUppercase converts FullName to UPPER CASE. This is a little contrived example of property usage, where properties are commonly used to present field values in the format that is more appropriate for user - for instance using current locale on specific numeric of DateTime format.
Beside this, properties can be defined as virtual or overridden - simply because they are regular .NET methods. The same rules applies for such property methods as for regular methods.
C# also supports indexers which are the properties that have an index parameter in property methods. Here is the example.
class MyList
{
private string[] MBuffer;
public MyList()
{
MBuffer=new string[100];
}
public string this[int Index]
{
get
{
return(MBuffer[Index]);
}
set
{
MBuffer[Index]=value;
}
}
}
MyList List=new MyList();
List[10]="ABC";
Console.WriteLine(List[10]);
Since C# 3.0 allows you to define automatic properties. Here is the example.
class AutoProps
{
public int Value1
{
get;
set;
}
public int Value2
{
get;
set;
}
}
Even though class AutoProps contains only properties (or it looks like), it can store 2 values and size of objects of this class is equal to sizeof(Value1)+sizeof(Value2)=4+4=8 bytes.
The reason for this is simple. When you define an automatic property, C# compiler generates automatic code that contains hidden field and a property with property methods accessing this hidden field. Here is the code compiler produces.
Here is a code generated by the ILSpy from compiled assembly. Class contains generated hidden fields and properties.
internal class AutoProps
{
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int <Value1>k__BackingField;
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int <Value2>k__BackingField;
public int Value1
{
[CompilerGenerated]
get
{
return <Value1>k__BackingField;
}
[CompilerGenerated]
set
{
<Value1>k__BackingField = value;
}
}
public int Value2
{
[CompilerGenerated]
get
{
return <Value2>k__BackingField;
}
[CompilerGenerated]
set
{
<Value2>k__BackingField = value;
}
}
}
So, as you can see, the compiler still uses the fields to store the values - since fields are the only way how to store values into objects.
So as you can see, though properties and fields have similar usage syntax they are very different concepts. Even if you use automatic properties or events - hidden fields are generated by compiler where the real data are stored.
If you need to make a field value accessible to the outside world (users of your class) don't use public or protected fields. Fields always should be marked as private. Properties allow you to make value checks, formatting, conversions etc. and generally make your code safer, more readable and more extensible for future modifications.
Properties have the primary advantage of allowing you to change the way data on an object is accessed without breaking it's public interface. For example, if you need to add extra validation, or to change a stored field into a calculated you can do so easily if you initially exposed the field as a property. If you just exposed a field directly, then you would have to change the public interface of your class to add the new functionality. That change would break existing clients, requiring them to be recompiled before they could use the new version of your code.
If you write a class library designed for wide consumption (like the .NET Framework, which is used by millions of people), that can be a problem. However, if you are writing a class used internally inside a small code base (say <= 50 K lines), it's really not a big deal, because no one would be adversely affected by your changes. In that case it really just comes down to personal preference.
Properties support asymmetric access, i.e. you can have either a getter and a setter or just one of the two. Similarly properties support individual accessibility for getter/setter. Fields are always symmetric, i.e. you can always both get and set the value. Exception to this is readonly fields which obviously cannot be set after initialization.
Properties may run for a very long time, have side effects, and may even throw exceptions. Fields are fast, with no side effects, and will never throw exceptions. Due to side effects a property may return a different value for each call (as may be the case for DateTime.Now, i.e. DateTime.Now is not always equal to DateTime.Now). Fields always return the same value.
Fields may be used for out / ref parameters, properties may not.
Properties support additional logic – this could be used to implement lazy loading among other things.
Properties support a level of abstraction by encapsulating whatever it means to get/set the value.
Use properties in most / all cases, but try to avoid side effects.
In the background a property is compiled into methods. So a Name property is compiled into get_Name() and set_Name(string value). You can see this if you study the compiled code.
So there is a (very) small performance overhead when using them. Normally you will always use a Property if you expose a field to the outside, and you will often use it internally if you need to do validation of the value.
When you want your private variable(field) to be accessible to object of your class from other classes you need to create properties for those variables.
for example if I have variables named as "id" and "name" which is private
but there might be situation where this variable needed for read/write operation outside of the class. At that situation , property can help me to get that variable to read/write depending upon the get/set defined for the property. A property can be a readonly / writeonly / readwrite both.
here is the demo
class Employee
{
// Private Fields for Employee
private int id;
private string name;
//Property for id variable/field
public int EmployeeId
{
get
{
return id;
}
set
{
id = value;
}
}
//Property for name variable/field
public string EmployeeName
{
get
{
return name;
}
set
{
name = value;
}
}
}
class MyMain
{
public static void Main(string [] args)
{
Employee aEmployee = new Employee();
aEmployee.EmployeeId = 101;
aEmployee.EmployeeName = "Sundaran S";
}
}
The second question here, "when should a field be used instead of a property?", is only briefly touched on in this other answer and kinda this one too, but not really much detail.
In general, all the other answers are spot-on about good design: prefer exposing properties over exposing fields. While you probably won't regularly find yourself saying "wow, imagine how much worse things would be if I had made this a field instead of a property", it's so much more rare to think of a situation where you would say "wow, thank God I used a field here instead of a property."
But there's one advantage that fields have over properties, and that's their ability to be used as "ref" / "out" parameters. Suppose you have a method with the following signature:
public void TransformPoint(ref double x, ref double y);
and suppose that you want to use that method to transform an array created like this:
System.Windows.Point[] points = new Point[1000000];
Initialize(points);
Here's I think the fastest way to do it, since X and Y are properties:
for (int i = 0; i < points.Length; i++)
{
double x = points[i].X;
double y = points[i].Y;
TransformPoint(ref x, ref y);
points[i].X = x;
points[i].Y = y;
}
And that's going to be pretty good! Unless you have measurements that prove otherwise, there's no reason to throw a stink. But I believe it's not technically guaranteed to be as fast as this:
internal struct MyPoint
{
internal double X;
internal double Y;
}
// ...
MyPoint[] points = new MyPoint[1000000];
Initialize(points);
// ...
for (int i = 0; i < points.Length; i++)
{
TransformPoint(ref points[i].X, ref points[i].Y);
}
Doing some measurements myself, the version with fields takes about 61% of the time as the version with properties (.NET 4.6, Windows 7, x64, release mode, no debugger attached). The more expensive the TransformPoint method gets, the less pronounced that the difference becomes. To repeat this yourself, run with the first line commented-out and with it not commented-out.
Even if there were no performance benefits for the above, there are other places where being able to use ref and out parameters might be beneficial, such as when calling the Interlocked or Volatile family of methods. Note: In case this is new to you, Volatile is basically a way to get at the same behavior provided by the volatile keyword. As such, like volatile, it doesn't magically solve all thread-safety woes like its name suggests that it might.
I definitely don't want to seem like I'm advocating that you go "oh, I should start exposing fields instead of properties." The point is that if you need to regularly use these members in calls that take "ref" or "out" parameters, especially on something that might be a simple value type that's unlikely to ever need any of the value-added elements of properties, an argument can be made.
Also, properties allow you to use logic when setting values.
So you can say you only want to set a value to an integer field, if the value is greater than x, otherwise throw an exception.
Really useful feature.
(This should really be a comment, but I can't post a comment, so please excuse if it is not appropriate as a post).
I once worked at a place where the recommended practice was to use public fields instead of properties when the equivalent property def would just have been accessing a field, as in :
get { return _afield; }
set { _afield = value; }
Their reasoning was that the public field could be converted into a property later in future if required. It seemed a little strange to me at the time. Judging by these posts, it looks like not many here would agree either. What might you have said to try to change things ?
Edit : I should add that all of the code base at this place was compiled at the same time, so they might have thought that changing the public interface of classes (by changing a public field to a property) was not a problem.
Technically, i don't think that there is a difference, because properties are just wrappers around fields created by the user or automatically created by the compiler.The purpose of properties is to enforce encapsuation and to offer a lightweight method-like feature.
It's just a bad practice to declare fields as public, but it does not have any issues.
Fields are ordinary member variables or member instances of a class. Properties are an abstraction to get and set their values. Properties are also called accessors because they offer a way to change and retrieve a field if you expose a field in the class as private. Generally, you should declare your member variables private, then declare or define properties for them.
class SomeClass
{
int numbera; //Field
//Property
public static int numbera { get; set;}
}
If you are going to use thread primitives you are forced to use fields. Properties can break your threaded code. Apart from that, what cory said is correct.
My design of a field is that a field needs to be modified only by its parent, hence the class. Result the variable becomes private, then to be able to give the right to read the classes / methods outside I go through the system of property with only the Get. The field is then retrieved by the property and read-only! If you want to modify it you have to go through methods (for example the constructor) and I find that thanks to this way of making you secure, we have better control over our code because we "flange". One could very well always put everything in public so every possible case, the notion of variables / methods / classes etc ... in my opinion is just an aid to the development, maintenance of the code. For example, if a person resumes a code with public fields, he can do anything and therefore things "illogical" in relation to the objective, the logic of why the code was written. It's my point of view.
When i use a classic model private field / public readonly properties,for 10 privates fields i should write 10 publics properties! The code can be really big faster. I discover the private setter and now i only use public properties with a private setter.
The setter create in background a private field.
That why my old classic programming style was:
public class MyClass
{
private int _id;
public int ID { get { return _id; } }
public MyClass(int id)
{
_id = id;
}
}
My new programming style:
public class MyClass
{
public int ID { get; private set; }
public MyClass(int id)
{
ID = id;
}
}
Basic and general difference is:
Fields
ALWAYS give both get and set access
CAN NOT cause side effects (throwing exceptions, calling methods, changing fields except the one being got/set, etc)
Properties
NOT ALWAYS give both get and set access
CAN cause side effects
Properties encapsulate fields, thus enabling you to perform additional processing on the value to be set or retrieved. It is typically overkill to use properties if you will not be doing any pre- or postprocessing on the field value.
IMO, Properties are just the "SetXXX()" "GetXXX()" functions/methods/interfaces pairs we used before, but they are more concise and elegant.
Traditionally private fields are set via getter and setter methods. For the sake of less code you can use properties to set fields instead.
when you have a class which is "Car". The properties are color,shape..
Where as fields are variables defined within the scope of a class.
From Wikipedia -- Object-oriented programming:
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which are data structures that contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. (emphasis added)
Properties are actually part of an object's behavior, but are designed to give consumers of the object the illusion/abstraction of working with the object's data.
Properties are special kind of class member, In properties we use a predefined Set or Get method.They use accessors through which we can read, written or change the values of the private fields.
For example, let us take a class named Employee, with private fields for name, age and Employee_Id. We cannot access these fields from outside the class , but we can access these private fields through properties.
Why do we use properties?
Making the class field public & exposing it is risky, as you will not have control what gets assigned & returned.
To understand this clearly with an example lets take a student class who have ID, passmark, name. Now in this example some problem with public field
ID should not be -ve.
Name can not be set to null
Pass mark should be read only.
If student name is missing No Name should be return.
To remove this problem We use Get and set method.
// A simple example
public class student
{
public int ID;
public int passmark;
public string name;
}
public class Program
{
public static void Main(string[] args)
{
student s1 = new student();
s1.ID = -101; // here ID can't be -ve
s1.Name = null ; // here Name can't be null
}
}
Now we take an example of get and set method
public class student
{
private int _ID;
private int _passmark;
private string_name ;
// for id property
public void SetID(int ID)
{
if(ID<=0)
{
throw new exception("student ID should be greater then 0");
}
this._ID = ID;
}
public int getID()
{
return_ID;
}
}
public class programme
{
public static void main()
{
student s1 = new student ();
s1.SetID(101);
}
// Like this we also can use for Name property
public void SetName(string Name)
{
if(string.IsNullOrEmpty(Name))
{
throw new exeception("name can not be null");
}
this._Name = Name;
}
public string GetName()
{
if( string.IsNullOrEmpty(This.Name))
{
return "No Name";
}
else
{
return this._name;
}
}
// Like this we also can use for Passmark property
public int Getpassmark()
{
return this._passmark;
}
}
Additional info:
By default, get and set accessors are as accessible as the property itself.
You can control/restrict accessor accessibility individually (for get and set) by applying more restrictive access modifiers on them.
Example:
public string Name
{
get
{
return name;
}
protected set
{
name = value;
}
}
Here get is still publicly accessed (as the property is public), but set is protected (a more restricted access specifier).
Think about it : You have a room and a door to enter this room. If you want to check how who is coming in and secure your room, then you should use properties otherwise they won't be any door and every one easily come in w/o any regulation
class Room {
public string sectionOne;
public string sectionTwo;
}
Room r = new Room();
r.sectionOne = "enter";
People is getting in to sectionOne pretty easily, there wasn't any checking
class Room
{
private string sectionOne;
private string sectionTwo;
public string SectionOne
{
get
{
return sectionOne;
}
set
{
sectionOne = Check(value);
}
}
}
Room r = new Room();
r.SectionOne = "enter";
Now you checked the person and know about whether he has something evil with him
Fields are the variables in classes. Fields are the data which you can encapsulate through the use of access modifiers.
Properties are similar to Fields in that they define states and the data associated with an object.
Unlike a field a property has a special syntax that controls how a person reads the data and writes the data, these are known as the get and set operators. The set logic can often be used to do validation.
Properties are used to expose field. They use accessors(set, get) through which the values of the private fields can be read, written or manipulated.
Properties do not name the storage locations. Instead, they have accessors that read, write, or compute their values.
Using properties we can set validation on the type of data that is set on a field.
For example we have private integer field age on that we should allow positive values since age cannot be negative.
We can do this in two ways using getter and setters and using property.
Using Getter and Setter
// field
private int _age;
// setter
public void set(int age){
if (age <=0)
throw new Exception();
this._age = age;
}
// getter
public int get (){
return this._age;
}
Now using property we can do the same thing. In the value is a key word
private int _age;
public int Age{
get{
return this._age;
}
set{
if (value <= 0)
throw new Exception()
}
}
Auto Implemented property if we don't logic in get and set accessors we can use auto implemented property.
When use auto-implemented property compiles creates a private, anonymous field that can only be accessed through get and set accessors.
public int Age{get;set;}
Abstract Properties
An abstract class may have an abstract property, which should be implemented in the derived class
public abstract class Person
{
public abstract string Name
{
get;
set;
}
public abstract int Age
{
get;
set;
}
}
// overriden something like this
// Declare a Name property of type string:
public override string Name
{
get
{
return name;
}
set
{
name = value;
}
}
We can privately set a property
In this we can privately set the auto property(set with in the class)
public int MyProperty
{
get; private set;
}
You can achieve same with this code. In this property set feature is not available as we have to set value to field directly.
private int myProperty;
public int MyProperty
{
get { return myProperty; }
}

C# - Difference between Automatic Property and returning a backing field?

Simple question I imagine, but what is the difference between these lines of code:
Code 1
public int Temp { get; set; }
and
Code 2
private int temp;
public int Temp { get { return temp; } }
My understand was that an automatic property as per Code 1 would perform the exact same function as Code 2?
I'm reading Head First C# and I'm finding it hard to understand why it's using two different ways of doing the same thing?
The primary difference between your Code1 and Code2 is that in #1, the property is settable.
You can achieve the same thing using automatic properties, because the setter can be private:
public int Temp { get; private set; }
Automatic properties was added in C#3, and is really just syntactic sugar for the longer version using a field. If you don't need to access the field directly, there is no reason not to use automatic properties. Automatic properties are equivalent to using a field - the compiler generates the field for you, it is just not accessible in code.
The first one is a writable property.
It's equivalent to
private int temp;
public int Temp {
get { return temp; }
set { temp = value; }
}
(except that you can't use the backingfield directly), but it requires 1 line of code instead of five.
When writing classes with 5 or 6 simple properties, auto-properties can make the classes much shorter.
You can make read-only auto-properties by writing
public int Temp { get; private set; }
The "automagic" property is just a "short-hand" notation:
public int Temp { get; set; }
is just a lot simpler to type than
public int Temp
{
get { return _temp; }
set { _temp = value; }
}
but functionally equivalent. Just a nice "shorthand" to improve your productivity, but no additional or magic functionality, really.
If your second example had both a getter and a setter, they would be functionally equivalent.
As it stands now, the first is publicly gett-able but can't be set publicly. You could also achieve the same thing using auto properties:
public int Temp { get; private set; }
And in case you're curious, automatic properties still get a backing private field. That bit is just handled by the compiler for you so that life is easier.
As for the reason why I would use property with a backing field is when I want to do something else when getting or setting the property. For example, a validation routine embedded into the property itself, or caching, etc...
Otherwise, for simple get and set, I'd use the automatic property format. It's more compact and involves less coding which I think it's a good thing.

Property as parameter? C#

So I've got a whole bunch of options, every different page/tab can have their own local options. We'll have maybe 10-15 pages tabs open tops. I need to implement a way to show the global defaults, weather the all the tabs have consistent values. I'm working on the model/viewmodel portion of a WPF app.
I'd love to find a way that is more elegant since I'm having to cut and past roughly the same code 20+ times and just change property names. Maybe this is the problem Dynamics solve, but right now this feels both wrong and painful.
Here is an example of my current solution:
public class Foo
{
private bool fooVar1;
private bool fooVar2;
//lots of these
private decimal fooVar23;
public Foo()
{
}
public bool FooVar1
{
get;
set;
}
//you get the picture...
}
public class FooMonitor
{
private Foo defaultFoo;
private List<Foo> allFoos;
public FooMonitor(Foo DefaultFoo)
{
defaultFoo = DefaultFoo;
}
public void AddFoo(Foo newFoo)
{
allFoos.Add(newFoo);
}
public void AddFoo(Foo oldFoo)
{
allFoos.Remove(oldFoo);
}
public bool IsFooVar1Consistent
{
get
{
Foo[] tempFoos = allFoos.ToArray();
foreach (Foo tempFoo in tempFoos)
{
if (tempFoo.FooVar1 != defaultFoo.FooVar1) return false;
}
return true;
}
}
}
Or am I approaching this problem entirely incorrectly.
As I'm writing this question (After about 2000 lines of code) I'm thinking of how I read that WPF itself implements Dictionary look ups that crawl up to the parent to see if a Property is present and what the value should be.
Well, for a start you are defining both backing fields which will never be used and automatic properties. This is enough for a simple bool property:
public bool FooVar1 { get; set; }
No need for the private field. This greatly reduces the number of lines in your example.
I'd love to find a way that is more
elegant since I'm having to cut and
past roughly the same code 20+ times
and just change property names.
Code generators exist for exactly this purpose. But if you don't want to go that route, you can shorten your code to this:
return allFoos.All(foo => foo.FooVar1 == defaultFoo.FooVar1);
I'm not quite sure what the question is, but if you're looking for some way to unify the IsFoorVarXConsistent code, you could do it using reflection or by passing in an expression:
public bool IsConsistent(Func<Foo, bool> property)
{
foreach (Foo tempFoo in allFoos)
{
if (property(tempFoo) != property(defaultFoo))
return false;
}
return true;
}
Called like this:
bool is1Consistent = IsConsistent(f => f.FooVar1);
As shown this will only work for boolean properties. To extend it to other types, we can make it generic in the property type. However, in this case we cannot use != to test for inequality because not all types define a != operator. Instead we can use the .Equals method and the ! operator:
public bool IsConsistent<T>(Func<Foo, T> property)
where T : struct
{
foreach (Foo tempFoo in allFoos)
{
if (!property(tempFoo).Equals(property(defaultFoo)))
return false;
}
return true;
}
The where T : struct clause restricts this to value types like int, bool and decimal. In particular it will not work on strings. Removing the where constraint allows it to work on strings and other reference types, but creates the possibility of property(tempFoo) being null, which would cause a NullReferenceException when we called .Equals on it. So if you remove the value types constraint then you will need to add error handling for this scenario.

C# design for an object where some properties are expensive: excuse to make it mutable?

Yes, I know, yet another question about mutable objects. See this for general background and this for the closest analogue to my question. (though it has some C++ specific overtones that don't apply here)
Let's assume that the following pseudo code represents the best interface design. That is, it's the clearest expression of the business semantics (as they stand today) into OO type. Naturally, the UglyData and the things we're tasked to do with it are subject to incremental change.
public class FriendlyWrapper
{
public FriendlyWrapper(UglyDatum u)
{
Foo = u.asdf[0].f[0].o.o;
Bar = u.barbarbar.ToDooDad();
Baz = u.uglyNameForBaz;
// etc
}
public Widget Foo { get; private set; }
public DooDad Bar { get; private set; }
public DooDad Baz { get; private set; }
// etc
public WhizBang Expensive1 { get; private set; }
public WhizBang Expensive2 { get; private set; }
public void Calculate()
{
Expensive1 = Calc(Foo, Bar);
Expensive2 = Calc(Foo, Baz);
}
private WhizBang Calc(Widget a, DooDad b) { /* stuff */ }
public override void ToString()
{
return string.Format("{0}{1}{2}{3}{4}", Foo, Bar, Baz, Expensive1 ?? "", Expensive2 ?? "");
}
}
// Consumer 1 is happy to work with just the basic wrapped properties
public string Summarize()
{
var myStuff = from u in data
where IsWhatIWant(u)
select new FriendlyWrapper(u);
var sb = new StringBuilder();
foreach (var s in myStuff)
{
sb.AppendLine(s.ToString());
}
return sb.ToString();
}
// Consumer 2's job is to take the performance hit up front. His callers might do things
// with expensive properties (eg bind one to a UI element) that should not take noticeable time.
public IEnumerable<FriendlyWrapper> FetchAllData(Predicate<UglyDatum> pred)
{
var myStuff = from u in data
where pred(u)
select new FriendlyWrapper(u);
foreach (var s in myStuff)
{
s.Calculate(); // as written, this doesn't do what you intend...
}
return myStuff;
}
What's the best route here? Options I can see:
Mutable object with an explicit Calculate() method, as above
Mutable object where expensive calculations are done in the getters (and probably cached)
Split into two objects where one inherits (or perhaps composes?) from the other
Some sort of static + locking mechanism, as in the C++ question linked above
I'm leaning toward #2 myself. But every route has potential pitfalls.
If you choose #1 or #2, then how would you implement Consumer2's loop over mutables in a clear, correct manner?
If you choose #1 or #3, how would you handle future situations where you only want to calculate some properties but not others? Willing to create N helper methods / derived classes?
If you choose #4, I think you're crazy, but feel free to explain
In your case, since you're using LINQ, you're only going to constructing these objects in cases where you want the calculation.
If that is your standard usage pattern, I would just put the expensive calculation directly in the constructor. Using lazy initialization is always slower unless you plan to have some cases where you do not calculate. Doing the calculation in the getters will not save anything (at least in this specific case).
As for mutability - mutable objects with reference syntax and identity (ie: classes in C#) are really okay - it's more a problem when you're dealing with mutable value types (ie: structs). There are many, many mutable classes in the .NET BCL - and they don't cause issues. The problem is typically more of one when you start dealing with value types. Mutable value types lead to very unexpected behavior.
In general, I'd turn this question upside down - How and where are you going to use this object? How can you make this object the most performant (if it's been determined to be problematic) without affecting usability? Your 1), 3) and 4) options would all make usability suffer, so I'd avoid them. In this case, doing 2) won't help. I'd just put it in the constructor, so your object's always in a valid state (which is very good for usability and maintainability).

Categories