hello,
I am very new to C# and I came across "property" in C#.
I am just abit confused about the logic behind having "accessors" in "property", I mean aren't accessors just "methods"
hello,
I am very new to C# and I came across "property" in C#.
I am just abit confused about the logic behind having "accessors" in "property", I mean aren't accessors just "methods"
C# novice
Juliano Nunes
no - accessors are properties, you get and set a private property and can control how the callers can access the property. A Method is a function that does a particular job with optional parameters to be given to it and return types
private string theName = "Bob";
public string TheName
{
get { return this.theName; }
set { this.theName = value; }
}
this allows the callers of other classes to get or set the variable "theName" via the property "TheName". You can control how the callers can access the property, either they can get the property name only, or set only, or get and set the variable name through the property
having a property is generally best practice and good design to some extent I believe otherwise if you just declare the private variable public:
public string theName = "bob";
then it means anyone can get or set that property but you may not want that, you may want to control how you can set or get that property/variable
LpAngelRob
goh6613
Judah
mig16
Properties in C# are an example of what is commonly caleld "syntactical sugar".
Internally, there is very little difference between the property code the ahmedilyas demostrated and the following:
private string theName = "Bob";
public string getTheName()
{
return this.theName;
}
public void setTheName(string value)
{
this.theName = value;
}
The IL code generated would be virtually identical.
But the writing code that look like this:
obj.TheName = obj.TheName.ToUpper();
is most "palatable" (and readable) than code like this:
obj.setTheName(obj.getTheName().ToUpper());