Automatically Implemented Properties--why bother?

  • Thread starter Thread starter raylopez99
  • Start date Start date
R

raylopez99

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
 
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.
 
raylopez99 said:
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.
 
raylopez99 said:
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/Chapter8/PropertiesMatter.aspx
 
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.
 
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?

Such questions are often best dealt with by looking to the
authoritative source: the compiler itself. .NET makes this pretty easy.

Take the example C# source code:

======================================
using System;

public class ExampleProperties {
public static void Main() {
new ExampleProperties();
}

internal string Name {
get;
set;
}

public ExampleProperties() {
Name = "foo";

Console.WriteLine(Name);
}
}
======================================

Compile this to an assembly using the C# compiler, and take a look at
the disassembly of the IL; you can learn a lot about how the compiler
does things that way.

The output shows that there is a private string "<Name>k__BackingField"
contained within the class. There is also a set_Name(string) method
and a get_Name(string) method which modify the '<Name>k__BackingField".

If you modify it so that you have a private variable mName, and fill-in
the property to get and set it, the effect is the same, but you've
explicitly set the name of the property's internal variable.
Second, why bother? how does this encapsulate anything? It seems you
can just make Name public and be done with it.

Properties are part of the public interface for a class. Using a
empty, default property such as above makes the value available to
consumers of the class, while leaving the implementation details free
to you to figure out. Properties are, after all, nothing but veiled
method calls.

Say that you want to make it read-only? Remove the "set;".
Write-only? Do the inverse. Want to add some verification logic to
the setter? Okay, go ahead---create the private variable, fill in the
get using default behavior, and fill in the logic for the set method.
Want to add something extra to the returned value later on? Modify the
"get" routine to do it for you. Want to make it something dynamic
altogether? Use the default for a stub, and fill in the logic later.
There are many, many uses.

--- Mike
 
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.

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
 
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?
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. 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.

--- Mike
 
Mythran said:
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...
 
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.
 
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.


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
 
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.

Indeed you are. The point is that if you gateway everything through
the property, you have clear code that is easy to understand at a
glance, and is guaranteed to be consistent because the modification of
the private backing variable is *always* done by the exact same code.

If you've the variable declared as a private variable and you write
properties for use by external interfaces and you modify the variable
internally without using the properties, that is certainly your right.
All that I am saying is that this has the decent chance (particularly
in a multi-programmer environment) to be badly used since you are then
able to bypass the properties and introduce potentially inconsistent
behavior. Like all practices, however, whether or not to use them is
situationally dependent. There is always the exception to a given rule
or practice.
"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.

Okay. I said that only because I haven't seen any reason thus far in
this thread to do it any other way. Simple preference might be reason
enough for you. It's not for me. It's always easier to have access to
the variable directly instead of having a property in the way. But,
the moment you start needing to use the property for logic, you have to
refactor the code. If you factor it properly in the beginning, you
avoid having to refactor for that reason later, and the code speaks for
itself (because it says "It is impossible for me to be changed without
going through this property, so you can be assured that I won't be
modified elsewhere in the class," which also can help you to understand
your code more quickly 6 months later, as well as someone new to learn
it the first time around looking at it).

There are times where using a private variable directly is something
that makes a class easier to implement. There are also ways around
that, you can use the property setter to store a second copy of the
value in a private variable that otherwise has no relation to the
property. You can also use methods to format values going back out to
the application. One of the great things about programming is that
there are multiple avenues to go down and one just has to determine
what is the best one for every situation.

Think about an example where you're storing a social security number in
a database. Let's say that you need to write a class that represents a
person, and that class needs to track the person's first name, middle
name, last name, and social security number. Usually, when you pull
the SSN out of the class, you're going to want it formatted in the
usual XXX-XX-XXXX format, not as a series of 9 digits. When you set
the value, you would accept either/or, when you get it out, you'd
output just the one that you'd use for formatting purposes. (This is,
itself, an example of accepting flexible output and strict about
output, which is a basic maxim of writing robust software.)

So, the class stores the social security number as nine characters.
Internally to .NET this means that its using 18 bytes, though when you
send it to a properly configured database system, it'll be back at 9.
(Internally, .NET encodes strings in UTF-16, like Win32 and Java do.)
A database system will usually be designed to use UTF-8 because it
saves a great deal of space any time you have a non-minority of Roman
characters stored within it (that is, characters which fit in the 7-bit
ASCII encoding). You could send the SSN to the database server as 11
characters, or as 9 characters. Now, specifically for SSNs you could
just filter out all characters that do not fit the character pattern
'[0-9]', and that'd work. You could also have a property that is
backed by a private variable that is accessible and just read that
variable. Or, you could have a private variable that holds a copy of
the value being held in the *real* backing store for the property and
just use that when you're writing to the database.

In *this* case, I would probably read the property, strip the
punctuation, and send the sanitized output of the stripping operation
to the database. I wouldn't use an accessible private variable at
all. But if you have lots of properties that need some sort of
processing before they're shunted to a database, it can be easier to
have the setter for the property put the information in another private
variable that is accessible, or even a nested structure that belongs to
the class that is used to hold such things. It all depends on what
you're doing and what justification there is for doing it that way.

Another time that not using automatically implemented properties is
worthwhile is when you're implementing the property in order to get/set
some dynamic value that is calculated, of course; not only will you be
unable to use an automatically implemented property for that purpose,
but there will be no backing store that is directly linked to the
property, so it wouldn't make any sense.
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?

Above? I assume you mean the post I made which created another
subthread; not sure how Google Groups views it, I read Usenet with a
threaded newsreader.

The example I posted was just that, an example. In the software that I
write in C#, I largely use that style of property because it is
efficient and because it makes it impossible for some method in the
class to go change the variable backing the property, making life
easier since it proactively eliminates many subtle bugs simply by
making it impossible for them to exist in the first place.

Again, to each their own. Though, to clarify, when I say that it's
best to avoid doing something unless there is a reason for doing so, I
really mean "it's best to avoid doing it unless there is a compelling
logical reason for doing so." I wasn't talking about preference or
some decision arrived at a long time ago that has never since been
questioned. I do think that it's best that we all question our
practices as programmers every now and again... The realm of
programming has very little room for dogma.

I am not saying that using automatically implemented properties is
something that should be done exclusively, rather that automatically
implemented properties make life easier generally because they hide the
private variable from the programming, and that reduces the probability
that something bad could happen since the setter exclusively controls
the private variable (unless, that is, you have a part of the class
implemented in IL Assembly, which I don't think will give you such
protection, but that's another can of worms altogether).

HTH,
Mike
 
[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
 
Mythran said:
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...
 
Back
Top