473,472 Members | 1,856 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Automatically Implemented Properties--why bother?

I'm going through a book by Jon Skeet that mentions automatically
implemented properties, but it doesn't do a good job of explaining why
you should bother and what is going on behind the scenes.

For example:

string name;
public string Name
{
get {return name;}
set {name=value;}
}

is the traditional way.

the "new" way (C#3):

public string Name {get; set;}

but what is not clear--is there a variable that's private named 'name'
in the 'new' way? Hidden behind the scenes?

Second, why bother? how does this encapsulate anything? It seems you
can just make Name public and be done with it.

Any help appreciated

RL
Oct 28 '08 #1
13 1664
public class Impl
{
public string Eggs { get; set; }
}

Is the same as

public class Impl
{
// Fields
[CompilerGenerated]
private string <Eggs>k__BackingField;

// Properties
public string Eggs
{
[CompilerGenerated]
get
{
return this.<Eggs>k__BackingField;
}
[CompilerGenerated]
set
{
this.<Eggs>k__BackingField = value;
}
}
}

As for the point. If you make Name public it is a field not a property, and
as far as I know you can only bind to properties. In addition you can do
this

public string Eggs { get; private set; }

Which you can't with a Field.

--
Pete
====
http://mrpmorris.blogspot.com
http://www.capableobjects.com

Oct 28 '08 #2


"raylopez99" <ra********@yahoo.comwrote in message
news:86**********************************@m74g2000 hsh.googlegroups.com...
I'm going through a book by Jon Skeet that mentions automatically
implemented properties, but it doesn't do a good job of explaining why
you should bother and what is going on behind the scenes.

For example:

string name;
public string Name
{
get {return name;}
set {name=value;}
}

is the traditional way.

the "new" way (C#3):

public string Name {get; set;}

but what is not clear--is there a variable that's private named 'name'
in the 'new' way? Hidden behind the scenes?
Yes a private field is created to hold the value but its not available
lexically in code so you can only access it via the Name property. This is
a good thing. Apart from reducing the number of lines needed it eliminates
the tendancy to access the value via the private field from code inside the
class. If at some point in the future it was determined the value needn't
be held but can be calculated one needs only to modify the property code,
there would be no need to find all potential uses of the private field.

Second, why bother? how does this encapsulate anything? It seems you
can just make Name public and be done with it.
If you are refering to making a Name field public that would be worse. If
again at a later time you decided you needed to change the Name to a
property for internal reasons you are forced into changing the classes
public interface. With the Name being implemented as a Property to start
with, if such a change is needed it is not apparent to external consumers of
your class.

--
Anthony Jones - MVP ASP/ASP.NET

Oct 28 '08 #3
raylopez99 <ra********@yahoo.comwrote:
I'm going through a book by Jon Skeet that mentions automatically
implemented properties, but it doesn't do a good job of explaining why
you should bother and what is going on behind the scenes.

For example:

string name;
public string Name
{
get {return name;}
set {name=value;}
}

is the traditional way.

the "new" way (C#3):

public string Name {get; set;}

but what is not clear--is there a variable that's private named 'name'
in the 'new' way? Hidden behind the scenes?
Yes - as stated in the middle paragraph of P209:

"The compiler generates a private variable that can't be referenced
directly in the source, and fills in the property getter and setter
with the simple code to read and write that variable."
Second, why bother? how does this encapsulate anything? It seems you
can just make Name public and be done with it.
See http://csharpindepth.com/Articles/Ch...iesMatter.aspx

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Oct 28 '08 #4
Jon

Off topic but didn’t you used to have a video somewhere where you
explained automatic properties?

I just remember you typing at 500 miles per hour in that video.

On Oct 28, 2:49*pm, Jon Skeet [C# MVP] <sk...@pobox.comwrote:
raylopez99 <raylope...@yahoo.comwrote:
I'm going through a book by Jon Skeet that mentions automatically
implemented properties, but it doesn't do a good job of explaining why
you should bother and what is going on behind the scenes.
For example:
string name;
public string Name
{
get {return name;}
set {name=value;}
}
is the traditional way.
the "new" way (C#3):
public string Name {get; set;}
but what is not clear--is there a variable that's private named 'name'
in the 'new' way? *Hidden behind the scenes?

Yes - as stated in the middle paragraph of P209:

"The compiler generates a private variable that can't be referenced
directly in the source, and fills in the property getter and setter
with the simple code to read and write that variable."
Second, why bother? *how does this encapsulate anything? *It seems you
can just make Name public and be done with it.

Seehttp://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx

--
Jon Skeet - <sk...@pobox.com>
Web site:http://www.pobox.com/~skeet*
Blog:http://www.msmvps.com/jon.skeet
C# in Depth:http://csharpindepth.com- Hide quoted text -

- Show quoted text -
Oct 28 '08 #5
<qg**********@mailinator.comwrote:
Off topic but didn=3Ft you used to have a video somewhere where you
explained automatic properties?

I just remember you typing at 500 miles per hour in that video.
Well remembered: http://csharpindepth.com/Screencasts.aspx

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Oct 29 '08 #6
On Oct 28, 6:59*am, "Peter Morris" <mrpmorri...@SPAMgmail.comwrote:
public class Impl
{
* * public string Eggs { get; set; }

}

Is the same as

public class Impl
{
* * // Fields
* * [CompilerGenerated]
* * private string <Eggs>k__BackingField;

* * // Properties
* * public string Eggs
* * {
* * * * [CompilerGenerated]
* * * * get
* * * * {
* * * * * * return this.<Eggs>k__BackingField;
* * * * }
* * * * [CompilerGenerated]
* * * * set
* * * * {
* * * * * * this.<Eggs>k__BackingField = value;
* * * * }
* * }

}

As for the point. *If you make Name public it is a field not a property, and
as far as I know you can only bind to properties. *In addition you can do
this

public string Eggs { get; private set; }

Which you can't with a Field.

--
Pete
====http://mrpmorris.blogspot.comhttp://www.capableobjects.com
Well I don't like this new convention.

Based on the way I code, I would like to know what the
"k__BackingField" compiler generated name is. I don't want it to be
hidden.

Put another way, in this 'traditional' way of coding:

string name;
public string Name
{
get {return name;}
set {name=value;}
}

I would refer to the variable "name" (smaller case, note) throughout
my class, internally. But, with the "new" C#3 convention, I have no
way of knowing what this variable is, since it's hidden now and named
by the compiler.

So I will stick to the older, 'traditional' way of using properties.

RL
Oct 29 '08 #7


"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP*********************@msnews.microsoft.com. ..
<qg**********@mailinator.comwrote:
>Off topic but didn=3Ft you used to have a video somewhere where you
explained automatic properties?

I just remember you typing at 500 miles per hour in that video.

Well remembered: http://csharpindepth.com/Screencasts.aspx

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
The page for the URL you posted works, but the link on that page to
"Automatic properties" takes me to a broken page :D

Uh-oh!

Mythran
Oct 29 '08 #8
Mythran <My*****@community.nospamwrote:
The page for the URL you posted works, but the link on that page to
"Automatic properties" takes me to a broken page :D

Uh-oh!
Hmm... I'll ask Dmitry...

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Oct 29 '08 #9
raylopez99 <ra********@yahoo.comwrote:

<snip>
Well I don't like this new convention.

Based on the way I code, I would like to know what the
"k__BackingField" compiler generated name is. I don't want it to be
hidden.
Why not? The whole point of automatic properties are that they're for
trivial ones, where referring to the field and referring to the
property are (at least for the time being) equivalent.
Put another way, in this 'traditional' way of coding:

string name;
public string Name
{
get {return name;}
set {name=value;}
}

I would refer to the variable "name" (smaller case, note) throughout
my class, internally. But, with the "new" C#3 convention, I have no
way of knowing what this variable is, since it's hidden now and named
by the compiler.

So I will stick to the older, 'traditional' way of using properties.
I still don't see why.

Personally I'd like a form of property which prevented the rest of the
class from seeing the variable but still allowed the property code
itself to do stuff. That way I could make sure that my class was using
the property throughout, which means I can't accidentally bypass any
validation, logging etc.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Oct 29 '08 #10
On Oct 29, 9:06*am, "Michael B. Trausch" <m...@trausch.uswrote:
On Wed, 29 Oct 2008 08:39:14 -0700 (PDT)

raylopez99 <raylope...@yahoo.comwrote:
Well I don't like this new convention.
Based on the way I code, I would like to know what the
"k__BackingField" compiler generated name is. *I don't want it to be
hidden.

Part of the reason for hiding it is that the Property get/set methods
are the only ones that should be playing with the private variable,
unless there is a *really* good reason to have other things messing
with it. *Say that you have a class that represents a text console
window, and you want to set the width, and you have a private variable
(this.mWidth) and a public property (this.Width). *Even within your
class, you'll use "this.Width", letting your properties abstract the
variable and handle it in terms of checking that, say, mWidth is never
going to be >= 200. *Do you understand what I'm trying to convey?
Yes, I see I think. You're saying you can incorporate "error
checking" such as range checking in your "set" portion of your
property. I do that all the time. But I do that so that when you use
the public portion (the Name in my example, not the 'name'), you can
get error checking. I'm still free to use .name internally to the
class as I see fit.
>
Put another way, in this 'traditional' way of coding:
string name;
public string Name
{
get {return name;}
set {name=value;}
}
I would refer to the variable "name" (smaller case, note) throughout
my class, internally. *But, with the "new" C#3 convention, I have no
way of knowing what this variable is, since it's hidden now and named
by the compiler.
So I will stick to the older, 'traditional' way of using properties.

Correct. *Again, that's the whole point: you don't need to know the
name of the private variable that backs the public property. *It's
really a good idea to use automatic properties, if you don't have any
reason to have a backing variable that you have access to.
"If you don't have any reason"...well, that's my point--I do have a
reason. I use Properties (perhaps improperly) as a gateway or
interface with the outside world, outside my class, only. Not
internally.

>*Think about
that carefully; _why_ does your private variable need to be accessed by
your class? *It'd probably be better to use the property as a gateway
to the variable whether you're using the variable internally or
externally.
Well that's news to me...the part about "internally". Externally,
like I said, I already use properties as a gateway.

Is what you posted above "conventional" in C# or something you like to
do?

RL
Oct 29 '08 #11
On Oct 29, 4:12*pm, "Michael B. Trausch" <m...@trausch.uswrote:

[Some useful pointers that I kind of understood on when to use
automatically generated properties and when not to]

Thanks for that reply. Indeed, as you alluded to, properties don't
always behave like ordinary variables, and I often get compiler error
messages saying "you can't do that with properties". But I would like
to see a complete example of when you can/should use an automatically
generated property (that uses a hidden private variable); so if you
have an example please shoot it my way. Until I see one, I will
continue using properties as a "public gateway" to the world, in lieu
of just making the private variable they refer to public (which I also
sometimes do, but is more dangerous).

Happy coding,

RL

Oct 30 '08 #12


"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP*********************@msnews.microsoft.com. ..
Mythran <My*****@community.nospamwrote:
>The page for the URL you posted works, but the link on that page to
"Automatic properties" takes me to a broken page :D

Uh-oh!

Hmm... I'll ask Dmitry...

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
No problemo Jon....I was just curious to watch your typing speed....what is
your typing speed, if you don't mind me delving into your "personal" life :D

Mythran
Oct 30 '08 #13
Mythran <My*****@community.nospamwrote:
No problemo Jon....I was just curious to watch your typing speed....what is
your typing speed, if you don't mind me delving into your "personal" life :D
Wouldn't like to say, other than it entirely depends on what I'm
typing. Reasonably quick in general though.

The screencast involved recording things several times though, until I
got the timing right without making too many typos...

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Oct 31 '08 #14

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

Similar topics

21
by: Sriek | last post by:
hi, i come from a c++ background. i ws happy to find myself on quite familiar grounds with Python. But, what surprised me was the fact that the __init__(), which is said to be the equivlent of the...
6
by: Boaz Ben-Porat | last post by:
I heard somewhere that the DataGrid class is implemented as a XML graph in memory. Is this true ? TIA Boaz Ben-Porat DataPharm a/s Denmark
24
by: Jazper | last post by:
hi i have this problem. i made a class deverted by CRootItem with implementation of IDisposable-Interface. i made a test-funktion to test my Dispose-Method.... but when set a breakpoint in my...
21
by: Simon Verona | last post by:
Hope somebody can help! I want to automatically be able to add code to the initialize routine on a Windows form when I add a custom control that I've written to a form. Specifically, I'm trying...
7
by: chellappa | last post by:
hi this program return value automatically ... how it is possible ..i am not return any value... but i return correct values i am using Linux -gcc complier please tell me what is this main() {...
12
by: cody | last post by:
Why can I overload operator== and operator!= separately having different implementations and additionally I can override equals() also having a different implementation. Why not forbid...
2
by: DanielLinn | last post by:
I'm getting an error in IE 6.0.2800 that says "Error: Not implemented." when I try to get a parent. Does it whether or not 'compatibility mode' is on. Here's my code: <!DOCTYPE html PUBLIC...
15
by: Gustaf | last post by:
Using VS 2005. I got an 'IpForm' class and an 'IpFormCollection' class, containing IpForm objects. To iterate through IpFrom objects with foreach, the class is implemented as such: public class...
13
by: Mary | last post by:
I'll pulling my hair out on this one and would be so appreciative of any help. I am creating a data entry form to enter results of a student survey. There are 40 questions on the survey. The...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...
1
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
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...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.