473,569 Members | 2,756 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What is a property?

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 InstanceStringV ariable()
{
get { return _instanceString Variable; }
set { _instanceString Variable = value; }
}

and

public string getInstanceStri ngVariable
{
return _instanceString Variable;
}

public void setInstanceStri ngVariable(stri ng stringVariable)
{
_instanceString Variable = stringVariable;
}

Thanks,
Peter
Nov 17 '05 #1
13 1790
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.

"Peter Kirk" <pk@alpha-solutions.dk> wrote in message
news:uy******** ******@TK2MSFTN GP14.phx.gbl...
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 InstanceStringV ariable()
{
get { return _instanceString Variable; }
set { _instanceString Variable = value; }
}

and

public string getInstanceStri ngVariable
{
return _instanceString Variable;
}

public void setInstanceStri ngVariable(stri ng stringVariable)
{
_instanceString Variable = stringVariable;
}

Thanks,
Peter

Nov 17 '05 #2
"Bob Powell [MVP]" <bob@_spamkille r_bobpowell.net > skrev i en meddelelse
news:uA******** ******@TK2MSFTN GP14.phx.gbl...
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 InstanceStringV ariable;

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 InstanceStringV ariable
{
get { ...; }
}
Peter
Nov 17 '05 #3
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


"Peter Kirk" wrote:
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 InstanceStringV ariable()
{
get { return _instanceString Variable; }
set { _instanceString Variable = value; }
}

and

public string getInstanceStri ngVariable
{
return _instanceString Variable;
}

public void setInstanceStri ngVariable(stri ng stringVariable)
{
_instanceString Variable = stringVariable;
}

Thanks,
Peter

Nov 17 '05 #4
"Prakash Prabhu K" <Pr************ @discussions.mi crosoft.com> skrev i en
meddelelse news:39******** *************** ***********@mic rosoft.com...
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?

Nov 17 '05 #5
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_Tex t();
control.get_Tex t(newText);

vs.

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

Christof

"Peter Kirk" <pk@alpha-solutions.dk> schrieb im Newsbeitrag
news:u1******** ******@TK2MSFTN GP12.phx.gbl... "Prakash Prabhu K" <Pr************ @discussions.mi crosoft.com> skrev i en
meddelelse news:39******** *************** ***********@mic rosoft.com...
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?

Nov 17 '05 #6

"Peter Kirk" <pk@alpha-solutions.dk> wrote in message
news:u1******** ******@TK2MSFTN GP12.phx.gbl...
"Prakash Prabhu K" <Pr************ @discussions.mi crosoft.com> skrev i en
meddelelse news:39******** *************** ***********@mic rosoft.com...
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?


If it is a benefit is a matter of oppinion.

But with a Property you can write:

String name=myObject.N ame;

With get/set you can write:

String name myObject.GetNam e();

With the property you can't see directly on the source, if it is a property
or 'just' a public variable.
--
Best regards Søren Reinke
www.Xray-Mag.com/ - Your free diving magazin on the net. Download it in PDF
Cover story: CAYMAN ISLANDS main features by John Collins and Alex Mustard.
Leigh Cunningham: Gear Configuration
Nov 17 '05 #7
A property appears to the outside world like a variable so you can write:

myIntProperty=1 0 instead of setMyIntPropert y(10) or

class1.intprop = class2.intprop instead of
class2.SetIntPr op(class1.GetIn tProp())

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.
Why not then go whole hog and allow something like:
public property string InstanceStringV ariable;

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.

"Peter Kirk" <pk@alpha-solutions.dk> wrote in message
news:uq******** ******@TK2MSFTN GP09.phx.gbl... "Bob Powell [MVP]" <bob@_spamkille r_bobpowell.net > skrev i en meddelelse
news:uA******** ******@TK2MSFTN GP14.phx.gbl...
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 InstanceStringV ariable;

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 InstanceStringV ariable
{
get { ...; }
}
Peter

Nov 17 '05 #8
Peter Kirk <pk@alpha-solutions.dk> wrote:
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.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #9
Peter Kirk wrote:
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 InstanceStringV ariable()
{
get { return _instanceString Variable; }
set { _instanceString Variable = value; }
}

and

public string getInstanceStri ngVariable
{
return _instanceString Variable;
}

public void setInstanceStri ngVariable(stri ng stringVariable)
{
_instanceString Variable = 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.

--

www.midnightbeach.com
Nov 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
11240
by: Mark Kamoski | last post by:
Hi Everyone-- Please help. What is the difference between a Field and a Property? Here is the context. In the VS.NET 2002 documentation, in the "String Members" section, we have the following...
9
1064
by: Mark Jones | last post by:
This rather cryptic title is actually a .net oop noob question. Example: My customer object has a public property called .name which is a string. I would like to be able to reference mycust.name.length which would return the string length of the value of name. I can't nest property/subs so how do I accomplish this? Another example...
11
1446
by: ucasesoftware | last post by:
If i have this property Dim m_name as string Property name() as string Get return m_name end Get Set (byval Value as string) m_name = Value
14
2366
by: Rich | last post by:
Yes, I need to store some values in an array type collection object that can hold 3 or more parameters per index. I have looked at the collection object, hashtable object and would prefer not to hassel with a multi-dimensional array. Is there such an object in VB.Net? Dim obj As someCollectionObj obj.Add("parmA1", "parmA2", "parmA3")...
5
2379
by: Cylix | last post by:
this.menus = { root: new Array };
6
2853
by: seb | last post by:
Hi, I am using pygtk for the first times. I am wondering what would be the best "pattern" to interface pygtk with a thread. The thread is collecting informations (over the network for example) or is doing some long calculations.
10
2093
by: Franky | last post by:
I think I misread a post and understood that if I do: System.Windows.Forms.Cursor.Current = Cursors.WaitCursor there is no need to reset the cursor to Default. So I made all the reset statements into comments (placed an ' in front)
5
2226
by: Daz | last post by:
Hi everyone. My query is very straight forward (I think). What's the difference between someFunc.blah = function(){ ; } and
6
4016
by: JonathanOrlev | last post by:
Hello everyone, I have a newbe question: In Access (2003) VBA, what is the difference between a Module and a Class Module in the VBA development environment? If I remember correctly, new types of objects (classes) can only be defined in Class modules.
1
1974
by: developing | last post by:
Hello, This time I want to filter the 'browse for file' API so that certain drives/folders cant be accessed. Not sure how to go about this...here is the module I am currently using to browse for a file then return the file link... any ideas/help are highly appreciated. Option Explicit Option Compare Database
0
7697
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7612
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7924
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8120
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7672
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6283
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5512
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3640
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.