As in title: what is the difference between:
private readonly string name = "ourName";
and
private string name { get { return "ourName" } }
The first version is part of the state of the object - it's just a field. It can still be changed within the constructor body, too.
The second version is just a property - it's effectively a method which returns the same value every time you call it, and isn't really part of the state of the object. (There's no field involved.)
The first is a field. The second is a property. The field holds the value "ourName" as local state. The property provides a method stateless accessing the literal "ourName".
You can set the field and mutate the state of the field in a constructor. You can also pass the field to a ref or out parameter of a method in the constructor.
None of these statements are true about the property. All you can do with the property is read the value returned by invoking the underlying get_name() method (which always returns the same literal value "ourName". Furthermore, consider these examples to see how the field case can be used in contrast to the property:
public class ExampleWithField
{
public ExampleWithField(){
this.name = "Not our name"; // the value will be "Not our name"
}
private readonly string name = "ourName";
}
public class ExampleWithFieldAndRefParam
{
public ExampleWithFieldAndRefParam(){
SetRefValue(ref this.name); // the value will be "Not our nameourName"
}
static void SetRefValue(ref string value){ value = "Not our name" + value; }
private readonly string name = "ourName";
}
public class ExampleWithFieldAndOutParam
{
public ExampleWithFieldAndOutParam(){
SetOutValue(out this.name); // the value will be "Not our name"
}
static void SetOutValue(out string value){ value = "Not our name"; }
private readonly string name = "ourName";
}
public class ExampleWithProperty
{
public ExampleWithProperty(){
this.name = "Not our name"; // this will not compile.
}
private string name { get { return "ourName"; } }
}
Also if you use reflection or serialization, it will behave different, ie: the GetProperties() method won't return the field in the first case and the field won't be serialized on the last one.
readonly field can be initialized/set in constructor.
property with only get works like function. can not be set in common case
A readonly field could be assigned to by a constructor. A property with no set method couldn't be assigned to by anything.
this is a field declaration that can only be set during declaration:
readonly string name = "abc";
or inside of a the class constructor.
Properties on the other hand are like syntactic sugar for methods. (i.e. get is for getFoo() and set is for setFoo(object value).
so the following line is actually compiled to a single method:
string name { get { return "xyz"; } }
this is why you cannot use properties as values to out or ref parameters
Related
I've seen Marc Gravell's answer from May 8 '09 at 13:29
:
public sealed class WriteOnce<T>
{
private T value;
private bool hasValue;
public override string ToString()
{
return hasValue ? Convert.ToString(value) : "";
}
public T Value
{
get
{
if (!hasValue) throw new InvalidOperationException("Value not set");
return value;
}
set
{
if (hasValue) throw new InvalidOperationException("Value already set");
this.value = value;
this.hasValue = true;
}
}
public T ValueOrDefault { get { return value; } }
public static implicit operator T(WriteOnce<T> value) { return value.Value; }
}
Then use, for example:
readonly WriteOnce<string> name = new WriteOnce<string>();
public WriteOnce<string> Name { get { return name; } }
But i could not understand why would one create readonly WriteOnce<T> if its value is private anyway and it's using a property Value that can only be set once.
Also i couldn't get why would one create a property Name that only enables the get but not the set so:
1.You can't set name's value beacuse it's readonly and
2.You can't set it's value through the property cuz it's only get.
You are confusing quite a few things here.
A readonly field means it can only be assigned inside a constructor or via a field initializer. Now WriteOnce is a reference type, so assigning only means that the value stored in name is a reference to the newly created WriteOnce<string> object.
Nothing stops you from doing whenever you want name.Value = "Hello"; because you are not changing the value of name. name = whatever outside a constructor or a field initializer on the other hand is disallowed becuase you are changing the value of the variable to a new reference, but nothing else.
Name is a readonly property, which has as the backing field name.
A read only propery doesn't let you do Name = new WriteOnce<string>(), but Name.Value = "Hello" is perfectly fine.
Anyhow, nowdays, you'd simply use a readonly autoproperty and let the compiler generate all the plumbing code (backing field):
public WriteOnce<string> Name { get }
readonly means that the object can only be created or changed in the constructor. Making it only private and not readonly would allow any method to create new name field instead. So it's true that you could set the Value only once, but if object is not read only you could completely replace it with the new one.
Creatint readonly WriteOnce means that you can set the name value anytime, not just in the constructor, but once you set the value you can't change it and you can't replace it with the new WriteOnce object.
You could re-write the class as a struct to make it a little simpler and easy to read.
struct WriteOnce<T>
{
public T Value { get; }
public WriteOnce(T input)
{
Value = input;
}
public static implicit operator WriteOnce<T>(T input)
{
return new WriteOnce<T>(input);
}
}
Usage:
WriteOnce<string> name = "test";
You can only change the value on instantiation so you will always know what it will be.
Thanks in advance guys. I am quite new to coding so please be patient. Below is a piece of code I am working on. This is the complete code below. It's as follows:
using System;
public class Product
{
private string name;
private decimal price;
public string Name
{
get
{ return name; }
set
{ name = value; }
}
public decimal Price
{
get
{ return price; }
set
{ price = value; }
}
public Product(string name, decimal price)
{
this.name = name;
this.price = price;
}
}
In the page load method, an object is instantiated and the constructor is called as follows:
private void Page_Load(object sender, EventArgs e)
{
Product saleProduct = new Product("Kitchen Garbage", 49.99M);
}
When the product is created, the constructor is initialised, with the above values. Now if you look in the constructor, you have:
this.name = name;
and
this.price = price;
After the above two lines of code are executed, the property accessors automatically assign the private variables ("name" and "price") with the intended values.
So how are the lines:
this.name = name;
and
this.price = price;
able to call the public accessors, named "Name" and "Price"?
I have only seen when a public accessor is explicitly called such as:
saleProduct.Name = "Kitchen Garbage";
I don't understand how:
this.name = name;
and
this.price = price;
can access a private variable directly. I thought the whole point of property accessors was that you had to go via the property name in order to access the private variables such as:
saleProduct.Name = "Kitchen Garbage";
Can you help and explain how
this.name = name;
and
this.price = price;
is able to access the public properties? Even the name of the properties ie "Name" and "Price" are changed to "Kitchen Garbage" and "49.99" respectively when the above two lines of code are executed.
Also, how does
this.name = name;
and
this.price = price;
know which public accessor to call?
I have searched everywhere for an explanation but no luck.
Thank you.
The private members name and price are accessible in all non-static methods within the class Product. Since the constructor for Product is part of the class, the members are accessible there as well.
Your constructor is not using the public properties Name and Price. They retrieve their values from the corresponding private members.
this.name refers to private string name;. It's private, so only code inside the class can refer to it.
The this. prefix is only required because otherwise the code would be ambiguous, since there's a parameter called name as well.
The public accessor public string Name does not have any storage of its own. It passes through to the private field name.
The code this.name = name; does not touch the property Name - it's the other way around.
When you do this.name = name;, you are setting the value of the private field called name.
Whenever you access the public property Name, you are indirectly accessing that same field (name).
Look at the definition of the property:
get { return name; }
Note that here, name refers to the same field as this.name. You could change it to this.name and there'd be no effect. It's just not required here, since there's no ambiguity.
this.name = name;
and
this.price = price;
are used in the Constructor for the Product class. Private members are accessible from the Constructor (as well as from any non-static method on the class).
Basically, when you 'new' an object, the memory structure of the object is allocated, and then the constructor is called to allow for any initialization of that object. Making the name and price member variables private just means that you can only access them from inside the class members themselves, of which the constructor is.
The public properties Name and Price, as implemented here, are just wrappers around those private name and price variables, and allow you to do other things when setting or fetching (imagine wanting to count the number of times a value is referenced: you could increment some counter in the get{} of a public property).
in your constructor you are not setting the values via the public setter, you're setting the private backing field directly.
FYI I believe it is generally considered best practice to name class level items with an Upper letter (or underscore sometimes in the case of members/backing fields?), and function level variables and parameters with a lower letter. (Don't quote me on this paragraph :P)
so to set the field via it's setter just do:
public class Foo
{
private string _bar;
public string Bar
{
set
{
this._bar = value;
}
get
{
return _bar;
}
}
public Foo(string bar)
{
this.Bar = bar;
}
}
vs.
public Foo(string bar)
{
this._bar = bar
}
The above is equivalent to what you're doing in your code. Note with your current implementation it doesn't really make a difference, since you have no additional logic in your setter. If you did however, in your implementation you would miss out on that additional logic.
note i changed the variables around a bit to make it more obvious what's being done.
to demonstrate that point consider this:
public class Foo
private string _bar;
public string Bar
{
set
{
this._bar = value + " blah blah";
}
get
{
return _bar;
}
}
public Foo()
{
this.Bar = "test";
Console.WriteLine(Bar); // outputs "test blah blah"
this._bar = "test";
Console.WriteLine(Bar); // outputs "test"
}
}
The lower cased name and price are private 'backing' variables for the public Name and Price variables. They can only be accessed from within the class itself. The reason for using this.price is because the method is taking a param called 'price' so you need to specify that you're setting the classes field and not assigning to the local variable. You'll often see this in constructors, personally I would choose to name the arguments something different than the fields in my class and then it wouldn't be necessary.
Can somebody help me understand the get & set?
Why are they needed? I can just make a public variable.
Warning: I am assuming you already know about object-oriented programming.
What are properties?
Properties are language elements that allow you to avoid the repetitive getXYZ() accessors and setXYZ() mutators techniques found in other languages, like Java.
Why do they exist?
They aim to solve the following problems:
Saying get and set in the beginning of every access or mutation of a value is annoying and distracting.
In Java, you often say:
class person
{
private int _age;
public void setAge(int value) { /*check value first, then set _age*/ }
public int getAge() { return this._age; }
}
and then consistently say:
if (person.getAge() > blah || person.getAge() < 10)
{
person.setAge(5);
}
After a while, the get and set become rather annoying.
Providing direct access to the actual variable breaks encapsulation, so that's not an option.
How are they used?
They are used just like variables. You read/write to them just like variables.
How are they created?
They are created as methods. You define a pair of methods that:
Return the current value of the property. Oftentimes, this is nothing more than something like the following:
class Person
{
private int _age; //Declare the backing field
public int Age
{
get { return this._age; }
set { ... }
}
}
Set the value of the property:
class Person
{
public int Age
{
get { ... }
set
{
if (value < 0) //'value' is what the user provided
{ throw new ArgumentOutOfRangeException(); } //Check validity
this._age = value;
}
}
}
Other notes:
Auto-implemented Properties
C# 3.0 introduced auto-implemented properties:
public int Age { get; set; }
This is equivalent to:
private int _age; //The name is auto-generated
public int Age { get { return this._age; } set { this._age = value; } }
Why does it exist?
It helps you avoiding breaking changes in client executables.
Let's say you're lazy and don't want to type the whole thing, and decide to expose a variable publicly. You then create an executable that reads from or writes to that field. Then you change your mind and decide that you in fact needed a property, so you change it to one.
What happens?
The depending executable breaks, because the code is no longer valid.
Auto-implemented properties help you avoid that, without extra redundancy in your initial code.
Indexers
Indexers extend the property syntax to let you index objects (surprise!), just like arrays.
For C++ users: This is similar to overloading operator [].
Example:
private int[] _elements;
public int this[int index] //Indexed property
{
get { return this._elements[index]; }
set
{
//Do any checks on the index and value
this._elements[index] = value;
}
}
You then use them like obj[5] = 10;, which is equivalent to calling the set method of obj's indexer.
In fact, System.Collections.Generic.List<T> is indexed:
var list = new List<int>();
list.Add(10);
list[0] = 5; //You're indexing list, as though it were an array!
Isn't that neat? :)
Anything else?
There are many more features to properties, not all of which are available in C#:
Parametrized properties, of which indexers are a special kind
Getter/setter access modifiers (in C#)
Multiple getters or setters (not in C#)
Et cetera
They are called Accessors
The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both.
The body of the get accessor resembles that of a method. It must return a value of the property type.
http://msdn.microsoft.com/en-us/library/w86s7x04.aspx
private string m_Name; // the name field
public string Name // the Name property
{
get
{
return m_Name;
}
}
The set accessor resembles a method whose return type is void. It uses an implicit parameter called value, whose type is the type of the property.
private m_Name;
public string Name {
get {
return m_Name;
}
set {
m_Name = value;
}
}
Then in the incarnation of C# 3, you can do this much easier through auto-properties
public string Name {get; set; } // read and write
public string Name {get; } // read only
public string Name { get; private set; } //read and parent write
http://msdn.microsoft.com/en-us/library/bb384054.aspx
Properties act as accessors to the internal state of an object, hiding the implementation of that state.
So, for example, you may have a first name property in a class
public class Example
{
private string firstName;
public string FirstName
{
get {return this.firstName;}
}
}
So anyone using the class doesn't need to know how first name is stored, they just know they can get a string representation of it. By adding a set you also add a mutator, something which changes an objects internal state
public class Example
{
private string firstName;
public string FirstName
{
get {return this.firstName;}
set {set this.firstName = value;}
}
}
Again you're still isolating how the first name is stored internally (encapsulation), but users can change it by passing in a string.
Simply put, get and set accessors are the functions called on a Property; that is, when you retrieve the value or when you set it. It forces a type of behavior on the way values are retrieved or set.
For example, you may want to have a mechanism to get/set passwords. Generally speaking, you'll only want to compare the hash of a password instead of storing things plaintext, so you'd have the getter variable retrieve the stored hash, and the setter would take the provided input and hash it for storage.
Here's what I mean:
public class User {
//Usery properties here, and...
private string _password;
public string Password {
get {
return _password;
}
set {
_password = SomeHashingFunction(value);
}
}
}
value is the variable provided to the setter from what has been given in the variable assignment. e.g.: someuser.Password = "blah";
Get and set are used in properties. They can each be public, protected, or private. Similar to accessor and mutator methods, they allow some computation when code tries to access/mutate the property. Of course, as long as you define one of get/set, the other is optional.
Example without properties:
private int test;
public int getTest() {
// some computation on test here, maybe?
return test;
}
private void setTest(int test) {
// some error/range checking, maybe?
this.test = test;
}
With properties:
private int test;
public int Test {
get {
// some computation on test here, maybe?
return test;
}
private set {
// some error/range checking, maybe?
test = value; // value is a keyword here
}
}
get{} and set{} are accessors that offer up the ability to easily read and write to private fields. Working with a simple example:
public class Foo()
{
//Field
private int _bar;
//Property
public int Bar
{
get { return _bar; }
set { _bar = value; }
//value is an implicit parameter to the set acccessor.
//When you perform an assignment to the property, the value you
//assign is the value in "value"
}
}
In this case, Bar is a public property that has a getter and a setter that allows access to the private field _bar that would otherwise be inaccessible beyond class Foo.
Now in a class that has an instace of Foo, you can do this:
public class IHasAFoo()
{
private Foo _myFoo = new Foo();
public void SomeMethod()
{
_myFoo.Bar = 42;
}
}
So the public accessor allows you to set the value of the private field back in Foo.
Hope that helps!
In the following code:
public class MovieRepository : IMovieRepository
{
private readonly IHtmlDownloader _downloader;
public MovieRepository(IHtmlDownloader downloader)
{
_downloader = downloader;
}
public Movie FindMovieById(string id)
{
var idUri = ...build URI...;
var html = _downloader.DownloadHtml(idUri);
return ...parse ID HTML...;
}
public Movie FindMovieByTitle(string title)
{
var titleUri = ...build URI...;
var html = _downloader.DownloadHtml(titleUri);
return ...parse title HTML...;
}
}
I asked for something to review my code, and someone suggested this approach. My question is why is the IHtmlDownloader variable readonly?
If it's private and readonly, the benefit is that you can't inadvertently change it from another part of that class after it is initialized. The readonly modifier ensures the field can only be given a value during its initialization or in its class constructor.
If something functionally should not change after initialization, it's always good practice to use available language constructs to enforce that.
On a related note, C# 9 introduces the init accessor method for properties, which indicates the property value can only be set during object construction, e.g.:
class InitExample
{
private double _seconds;
public double Seconds
{
get { return _seconds; }
init { _seconds = value; }
}
}
This ensures that the value of _downloader will not be changed after the constructor was executed. Fields marked as readonly can only be assigned a value from within the constructor(s) of a class.
A readonly field is useful for modelling data that should not change after it has been initialized. You can assign a value to a readonly field by using a initializer when you declare it or in a constructor, but thereafter you cannot change it.
This question already has answers here:
What is the { get; set; } syntax in C#?
(20 answers)
Closed 8 years ago.
I see this quiet often in C# documentation. But what does it do?
public class Car
{
public Name { get; set; }
}
It is shorthand for:
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
The compiler generates the member variable. This is called an automatic property.
In simple terms they are referred as property accessors. Their implementation can be explained as below
1.get{ return name}
The code block in the get accessor is executed when the property is Read.
2.set{name = value}
The code block in the set accessor is executed when the property is Assigned a new value.
Eg.(Assuming you are using C#)
class Person
{
private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
set
{
name = value;
}
}
}
Now when you refer to this property as below
Person p = new Person();// Instantiating the class or creating object
'p' of class 'Person'
System.Console.Write(p.Name); //The get accessor is invoked here
The get accessor is invoked to Read the value of property i.e the compiler tries to read the value of string 'name'.
2.When you Assign a value(using an argument) to the 'Name' property as below
Person p = new Person();
p.Name = "Stack" // the set accessor is invoked here
Console.Writeline(p.Name) //invokes the get accessor
Console.ReadKey(); //Holds the output until a key is pressed
The set accessor Assigns the value 'Stack" to the 'Name property i.e 'Stack' is stored in the string 'name'.
Ouput:
Stack
It's an automatic read-write property. It's a C# 3.0 addition. Something like:
public class Car {
private string name;
public string Name { get { return name; } set { name = value; } }
}
except that you can't directly access the backing field.
It's called an Auto-Implemented Property and is new to C# 3.0. It's a cleaner syntax when your access to the property doesn't need any special behavior or validation. It's similar in function to:
public class Car
{
private string _name;
public string Name
{
get { return _name; }
set {_name = value; }
}
}
So it saves a fair amount of code, but leaves you the option later to modify the accessor logic if behavior or rules need to change.
It is the equivilent of doing:
private string _Text;
public string Text
{
get { return _Text; }
set { _Text = value; }
}
Except you don't have access to the private variable while inside the class.
Auto-Implemented Properties
SUMMARY:In C# 3.0 and later, auto-implemented properties make
property-declaration more concise when
no additional logic is required in the
property accessors.