473,800 Members | 2,648 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
13 1697
On Oct 29, 9:06*am, "Michael B. Trausch" <m...@trausch.u swrote:
On Wed, 29 Oct 2008 08:39:14 -0700 (PDT)

raylopez99 <raylope...@yah oo.comwrote:
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.

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 "convention al" in C# or something you like to
do?

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

[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.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
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
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*****@commun ity.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.co m>
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
12297
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
7699
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
1903
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
1728
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
2735
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
3552
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
9690
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
9550
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10501
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...
1
10250
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
10032
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
9085
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
5469
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5603
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2944
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.