What is a property?

P

Peter Kirk

Hi there,

can someone tell me what exactly a "property" is in a C# class? As far as I
can see it is "two methods" - ie a getter and a setter for an instance
variable.

What is the difference between these:

public string InstanceStringVariable()
{
get { return _instanceStringVariable; }
set { _instanceStringVariable = value; }
}

and

public string getInstanceStringVariable
{
return _instanceStringVariable;
}

public void setInstanceStringVariable(string stringVariable)
{
_instanceStringVariable = stringVariable;
}

Thanks,
Peter
 
B

Bob Powell [MVP]

You are exactly correct. Properties exist so that the rules of encapsulation
within a class can be obeyed. It is very bad practice to expose data as a
public field because any external class can alter that data without the
knowledge of the class. In the case of a data member that assumes say, a
range of valid values, this can be disastrous because there is no value
checking before the value is changed.

A property is indeed a little chunk of code owned by the class to enforce
whatever rules the class needs to over the control of it's data.

Properties can also synthesize a value from some other data. For example you
may store a temperature in Kelvin but provide properties to return that data
in Fahrenheit or Centigrade doing the calculation in the getter
implementation.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
P

Peter Kirk

Bob Powell said:
You are exactly correct. Properties exist so that the rules of
encapsulation within a class can be obeyed. It is very bad practice to
expose data as a public field because any external class can alter that
data without the knowledge of the class. In the case of a data member that
assumes say, a range of valid values, this can be disastrous because there
is no value checking before the value is changed.

A property is indeed a little chunk of code owned by the class to enforce
whatever rules the class needs to over the control of it's data.

Properties can also synthesize a value from some other data. For example
you may store a temperature in Kelvin but provide properties to return
that data in Fahrenheit or Centigrade doing the calculation in the getter
implementation.

OK, thanks. What then is the actual point of properties - why not just write
a getter and a setter method? Is it just the perceived "less typing"? Why
not then go whole hog and allow something like:

public property string InstanceStringVariable;

This would then generate an instance variable, a getter, and a setter. Of
course there is no "body" to the getter and setter, but then it could just
be extended if required:

public property string InstanceStringVariable
{
get { ...; }
}


Peter
 
G

Guest

Hi Peter,

we can tell properties are smart fields (Class members) in C#. Public fields
in the class would give complete access to field from other classes. So it is
not possible to give read-only or write only access to public fields. This is
possible through properties.

Properties can give read only, write only or read right access to fields.
This also allow us to add extra business logic to fields.

class Class1
{
private string firstname;
private string lastname;
private int id;

//This property allows only to set (Write only)
public string FirstName
{
set
{
firstname = value;
}
}

//This property allows only to set (Write only)
public string LastName
{
set
{
lastname = value;
}
}

//This is auto generated so has only get (readonly)
//This property has extra logic to create id
public int ID
{
get
{
Random rd = new Random();
id = rd.Next();
return id;
}
}

//This property is readonly with extra business logic
public string Name
{
get
{
return firstname + lastname;
}
}
}

You can see properties as two methods when it has both get and set, but
Properties visible like class members to outside world. we can use properties
in the same way has public fields in the class with extra accessibility.

Regards
Prakash Prabhu K
 
P

Peter Kirk

Prakash Prabhu K said:
Hi Peter,

we can tell properties are smart fields (Class members) in C#. Public
fields
in the class would give complete access to field from other classes. So it
is
not possible to give read-only or write only access to public fields. This
is
possible through properties.

Properties can give read only, write only or read right access to
fields.
This also allow us to add extra business logic to fields.

It is also possible via getter and setter methods. What exact benefit does a
"property" give us over getter and setter methods?
 
C

Christof Nordiek

Hi Peter,
It is also possible via getter and setter methods. What exact benefit does
a "property" give us over getter and setter methods?

Simply look at this Example and decide yourselve, wich is more readable:

oldText = control.get_Text();
control.get_Text(newText);

vs.

oldText = control.Text;
constrol.Text = newText;

