This question already has answers here:
What is the difference between a field and a property?
(33 answers)
Closed 1 year ago.
So this is one of my first classes for Object-Oriented Development and my feedback for my code was that I was missing "a property" and that GetName() is a method rather than a property. I'm currently coding in c# and was wondering if anyone could explain what a property is or point me in the right direction I'd be very appreciative.
//Instance Variables
private String name;
private decimal balance;
//Variables
public AccountDetails(String name, decimal balance)
{
this.name = name;
this.balance = balance;
}
//Accessor Methods
public String GetName()
{
return this.name;
}
You could have replaced your method with property like
public string Name { get { return this.name; } }
There is basically no difference between methods and properties. Getters and setters get internally translated into standard methods such that the runtime has no idea whether some getter or setter is associated with a certain property.
However, there is an important software engineering benefit: your code tends to be easier to understand if you restrict yourself to use getters and setters with get and set semantics. I.e. do only the steps necessary to provide the respective property.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
GeeName() is a method, could be called Getter in Java. Properties in C# work a bit differently, the declaration goes like
//no direct variable declaration
public String Name1 { get; set; }
//with variable declaration and custom getter logic
//notice, that properties don't need to implement both GET and SET (but they can)
private String _name;
private int _access_counter = 0;
public String Name2
{
get
{
_access_counter++;
return _name + _access_counter;
}
}
public String Name3
{
set
{
_access_counter--;
_name = value;
}
}
Related
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between Property and Field in C# .NET 3.5+
What's the difference between using
public string Username { get; set; }
and using
public string Username;
I have always been using the first one, but wanted to understand if there is any difference between the two, and scenarios when one should prefer over the other.
public string Username { get; set; }
is a Property.
while
public string Username;
is a Public variable.
For more comparison,
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.
Other link
Properties vs. Public Variables
One thing you can do with properties that you can't do with fields is limit visibility for either setter or getter:
public string MyProperty { get; private set; }
Something I use quite a lot.
And something (more powerful) you can't do with fields is define them inside an interface. Suppose you want an interface that requires implementing classes to have a certain property:
public interface MyInterface
{
string MyProperty { get; }
}
Note that you do not need to have a setter here. It is entirely up to implementing classes to determine how they should set MyProperty.
Here is a very small example of one way you could use a string property over simply using a string.
Say you have a private variable called:
private string _name;
Now lets say you wanted to make that string read only? In other words, you can't change the value. You could use the following:
public string Name
{
get { return _name; }
}
It can allow you to control access to that value. Alternatively, you can have it so that that variable can only be write only doing the following:
public string Name
{
set { _name = value; }
}
Now if you put it together, it will allow you to set to value or simply get the value. See the following:
public string Name
{
get { return _name; }
set { _name = value; }
}
You may be wondering what the point of that is since it looks like you can do the same thing with a regular string, well of course but this controls direct access to the _name variable from outside classes that aren't derived from said class.
Now what if you wanted to control how that value is set? What if you want to do some calculation or perhaps you wanted to add a prefix or suffix to that value? You do the following:
public string Name
{
get
{
return _name;
}
set
{
if (value.ToLower() == "bilbo")
_name = "Bilbo Baggins";
}
}
Now, if you set the Name property of the class to bilbo, the value of _name will be set to Bilbo Baggins as opposed to if you set the property to Amy, the _name variable will contain simply, amy.
You can do this to guarantee that whatever value that the property is set to is automatically upper or lowercase, or perhaps you can do some validation on the value or something of that sort.
I hope this explains the uses of properties and how they can be useful without making it too complicated.
Properties provide you with more flexibility, especially in .NET. C# shows bias toward properties, so keep that in mind. However, as a general rule, use accessors/mutators when getting or setting needs "processing" or an accompanying action. Use fields for holding values. E.g.,
public class Name
{
public string First;
public string Last;
public string Full{ get { return this.First + " " + this.Last; } }
}
I learned c# recently, so when I learned to write properties, I was taught to do it like this:
public string Name { get; set; }
Auto properties are great! But now I'm trying to do something a little more complicated, so I need to write a custom pair of accessors.
private string _Name;
public string Name {
get { return _Name; }
set { _Name = value }
}
I know the compiler makes a private instance variable down in it's murky depths when one uses autos, but I'm spoiled and don't want that private variable sitting around looking pointless.
Is there a way to use custom accessors without a private variable?
Properties don't need backing variables (fields) at all. While they can be used for encapsulating simple fields you can also use them to access other data.
public Decimal GrandTotal { get { return FreightTotal + TaxTotal + LineTotal; } }
or
public string SomeStatus { get { return SomeMethodCall(); } }
If the goal is to simply encapsulate some field with a property you would need some sort of backing field if you are not using automatic properties.
The answer is No, you cannot do that.
It is because of recursion. (See line numbers 9 and 7):
Line 1 : public string Name
Line 2 : {
Line 3 : get
Line 4 : {
Line 5 : return FirstName + " " + LastName;
Line 6 : }
Line 7 : set
Line 8 : {
Line 9 : Name = value; // <-- Goes back to Line 7
Line 10 : }
Line 11 : }
No, I'm afraid not. The compiler is smart enough to make this happen for you on auto-generated properties, but with standard properties I imagine the logic behind something like that would end up getting in the way and doing more harm than good.
For example, what if I create a property like this...
public int SomeValue
{
get
{
return 0;
}
}
Would the compiler (with the feature you're looking for) create a backing private variable? Why? It doesn't need one.
Additionally, if the private value isn't created until compilation time, what are you going to reference in your code:
public string Name {
get { return _Name; }
set { _Name = value }
}
What is _Name? What if you have another value somewhere else called _Name? Then what would the compiler call the backing value for this property? What if I need two backing values? Would the compiler be smart enough for that?
public string Name
{
get
{
return string.Format("{0} {1}", _FirstName, _LastName);
}
set
{
// some parsing magic
}
}
It's been asked before, but I imagine the answer is going to continue to be "no" for the foreseeable future.
An auto-property is syntactic shorthand for simple direct member access. (And I imagine one of its driving forces was simply to try to get people to stop creating public values directly.) Properties can grow in complexity well beyond that very easily and I personally wouldn't want the compiler trying to figure out what I can easily just tell it to do.
I know this is an old question, but there is at least one other option here. I'm doing something similar to the below for my own app.
This might not exactly be for your use case, but it shows that a custom getter and setter can be used without a private instance variable. In this case, the getter and setter are shortcut or helper methods to access the Name property of the User for the Account.
We can let the value be set by doing Account.AccountUser.Name = "John Doe";, but sometimes that seems a bit clunky and it works against the idea of separation of concerns. Do we want someone using the Account class to know there's a User imbedded in it? If for some reason we don't, we now have a way to still update the User.Name even if we make AccountUser private.
In this case, AccountUser is public, but it doesn't have to be. When it's private, a Json or XML conversion utility (such as Newtonsoft) should ignore the AccountUser and show just the Name as if the Account were a flat model, instead of having multiple levels.
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Account
{
public int Id { get; set; }
public User AccountUser { get; set; }
public string Name
{
get
{
return AccountUser.Name;
}
set
{
AccountUser.Name = value;
}
}
}
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!
I've created this "question" as a community-wiki, because there is no right or wrong answer. I only would like to know how the community feels about this specific issue.
When you have a class with instance variables, and you also created properties that are simply getters and setters for these instance variables, should you use the properties inside your own class, or should you always use the instance variable?
Having auto-properties in C# 3.0 made this an even harder decision.
Using properties:
public class MyClass
{
private string _name;
// could be an auto-property of-course
public string Name { get { return _name; } set { _name = value; } }
public void Action()
{
string localVar = Name;
// ...
Name = "someValue";
// ...
}
}
Using instance variables:
public class MyClass
{
private string _name;
public string Name { get { return _name; } set { _name = value; } }
public void Action()
{
string localVar = _name;
// ...
_name = "someValue";
// ...
}
}
(for those who hate member prefixes, I apologize)
Personally, I always use the latter (instance variables), because I feel that properties should only be used by other classes, not yourself. That's why I mostly stay away from auto-properties as well.
Of course, things change when the property setter (or getter) does a little more than just wrapping the instance variable.
Are there compelling reasons to pick one or the other?
I always use instance variables as well. The reason is because properties might be doing stuff like validating arguments (like in a setter) for not null or not empty. If you're using the variable inside your class code, there's no need to go through the extra overhead of those checks (assuming you know the variable value is valid). The properties could be doing other things as well (logging, for example), that are important for the public API, but not for internal usage, so again, it's better to avoid the overhead and just use the instance variable in my opinion.
I think it becomes more difficult to change the internal implementation if the code uses its own public interface.
Difficult to explain but consider these expressions:
mTotalPrice = mPrice * mQuantity;
mTotalPrice = Price * Quantity;
What to do in the second expression if I need to change the internals to express all prices in € instead of $ (without affecting the public interface which still uses $)?
One solution is to make the expression more complex by adding the opposite of the change in the property.
mTotalPrice = Price / Rate * Quantity
The other solution is to start to use the private field instead.
mTotalPrice = mPrice * Quantity
In the end you get a mix of private and public use. The only way to get consistent use is to always use the private field.
I don't like prefixing members either, but actually I find I can write something like this accidently and not spot it until run time. Which kinda tempts me to avoid using properties where they're not necessary... but I still do, currently!
Public String MyString
{
{ get { return this.MyString; } } //<== Stack Overflow
{ set { this.myString = value; } }
}
private String myString;
I think that there is no difference between these two approaches.
Auto-implemented properties is just a quick way to access private members which are created any way.
Example from MSDN:
class Customer
{
// Auto-Impl Properties for trivial get and set
public double TotalPurchases { get; set; }
public string Name { get; set; }
public int CustomerID { get; set; }
// Constructor
public Customer(double purchases, string name, int ID)
{
TotalPurchases = purchases;
Name = name;
CustomerID = ID;
}
// Methods
public string GetContactInfo() {return "ContactInfo";}
public string GetTransactionHistory() {return "History";}
// .. Additional methods, events, etc.
}
99% of the time I use the property rather then the instance variable. In the past, I've worked with a lot of code that used the instance variable and when there was a bug associated with that variable, I had to put a breakpoint on every line of code that referenced it.
I decided to use properties instead, either public or private, to wrap around the instance variable. Doing this means that I only have to put a breakpoint in the getter/setter of the property if I need to debug an issue with the instance variable, rather then having (potentially) a lot of breakpoints scattered all over the code.