Why not explicitly initialized readonly autoimplemented property is valid in c# 6? - c#

Update 1
It seems like either my English is terribly awful, or people just don't give a sh... to understand what I'm asking about or simply look at the title of the post.
C#5 specification clearly states:
Because the backing field is inaccessible, it can be read and written
only through the property accessors, even within the containing type.
This means that automatically implemented read-only or write-only
properties do not make sense, and are disallowed.
public string MyProperty {get;} has no sense, yet it costs nothing for compiler to emit getter not even warring about lacking setter. Backing field will be initialized with a default value. What does it mean? It means that designers spent some effort to implement a verification, to introduce functionality that could be left out.
Let's now consider C#6:
In C#6 the initialization of auto-implemented properties was introduced.
public string FirstName { get; set; } = "Jane";
or
public string FirstName { get; } = "Jane";
In the latter case property can be set in a constructor as well:
public class Program
{
public string ImagePath { get; }
public static void Main()
{
}
public Program()
{
ImagePath = "";
}
}
But only in constructor of the class where property was declared. Derived classes cannot set property's value.
Now ask yourself what this property means, if it was not initialized in constructor:
property string My {get;}
This is a 100% equivalent of C#5 prohibited property. It has no sense.
But such declaration being invalid in C#5 became valid in C#6. However semantics didn't change at all: this property is useless without explicit initialization.
That's why I am asking:
Why not explicitly initialized readonly auto-implemented property is valid in c# 6?
What I expect to see as an answer:
Either debunking of my initial assumptions about changes in C#6
Or the explanation of how and why compiler designers changed their mind
about what makes sense, and what does not.
I find the answer It's by design to be completely irrelevant. It is just a fact. I look for reasons. I don't believe compiler designers decide on changes in behavior of compiler with just tossing the coin.
This is an example of good answer.
Original question
In VS2015 this code is compiled without errors:
public class Program
{
public string ImagePath { get; }
public static void Main()
{
Console.WriteLine("Hello World");
}
}
However, in VS2013 I get error:
Compilation error (line 5, col 28): 'Program.ImagePath.get' must
declare a body because it is not marked abstract or extern.
Automatically implemented properties must define both get and set
accessors.
I know about initializable auto implemented properties, and in case of VS2015 field gets default value, that is null here. But then it's interesting to know why this snippet was invalid in C# 5?
Initializable auto-implemented readonly property left without explicit initialization seems to me a bit ODD. It is likely a mistake rather than intention. I'd personally prefer compiler to require explicit initialization in this case:
public string ImagePath { get; } = default(string);
Ok, I know that such property can be also assigned in constructor:
public class Program
{
public string ImagePath { get; }
public static void Main()
{
}
public Program()
{
ImagePath = "";
DoIt();
}
public void DoIt()
{
//ImagePath = "do it";
}
}
public class My : Program
{
public My()
{
//ImagePath = "asdasd";
}
}
But if compiler can check that local variable is not initialized, the same is possible for the property.
So why is it as it is?

The compiler is telling you that automatic properties must have both accessors defined. For example, you could fix the error with
public string ImagePath { get; private set; }
assuming that you do not intend the property to be settable outside the class.
As to why you have to declare a setter or manually implement the property -- well, what good would be a property that you can read from, but will always return the default value of its type since there is no way to set it? Conversely, what good would be a property you can write to but can neither read from nor hook into its setter?
C# 6.0 gives you the option of having write-once, read many auto-properties; this is a huge difference as the value can be arbitrarily chosen, allowing you convenient syntax for properties with immutable values.

I have no idea why your question have been down voted. This is interesting observation but please keep in mind that it is not a breaking change - it is just 'new functionality' that is 'leftover' of other functionality - initialization of auto-implemented properties.
That means it had no sense previously, but now it has.
Moreover, I think it has always had sense. E.g. when you have some base class or interface, for example
interface IPerson
{
int Age { get; }
}
Some day you may want to implement null-object pattern where the age is irrelevant. In c#5 you have to write public int Age { get { return 0; } }, while in c#6 you can simply do public int Age { get; } or even transform interface to abstract class changing only its definition from interface to abstract class.

