Automatically Implemented Properties--why bother?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • raylopez99

    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
  • Peter Morris

    #2
    Re: Automatically Implemented Properties--why bother?

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



    Comment

    • Anthony Jones

      #3
      Re: Automatically Implemented Properties--why bother?



      "raylopez99 " <raylopez99@yah oo.comwrote in message
      news:86ac7e9a-def6-47d8-b6e5-f716df22a20e@m7 4g2000hsh.googl egroups.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

      Comment

      • Jon Skeet [C# MVP]

        #4
        Re: Automatically Implemented Properties--why bother?

        raylopez99 <raylopez99@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 - <skeet@pobox.co m>
        Web site: http://www.pobox.com/~skeet
        Blog: http://www.msmvps.com/jon.skeet
        C# in Depth: http://csharpindepth.com

        Comment

        • qglyirnyfgfo@mailinator.com

          #5
          Re: Automatically Implemented Properties--why bother?

          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 -

          Comment

          • Jon Skeet [C# MVP]

            #6
            Re: Automatically Implemented Properties--why bother?

            <qglyirnyfgfo@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 - <skeet@pobox.co m>
            Web site: http://www.pobox.com/~skeet
            Blog: http://www.msmvps.com/jon.skeet
            C# in Depth: http://csharpindepth.com

            Comment

            • raylopez99

              #7
              Re: Automatically Implemented Properties--why bother?

              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

              Comment

              • Mythran

                #8
                Re: Automatically Implemented Properties--why bother?



                "Jon Skeet [C# MVP]" <skeet@pobox.co mwrote in message
                news:MPG.237212 d17b6703f6fdd@m snews.microsoft .com...
                <qglyirnyfgfo@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 - <skeet@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


                Comment

                • Jon Skeet [C# MVP]

                  #9
                  Re: Automatically Implemented Properties--why bother?

                  Mythran <Mythran@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 - <skeet@pobox.co m>
                  Web site: http://www.pobox.com/~skeet
                  Blog: http://www.msmvps.com/jon.skeet
                  C# in Depth: http://csharpindepth.com

                  Comment

                  • Jon Skeet [C# MVP]

                    #10
                    Re: Automatically Implemented Properties--why bother?

                    raylopez99 <raylopez99@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 - <skeet@pobox.co m>
                    Web site: http://www.pobox.com/~skeet
                    Blog: http://www.msmvps.com/jon.skeet
                    C# in Depth: http://csharpindepth.com

                    Comment

                    • raylopez99

                      #11
                      Re: Automatically Implemented Properties--why bother?

                      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

                      Comment

                      • raylopez99

                        #12
                        Re: Automatically Implemented Properties--why bother?

                        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

                        Comment

                        • Mythran

                          #13
                          Re: Automatically Implemented Properties--why bother?



                          "Jon Skeet [C# MVP]" <skeet@pobox.co mwrote in message
                          news:MPG.2372a2 6de13c235afde@m snews.microsoft .com...
                          Mythran <Mythran@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 - <skeet@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


                          Comment

                          • Jon Skeet [C# MVP]

                            #14
                            Re: Automatically Implemented Properties--why bother?

                            Mythran <Mythran@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 - <skeet@pobox.co m>
                            Web site: http://www.pobox.com/~skeet
                            Blog: http://www.msmvps.com/jon.skeet
                            C# in Depth: http://csharpindepth.com

                            Comment

                            Working...