473,788 Members | 2,715 Online
Bytes | Software Development & Data Engineering Community
+ 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 1695
public class Impl
{
public string Eggs { get; set; }
}

Is the same as

public class Impl
{
// Fields
[CompilerGenerat ed]
private string <Eggs>k__Backin gField;

// Properties
public string Eggs
{
[CompilerGenerat ed]
get
{
return this.<Eggs>k__B ackingField;
}
[CompilerGenerat ed]
set
{
this.<Eggs>k__B ackingField = 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********@yah oo.comwrote in message
news:86******** *************** ***********@m74 g2000hsh.google groups.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********@yah oo.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.co m>
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.co mwrote:
raylopez99 <raylope...@yah oo.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.c om/Articles/Chapter8/PropertiesMatte r.aspx

--
Jon Skeet - <sk...@pobox.co m>
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**********@m ailinator.comwr ote:
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.co m>
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...@SP AMgmail.comwrot e:
public class Impl
{
* * public string Eggs { get; set; }

}

Is the same as

public class Impl
{
* * // Fields
* * [CompilerGenerat ed]
* * private string <Eggs>k__Backin gField;

* * // Properties
* * public string Eggs
* * {
* * * * [CompilerGenerat ed]
* * * * get
* * * * {
* * * * * * return this.<Eggs>k__B ackingField;
* * * * }
* * * * [CompilerGenerat ed]
* * * * set
* * * * {
* * * * * * this.<Eggs>k__B ackingField = 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.blogs pot.comhttp://www.capableobje cts.com
Well I don't like this new convention.

Based on the way I code, I would like to know what the
"k__BackingFiel d" 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.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
<qg**********@m ailinator.comwr ote:
>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.co m>
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*****@commun ity.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.co m>
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********@yah oo.comwrote:

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

Based on the way I code, I would like to know what the
"k__BackingFiel d" 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.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Oct 29 '08 #10

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

Similar topics

21
12293
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 constructor in c++, is not automatically called. I'm sure there must be ample reason for this. I would like to know why this is so? This is my view is more burden on the programmer. Similarly, why do we have to explicitly use the 'self' keyword...
6
2671
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
7696
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 Dispose-Method and call the GC nothing happend!!! my Disposemethod has never been called!! so the GC dont call my Dispose-Method although I implemented IDisposable? what am i doing wrong?
21
1902
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 to data bind to a normal class. So I've extended the standard text box to include a field for object name and property name. I want to be able to add a line such as : controlname.DataBindings.Add("Text", objectName, "myPropertyName") I've...
7
1726
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() { int a,b,c,sum; printf("ENTER ANY THREE NUMBERS :\n"); scanf("%d%d%d",&a,&b,&c);
12
2211
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 overloading of == and != but instead translate each call of objA==objB automatically in System.Object.Equals(objA, objB). This would remove inconsistencies like myString1==myString2
2
4451
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 "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>
15
2734
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 IpFormCollection : IEnumerable<IpForm> { ArrayList forms = new ArrayList(); public IEnumerator<IpFormGetEnumerator() {
13
3551
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 first 7 have to do with respondent information like grade, class and age. I have those in a table with a PK of RespondentId, which is autonumbered. Questions 8-40 all have the same format. For these questions I have a table set up with the...
0
9656
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10366
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9967
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4070
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
2
3674
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.