Related

DbContext with and without { get; set; } in C# [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; }
}

Object Oriented - Class Variables

I am pretty new to OOP and looking into things in a bit more depth, but I have a bit of confusion between these 3 methods in C# and which one is best and what the differences are between 2 of them.
Example 1
So lets start with this one, which (so I understand) is the wrong way to do it:
public class MyClass
{
public string myAttribute;
}
and in this way I can set the attribute directly using:
myObject.myAttribute = "something";
Example 2
The next way I have seen and that seems to be recomended is this:
public class MyClass
{
public string myAttribute { get; set;}
}
With getters and setters, this where I dont understand the difference between the first 2 as the variable can still be set directly on the object?
Example 3
The third way, and the way that I understand the theory behind, is creating a set function
public class MyClass
{
string myAttribute;
public void setAttribute(string newSetting)
{
myAttribute = newSetting;
//obviously you can apply some logic in here to remove unwanted characters or validate etc.
}
}
So, what are the differences between the three? I assume example 1 is a big no-no so which is best out of 2 and 3, and why use one over the other?
Thanks
The second
public class MyClass
{
public string MyAttribute { get; set;}
}
is basically shorthand for:
public class MyClass
{
private string myPrivateAttribute;
public string MyAttribute
{
get {return myPrivateAttribute;}
set {myPrivateAttribute = value;}
}
}
That is an auto-implemented property, which is exactly the same as any regular property, you just do not have to implement it, when the compiler can do that for you.
So, what is a property? It's nothing more than a couple of methods, coupled with a name. I could do:
public class MyClass
{
private string myPrivateAttribute;
public string GetMyAttribute()
{
return myPrivateAttribute;
}
public void SetMyAttribute(string value)
{
myPrivateAttribute = value;
}
}
but then instead of writing
myClass.MyAttribute = "something";
string variable = myClass.MyAttribute;
I would have to use the more verbose, but not necessarily clearer form:
myClass.SetMyAttribute("something");
string variable = myClass.GetMyAttribute();
Note that nothing constraints the contents of the get and set methods (accessors in C# terminology), they are methods, just like any other. You can add as much or as little logic as you need inside them. I.e. it is useful to make a prototype with auto-implemented properties, and later to add any necessary logic (e.g. log property access, or add lazy initalization) with an explicit implementation.
What your asking here has to do with encapsulation in OOP languages.
The difference between them is in the way you can access the propriety of an object after you created an object from your class.
In the fist example you can access it directly new MyClass().MyAttribute whether you get or set it's value.
In the second example you declare 2 basic functions for accessing it:
public string MyAttribute
{
get {return myPrivateAttribute;}
set {myPrivateAttribute = value;}
}
In the third example you declare your own method for setting the value. This is useful if you want to customize the setter. For example you don't want to set the value passed, but the value multiplied by 2 or something else...
I recommend some reading. You can find something here and here.
Property is a syntactic sugar over private attribute with get and set methods and it's realy helpful and fast to type;
You may treat automatic property with { get; set;} as a public attribute. It has no additional logic but you may add it later without uset ever notice it.
Just exchange
public string MyLine { get; set;}
to
string myLine;
public string MyLine
{
get { return myLine; }
set { myLine = value + Environment.NewLine; }
}
for example if you need so.
You can also easily create read only property as { get; private set }.
So use Properties instead of public attributes every time just because its easier and faster to write and it's provides better encapsulation because user should not be used get and set methods if you decide to use it in new version of yours programm.
One of the main principles of OOP is encapsulation, and this is essentially the difference between the first example and the other 2.
The first example you have a private field which is exposed directly from the object - this is bad because you are allowing mutation of internal data from outside the object and therefore have no control over it.
The other 2 examples are syntactically equivalent, the second being recommended simply because it's less code to write. However, more importantly they both restrict access & control mutation of the internal data so give you complete control over how the data should be managed - this is ecapsulation.

Getters, setters, and properties best practices. Java vs. C#

I'm taking a C# class right now and I'm trying to find out the best way of doing things. I come from a Java background and so I'm only familiar with Java best-practices; I'm a C# novice!
In Java if I have a private property, I do this;
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
In C#, I see that there are many ways of doing this.
I can do it like Java:
private string name;
public void setName(string name) {
this.name = name;
}
public string getName() {
return this.name;
}
Or I can do it this way:
private string name;
public string Name {
get { return name; }
set { name = value; }
}
Or:
public string Name { get; set; }
Which one should I use, and what are the caveats or subtleties involved with each approach? When creating classes, I am following general best-practices that I know from Java (especially reading Effective Java). So for example, I am favoring immutability (providing setters only when necessary). I'm just curious to see how these practices fit in with the various ways of providing setters and getters in C#; essentially, how would I translate best-practices from the Java world into C#?
EDIT
I was posting this as a comment to Jon Skeet's answer but then it got long:
What about a non-trivial property (i.e., with significant processing and validation perhaps)? Could I still expose it via a public property but with the logic encapsulated in get and set? Why would/should I do this over having dedicated setter and getter methods (with associated processing and validation logic).
Pre-C# 6
I'd use the last of these, for a trivial property. Note that I'd call this a public property as both the getters and setters are public.
Immutability is a bit of a pain with automatically implemented properties - you can't write an auto-property which only has a getter; the closest you can come is:
public string Foo { get; private set; }
which isn't really immutable... just immutable outside your class. So you may wish to use a real read-only property instead:
private readonly string foo;
public string Foo { get { return foo; } }
You definitely don't want to write getName() and setName(). In some cases it makes sense to write Get/Set methods rather than using properties, particularly if they could be expensive and you wish to emphasize that. However, you'd want to follow the .NET naming convention of PascalCase for methods, and you wouldn't want a trivial property like this to be implemented with normal methods anyway - a property is much more idiomatic here.
C# 6
Hooray, we finally have proper read-only automatically implemented properties:
// This can only be assigned to within the constructor
public string Foo { get; }
Likewise for read-only properties which do need to do some work, you can use member-bodied properties:
public double Area => height * width;
If all you need is a variable to store some data:
public string Name { get; set; }
Want to make it appear read-only?
public string Name { get; private set; }
Or even better...
private readonly string _name;
...
public string Name { get { return _name; } }
Want to do some value checking before assigning the property?
public string Name
{
get { return m_name; }
set
{
if (value == null)
throw new ArgumentNullException("value");
m_name = value;
}
}
In general, the GetXyz() and SetXyz() are only used in certain cases, and you just have to use your gut on when it feels right. In general, I would say that I expect most get/set properties to not contain a lot of logic and have very few, if any, unexpected side effects. If reading a property value requires invoking a service or getting input from a user in order to build the object that I'm requesting, then I would wrap it into a method, and call it something like BuildXyz(), rather than GetXyz().
Use properties in C#, not get/set methods. They are there for your convenience and it is idiomatic.
As for your two C# examples, one is simply syntactic sugar for the other. Use the auto property if all you need is a simple wrapper around an instance variable, use the full version when you need to add logic in the getter and/or setter.
In C# favor properties for exposing private fields for get and/or set. The thie form you mention is an autoproperty where the get and set automatically generate a hidden pivot backing field for you.
I favor auto properties when possible but you should never do a set/get method pair in C#.
public string Name { get; set; }
This is simply a auto-implemented property, and is technically the same as a normal property. A backing field will be created when compiling.
All properties are eventually converted to functions, so the actual compiled implementation in the end is the same as you are used to in Java.
Use auto-implemented properties when you don't have to do specific operations on the backing field. Use a ordinary property otherwise. Use get and set functions when the operation has side effects or is computationally expensive, use properties otherwise.
Regardless of which way you choose in C# the end result is the same. You will get a backinng variable with separate getter and setter methods. By using properties you are following best practices and so it's a matter of how verbose you want to get.
Personally I would choose auto-properties, the last version: public string Name { get; set; }, since they take up the least amount of space. And you can always expand these in the future if you need add something like validation.
Whenever possible I prefer public string Name { get; set; } as it's terse and easily readable. However, there may be times when this one is necessary
private string name;
public string Name {
get { return name; }
set { name = value; }
}
In C# the preferred way is through properties rather than getX() and setX() methods. Also, note that C# does not require that properties have both a get and a set - you can have get-only properties and set-only properties.
public boolean MyProperty
{
get { return something; }
}
public boolean MyProperty
{
set { this.something = value; }
}
First let me try to explain what you wrote:
// private member -- not a property
private string name;
/// public method -- not a property
public void setName(string name) {
this.name = name;
}
/// public method -- not a property
public string getName() {
return this.name;
}
// yes it is property structure before .Net 3.0
private string name;
public string Name {
get { return name; }
set { name = value; }
}
This structure is also used nowadays but it is most suitable if you want to do some extra functionality, for instance when a value is set you can it to parse to capitalize it and save it in private member for alter internal use.
With .net framework 3.0
// this style is introduced, which is more common, and suppose to be best
public string Name { get; set; }
//You can more customize it
public string Name
{
get;
private set; // means value could be set internally, and accessed through out
}
Wish you better luck in C#
As mentioned, all of these approaches result in the same outcome. The most important thing is that you pick a convention and stick with it. I prefer using the last two property examples.
like most of the answers here, use Automatic properties. Intuitive, less lines of code and it is more clean. If you should serialize your class, mark the class [Serializable]/ with [DataConract] attribute. And if you are using [DataContract] mark the member with
[DataMember(Name="aMoreFriendlyName")]
public string Name { get; set; }
Private or public setter depends on your preference.
Also note that automatic properties require both getters and setters(public or private).
/*this is invalid*/
public string Name
{
get;
/* setter omitted to prove the point*/
}
Alternatively, if you only want get/set, create a backing field yourself
Which one should I use, and what are the caveats or subtleties involved with each approach?
When going with properties there is one caveat that has not been mentioned yet: With properties you cannot have any parametrization of your getters or setters.
For example imagine you want to retrieve a list items and want to also apply a filter at the same time. With a get-method you could write something like:
obj.getItems(filter);
In contrast, with a property you are forced to first return all items
obj.items
and then apply the filter in the next step or you have to add dedicated properties that expose items filtered by different criteria, which soon bloats your API:
obj.itemsFilteredByX
obj.itemsFilteredByY
What sometimes can be a nuisance is when you started with a property, e.g. obj.items and then later discovered that getter- or setter-parametrization is needed or would make things easier for the class-API user. You would now need to either rewrite your API and modify all those places in your code that access this property or find an alternative solution. In contrast, with a get-method, e.g. obj.getItems(), you can simply extend your method's signature to accept an optional "configuration" object e.g. obj.getItems(options) without having to rewrite all those places that call your method.
That being said, (auto-implemented) properties in C# are still very useful shortcuts (for the various reasons mentioned here) since most of the time parametrization may not be needed – but this caveat stands.

How to implement a read only property

I need to implement a read only property on my type. Moreover the value of this property is going to be set in the constructor and it is not going to be changed (I am writing a class that exposes custom routed UI commands for WPF but it does not matter).
I see two ways to do it:
class MyClass
{
public readonly object MyProperty = new object();
}
class MyClass
{
private readonly object my_property = new object();
public object MyProperty { get { return my_property; } }
}
With all these FxCop errors saying that I should not have public member variables, it seems that the second one is the right way to do it. Is this correct?
Is there any difference between a get only property and a read only member in this case?
The second way is the preferred option.
private readonly int MyVal = 5;
public int MyProp { get { return MyVal;} }
This will ensure that MyVal can only be assigned at initialization (it can also be set in a constructor).
As you had noted - this way you are not exposing an internal member, allowing you to change the internal implementation in the future.
C# 6.0 adds readonly auto properties
public object MyProperty { get; }
So when you don't need to support older compilers you can have a truly readonly property with code that's just as concise as a readonly field.
Versioning:
I think it doesn't make much difference if you are only interested in source compatibility.
Using a property is better for binary compatibility since you can replace it by a property which has a setter without breaking compiled code depending on your library.
Convention:
You are following the convention. In cases like this where the differences between the two possibilities are relatively minor following the convention is better. One case where it might come back to bite you is reflection based code. It might only accept properties and not fields, for example a property editor/viewer.
Serialization
Changing from field to property will probably break a lot of serializers. And AFAIK XmlSerializer does only serialize public properties and not public fields.
Using an Autoproperty
Another common Variation is using an autoproperty with a private setter. While this is short and a property it doesn't enforce the readonlyness. So I prefer the other ones.
Readonly field is selfdocumenting
There is one advantage of the field though:
It makes it clear at a glance at the public interface that it's actually immutable (barring reflection). Whereas in case of a property you can only see that you cannot change it, so you'd have to refer to the documentation or implementation.
But to be honest I use the first one quite often in application code since I'm lazy. In libraries I'm typically more thorough and follow the convention.
With the introduction of C# 6 (in VS 2015), you can now have get-only automatic properties, in which the implicit backing field is readonly (i.e. values can be assigned in the constructor but not elsewhere):
public string Name { get; }
public Customer(string name) // Constructor
{
Name = name;
}
private void SomeFunction()
{
Name = "Something Else"; // Compile-time error
}
And you can now also initialise properties (with or without a setter) inline:
public string Name { get; } = "Boris";
Referring back to the question, this gives you the advantages of option 2 (public member is a property, not a field) with the brevity of option 1.
Unfortunately, it doesn't provide a guarantee of immutability at the level of the public interface (as in #CodesInChaos's point about self-documentation), because to a consumer of the class, having no setter is indistinguishable from having a private setter.
In C# 9, Microsoft introduced a new way to have properties set only on initialization using the init accessor, like so:
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
This way, you can assign values when initializing a new object:
var person = new Person
{
Firstname = "John",
LastName = "Doe"
}
But later on, you cannot change it:
person.LastName = "Denver"; // throws a compiler error
You can do this:
public int Property { get { ... } private set { ... } }
I agree that the second way is preferable. The only real reason for that preference is the general preference that .NET classes not have public fields. However, if that field is readonly, I can't see how there would be any real objections other than a lack of consistency with other properties. The real difference between a readonly field and get-only property is that the readonly field provides a guarantee that its value will not change over the life of the object and a get-only property does not.
yet another way (my favorite), starting with C# 6
private readonly int MyVal = 5;
public int MyProp => MyVal;
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties#expression-body-definitions
The second method is preferred because of the encapsulation. You can certainly have the readonly field be public, but that goes against C# idioms in which you have data access occur through properties and not fields.
The reasoning behind this is that the property defines a public interface and if the backing implementation to that property changes, you don't end up breaking the rest of the code because the implementation is hidden behind an interface.