Christof
 
S

Søren Reinke

Peter Kirk said:
It is also possible via getter and setter methods. What exact benefit does
a "property" give us over getter and setter methods?

If it is a benefit is a matter of oppinion.

But with a Property you can write:

String name=myObject.Name;

With get/set you can write:

String name myObject.GetName();

With the property you can't see directly on the source, if it is a property
or 'just' a public variable.
 
B

Bob Powell [MVP]

A property appears to the outside world like a variable so you can write:

myIntProperty=10 instead of setMyIntProperty(10) or

class1.intprop = class2.intprop instead of
class2.SetIntProp(class1.GetIntProp())

While functionally similar the property examples are eminiently readable.

Secondly, properties play a big role in the component oriented world of
..NET. Properties have a special place in the design-time environment and are
necessary to the designtime experience.

This approach would be fine if you wanted to do nothing more than povide
fields with accessors. However, when those accessors actually need to do
something like check a value range or do a conversion the whole scheme
becomes cumbersome. Building this into any compiler would certainly muddy
the waters.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
J

Jon Skeet [C# MVP]

Peter Kirk said:
It is also possible via getter and setter methods. What exact benefit does a
"property" give us over getter and setter methods?

1) Better readability (working in both Java and C# at the moment, this
is definitely significant)
2) No need for just a convention (such as JavaBeans) to decide what
constitutes a property - it's specified in the meta-data.
 
J

Jon Shemitz

Peter said:
can someone tell me what exactly a "property" is in a C# class? As far as I
can see it is "two methods" - ie a getter and a setter for an instance
variable.

Well, "one or two methods" - you have can have a get without a set (or
a set without a get, though the semantics are pretty weird, there).
What is the difference between these:

public string InstanceStringVariable()
{
get { return _instanceStringVariable; }
set { _instanceStringVariable = value; }
}

and

public string getInstanceStringVariable
{
return _instanceStringVariable;
}

public void setInstanceStringVariable(string stringVariable)
{
_instanceStringVariable = stringVariable;
}

First, as a number of people have pointed out, a property is a lot
easier to read.

if (This.Bool)

vs

if (this.getBool())

and the like.

Second, property methods are linked. Declare a property abstract, or
virtual, or static, and both methods are abstract, or virtual, or
static. It would be hard (impossible?) to enforce this linkage with a
get/set convention.

Third, properties ease maintenance / allow optimization. A member
might be a field, because setting it has no side-effects, and you want
to allow fast read/write. As your requirements change, you can easily
change the field to a property without rewriting all the client code.
 
G

Guest

I tend to think of properties as adjectives and methods as verbs - properties
describe the object - color, name, size - whereas methods are actions -
Read(), Write(), Dispose(), Jump(), etc.

It should probably be noted that properties get turned into methods by the
compiler. So for example if you had a property:

object MyProperty
{
get { throw new Exception(); }
}

and you called .MyProperty, it would be referred to in the call stack as:

get_MyProperty(object value)
 
H

Howard Swope

Peter:

There are a million different ways to skin a cat. The fact that you have
notion of a getter and a setter (as we all do) is an indication that it
might as well be added as a language feature and fully supported.

I think also that properties are good for thinking in terms of objects. When
I envision systems, my first level of thought is objects consisting of
events, methods, and properties (EMP). Objects of this nature form
relationships with other objects to perform work and provide services.
Properties allow an object to present a public face to the system.
 
S

Steve Walker

Christof Nordiek said:
Hi Peter,


Simply look at this Example and decide yourselve, wich is more readable:

oldText = control.get_Text();
control.get_Text(newText);

vs.

oldText = control.Text;
constrol.Text = newText;

Or

position.X++;

versus

position.set_X(position.get_X()+1);
 
P

Peter Kirk

Peter Kirk said:
can someone tell me what exactly a "property" is in a C# class? As far as
I can see it is "two methods" - ie a getter and a setter for an instance
variable.

Thanks for all the helpful and informative answers.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top