Should I use public properties and private fields or public fields for data?

In much of the code I have seen (on SO, thecodeproject.com and I tend to do this in my own code), I have seen public properties being created for every single private field that a class contains, even if they are the most basic type of get; set; like:
private int myInt;
public int MyInt
{
get { return myInt; }
set { myInt = value }
}
My question is: how does this differ from:
public int MyInt;
and if we should use properties instead of public fields why should we use them in this specific case? (I am not talking about more complex examples where the getters and setters actually do something special or there is only one get or set (read/write only) rather than just returning/setting a value of a private field). It does not seem to add any extra encapsulation, only give a nice icon in IntelliSense and be placed in a special section in class diagrams!
See this article http://blog.codinghorror.com/properties-vs-public-variables/
Specifically
Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
You can't databind against a variable.
Changing a variable to a property is a breaking change.
Three reasons:
You cannot override fields in subclasses like you can properties.
You may eventually need a more complex getter or setter, but if it's a field, changing it would break the API.
Convention. That's just the way it's done.
I'm sure there are more reasons that I'm just not thinking of.
In .Net 3.x you can use automatic properties like this:
public int Age { get; set; }
instead of the old school way with declaring your private fields yourself like this:
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
This makes it as simple as creating a field, but without the breaking change issue (among other things).
When you create private field name and a simple public property Name that actually gets and sets the name field value
public string Name
{
get { return name; }
}
and you use this property everywhere outside your class and some day you decide that the Name property of this class will actually refer to the lastName field (or that you want to return a string "My name: "+name), you simply change the code inside the property:
public string Name
{
get { return lastName; //return "My name: "+name; }
}
If you were using public field name everywhere in the outside code then you would have to change name to lastName everywhere you used it.
Well it does make a difference. Public data can be changed without the object instance knowing about it. Using getters and setters the object is always aware that a change has been made.
Remember that encapsulating the data is only the first step towards a better structured design, it's not an end-goal in itself.
You have to use properties in the following cases:
When you need to serialize data in the property to some format.
When you need to override properties in derived class.
When you implement get and set methods with some logic. For example, when you implement Singleton pattern.
When you're derived from interface, where property was declared.
When you have specific issues related to Reflection.
It... depends?
I always use getters & setters, since they created this shortcut:
public int Foo { get; set; }
At compile time it is translated. Now you can't get fancy with it, but it is there, and if you need to get fancy you just spell it out later.
However public, private, protected... it's all a matter of who you want to be able to tweak the data. We use inheritance a lot and this is a very common method for us, so that only chidren can edit certain properties.
protected _foo;
public Foo
{
get { return _foo; }
} //lack of set intentional.
I can't believe that with 11 answers, nobody has said this:
Not all private fields should be exposed as public properties. You should certainly use properties for anything that needs to be non-private, but you should keep as much of your class private as possible.
There are many reasons why.
Mainly:
You can do some other functions when the variable is set
You can prevent setting and provide only get
Some 'things' only work on properties (DataBinding, for example)
You can hide the implementation of the property [perhaps it is a ViewState variable, in ASP.NET).
The point is - what if further down the line you want to make sure that every time myInt is referenced something special happens (a log file is written to, it's changed to 42 etc)? You can't do that without getters and setters. Sometimes it's wise to program for what you might need, not what you need right now.
Actually, if you're using Silverlight, you'll realise that fields cannot be set a static resources and thus you'll have to use a property (even to access a const).
I've realised that when I tried to federate the region names I use in Composite Guidance (PRISM).
However, that's just a language limitations and apart from static/const fields I alsways use properties.
The idea is you should not accidentally/unintentionally change the value of a class private field outside.
When you use get and set, that means you are changing the class private field intentionally and knowingly.
Setting a value into a private field only changes that field,but making them in property you can handle another arguments for example,you can call a method after setting a value
private string _email;
public string Email
{
get
{
return this._email;
}
set
{
this._email = value;
ReplaceList(); //**
}
}
In simpler words, answer to your question is the access modifiers i.e. public and private.
If you use:
public int myInt;
public int MyInt
{
get { return myInt; }
set { myInt = value }
}
then both MyInt property and myInt variable is available in the project to be modified.
Means, if your class suppose A is inherited by class suppose B,
then myInt and MyInt both are available for modification and no check can be applied.
Suppose you want myInt value can be set in derive class if some particular condition pass.
This can be achieved only by making field private and property to be public.
So that only property is available and conditions can be set based on that.

Categories

Resources