Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Other Discussions
  3. Clever Code
  4. Object initializers. [modified]

Object initializers. [modified]

Scheduled Pinned Locked Moved Clever Code
comtoolshelpquestion
26 Posts 15 Posters 32 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • G Offline
    G Offline
    Giorgi Dalakishvili
    wrote on last edited by
    #1

    class Foo
    {
    public string Description { get; set; }
    public String Name { get; set; }
    }

    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    private void InitFoo()
    {
    Foo foo = new Foo() { Description = Name = "name" };
    }
    }

    After running InitFoo method foo.Name is not initialized. Can you spot the bug? You can see answer at my blog post: Object Initializers and Possible Bugs[^]

    Giorgi Dalakishvili #region signature my articles My blog[^] #endregion

    modified on Friday, September 19, 2008 2:19 AM

    P M realJSOPR L R 5 Replies Last reply
    0
    • G Giorgi Dalakishvili

      class Foo
      {
      public string Description { get; set; }
      public String Name { get; set; }
      }

      public partial class Form1 : Form
      {
      public Form1()
      {
      InitializeComponent();
      }

      private void InitFoo()
      {
      Foo foo = new Foo() { Description = Name = "name" };
      }
      }

      After running InitFoo method foo.Name is not initialized. Can you spot the bug? You can see answer at my blog post: Object Initializers and Possible Bugs[^]

      Giorgi Dalakishvili #region signature my articles My blog[^] #endregion

      modified on Friday, September 19, 2008 2:19 AM

      P Offline
      P Offline
      Pete OHanlon
      wrote on last edited by
      #2

      You can't initialize objects like this. You need to use Description="Blah", Name="Blah".

      Deja View - the feeling that you've seen this post before.

      My blog | My articles

      G 1 Reply Last reply
      0
      • P Pete OHanlon

        You can't initialize objects like this. You need to use Description="Blah", Name="Blah".

        Deja View - the feeling that you've seen this post before.

        My blog | My articles

        G Offline
        G Offline
        Giorgi Dalakishvili
        wrote on last edited by
        #3

        Pete O'Hanlon wrote:

        You can't initialize objects like this.

        That's correct but the above code compiles. But foo.Name is not initialized. That's why it is a subtle bug ;)

        Giorgi Dalakishvili #region signature my articles My blog[^] #endregion

        L 1 Reply Last reply
        0
        • G Giorgi Dalakishvili

          class Foo
          {
          public string Description { get; set; }
          public String Name { get; set; }
          }

          public partial class Form1 : Form
          {
          public Form1()
          {
          InitializeComponent();
          }

          private void InitFoo()
          {
          Foo foo = new Foo() { Description = Name = "name" };
          }
          }

          After running InitFoo method foo.Name is not initialized. Can you spot the bug? You can see answer at my blog post: Object Initializers and Possible Bugs[^]

          Giorgi Dalakishvili #region signature my articles My blog[^] #endregion

          modified on Friday, September 19, 2008 2:19 AM

          realJSOPR Offline
          realJSOPR Offline
          realJSOP
          wrote on last edited by
          #4

          I didn't know you could do this (citing the correct way to do it):

          Foo foo = new Foo() { Description="Blah", Name="name"};

          Putting the constructor body here is, IMHO, bad programming technique.

          "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
          -----
          "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

          G P R J 4 Replies Last reply
          0
          • G Giorgi Dalakishvili

            class Foo
            {
            public string Description { get; set; }
            public String Name { get; set; }
            }

            public partial class Form1 : Form
            {
            public Form1()
            {
            InitializeComponent();
            }

            private void InitFoo()
            {
            Foo foo = new Foo() { Description = Name = "name" };
            }
            }

            After running InitFoo method foo.Name is not initialized. Can you spot the bug? You can see answer at my blog post: Object Initializers and Possible Bugs[^]

            Giorgi Dalakishvili #region signature my articles My blog[^] #endregion

            modified on Friday, September 19, 2008 2:19 AM

            M Offline
            M Offline
            Mirko1980
            wrote on last edited by
            #5

            That was subtle! Actually Visual Studio tooltips help in spotting it. Another way to spot it is to change the assignment to the following:

            Foo foo = new Foo() { Name = Description = "name" };

            Initially I tought the problem was the order of assignement, so I inverted it. Well the result was somewhat surprising :-D

            G 1 Reply Last reply
            0
            • realJSOPR realJSOP

              I didn't know you could do this (citing the correct way to do it):

              Foo foo = new Foo() { Description="Blah", Name="name"};

              Putting the constructor body here is, IMHO, bad programming technique.

              "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
              -----
              "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

              G Offline
              G Offline
              Giorgi Dalakishvili
              wrote on last edited by
              #6

              John Simmons / outlaw programmer wrote:

              I didn't know you could do this: Foo foo = new Foo() { Description = Name = "name" };

              You can't. But in this case it compiles. That's why it's a subtle bug :)

              Giorgi Dalakishvili #region signature my articles My blog[^] #endregion

              realJSOPR 1 Reply Last reply
              0
              • M Mirko1980

                That was subtle! Actually Visual Studio tooltips help in spotting it. Another way to spot it is to change the assignment to the following:

                Foo foo = new Foo() { Name = Description = "name" };

                Initially I tought the problem was the order of assignement, so I inverted it. Well the result was somewhat surprising :-D

                G Offline
                G Offline
                Giorgi Dalakishvili
                wrote on last edited by
                #7

                yes, changing the assignment really helps :)

                Giorgi Dalakishvili #region signature my articles My blog[^] #endregion

                1 Reply Last reply
                0
                • G Giorgi Dalakishvili

                  John Simmons / outlaw programmer wrote:

                  I didn't know you could do this: Foo foo = new Foo() { Description = Name = "name" };

                  You can't. But in this case it compiles. That's why it's a subtle bug :)

                  Giorgi Dalakishvili #region signature my articles My blog[^] #endregion

                  realJSOPR Offline
                  realJSOPR Offline
                  realJSOP
                  wrote on last edited by
                  #8

                  When I said "I didn't know you could do this", I was talking about initializing the properties when instantiating the object.

                  "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                  -----
                  "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                  G 1 Reply Last reply
                  0
                  • realJSOPR realJSOP

                    When I said "I didn't know you could do this", I was talking about initializing the properties when instantiating the object.

                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                    -----
                    "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                    G Offline
                    G Offline
                    Giorgi Dalakishvili
                    wrote on last edited by
                    #9

                    Oh my mistake. It's a new feature in c# 3.0 called object initializers.

                    Giorgi Dalakishvili #region signature my articles My blog[^] #endregion

                    P 1 Reply Last reply
                    0
                    • G Giorgi Dalakishvili

                      Oh my mistake. It's a new feature in c# 3.0 called object initializers.

                      Giorgi Dalakishvili #region signature my articles My blog[^] #endregion

                      P Offline
                      P Offline
                      PIEBALDconsult
                      wrote on last edited by
                      #10

                      Ah, more new "features" to avoid. I wish they'd add the features the I want.

                      R 1 Reply Last reply
                      0
                      • realJSOPR realJSOP

                        I didn't know you could do this (citing the correct way to do it):

                        Foo foo = new Foo() { Description="Blah", Name="name"};

                        Putting the constructor body here is, IMHO, bad programming technique.

                        "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                        -----
                        "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                        P Offline
                        P Offline
                        Paul Conrad
                        wrote on last edited by
                        #11

                        John Simmons / outlaw programmer wrote:

                        Putting the constructor body here is, IMHO, bad programming technique.

                        I second that.

                        "The clue train passed his station without stopping." - John Simmons / outlaw programmer "Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon "Not only do you continue to babble nonsense, you can't even correctly remember the nonsense you babbled just minutes ago." - Rob Graham

                        1 Reply Last reply
                        0
                        • G Giorgi Dalakishvili

                          class Foo
                          {
                          public string Description { get; set; }
                          public String Name { get; set; }
                          }

                          public partial class Form1 : Form
                          {
                          public Form1()
                          {
                          InitializeComponent();
                          }

                          private void InitFoo()
                          {
                          Foo foo = new Foo() { Description = Name = "name" };
                          }
                          }

                          After running InitFoo method foo.Name is not initialized. Can you spot the bug? You can see answer at my blog post: Object Initializers and Possible Bugs[^]

                          Giorgi Dalakishvili #region signature my articles My blog[^] #endregion

                          modified on Friday, September 19, 2008 2:19 AM

                          L Offline
                          L Offline
                          leppie
                          wrote on last edited by
                          #12

                          Giorgi Dalakishvili wrote:

                          Foo foo = new Foo() { Description = Name = "name" };

                          OMG! I didn't even know that was legal syntax! (but I can see it now) Good spot :)

                          xacc.ide - now with TabsToSpaces support
                          IronScheme - 1.0 alpha 4a out now (29 May 2008)
                          ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

                          1 Reply Last reply
                          0
                          • realJSOPR realJSOP

                            I didn't know you could do this (citing the correct way to do it):

                            Foo foo = new Foo() { Description="Blah", Name="name"};

                            Putting the constructor body here is, IMHO, bad programming technique.

                            "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                            -----
                            "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                            R Offline
                            R Offline
                            Roger Alsing 0
                            wrote on last edited by
                            #13

                            What do you mean with this?:

                            John Simmons / outlaw programmer wrote:

                            Putting the constructor body here is, IMHO, bad programming technique

                            It's not like you are moving the ctor out from the class and into the initializer. the initializer is the initializer, configuring stuff that are not default values. eg: Person you = new Person() {FirstName = "John",LastName="Simmons"}; Ofcourse you could write your own constructor that takes those as in params. But there are cases where a class has alot of properties and you are not likely to provide a constructor with every possible set of in param combination for those. Or did I completely misinterpret what you said?

                            My Blog

                            realJSOPR 1 Reply Last reply
                            0
                            • R Roger Alsing 0

                              What do you mean with this?:

                              John Simmons / outlaw programmer wrote:

                              Putting the constructor body here is, IMHO, bad programming technique

                              It's not like you are moving the ctor out from the class and into the initializer. the initializer is the initializer, configuring stuff that are not default values. eg: Person you = new Person() {FirstName = "John",LastName="Simmons"}; Ofcourse you could write your own constructor that takes those as in params. But there are cases where a class has alot of properties and you are not likely to provide a constructor with every possible set of in param combination for those. Or did I completely misinterpret what you said?

                              My Blog

                              realJSOPR Offline
                              realJSOPR Offline
                              realJSOP
                              wrote on last edited by
                              #14

                              This falls neatly under the category of "Just because you *can* do it, doesn't mean you *should* do it". Why is that better than writing the appropriate constructor and using new Person("John", "Simmons");? Further, an appropriately designed class initializes all of its properties when it's instantiated. This new feature of .Net appears to propagate lazy programmers.

                              "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                              -----
                              "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                              CPalliniC R P J 4 Replies Last reply
                              0
                              • realJSOPR realJSOP

                                This falls neatly under the category of "Just because you *can* do it, doesn't mean you *should* do it". Why is that better than writing the appropriate constructor and using new Person("John", "Simmons");? Further, an appropriately designed class initializes all of its properties when it's instantiated. This new feature of .Net appears to propagate lazy programmers.

                                "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                -----
                                "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                                CPalliniC Offline
                                CPalliniC Offline
                                CPallini
                                wrote on last edited by
                                #15

                                John Simmons / outlaw programmer wrote:

                                This new feature of .Net appears to propagate lazy programmers.

                                All the .NET thing goes in such a direction... :-D

                                If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                                This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                                [My articles]

                                In testa che avete, signor di Ceprano?

                                1 Reply Last reply
                                0
                                • realJSOPR realJSOP

                                  This falls neatly under the category of "Just because you *can* do it, doesn't mean you *should* do it". Why is that better than writing the appropriate constructor and using new Person("John", "Simmons");? Further, an appropriately designed class initializes all of its properties when it's instantiated. This new feature of .Net appears to propagate lazy programmers.

                                  "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                  -----
                                  "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                                  R Offline
                                  R Offline
                                  Roger Alsing 0
                                  wrote on last edited by
                                  #16

                                  John Simmons / outlaw programmer wrote:

                                  Why is that better than writing the appropriate constructor

                                  As I said in my first post. Lets assume that your class contains 20 properties, all of those recieve default values in the default ctor. And the user only wants to init custom values in 5 of them.. (Think winforms control or such, eg a grid) Should you create a constructor for each possible combination of properties that the user _might_ want to set? No way..

                                  My Blog

                                  D 1 Reply Last reply
                                  0
                                  • R Roger Alsing 0

                                    John Simmons / outlaw programmer wrote:

                                    Why is that better than writing the appropriate constructor

                                    As I said in my first post. Lets assume that your class contains 20 properties, all of those recieve default values in the default ctor. And the user only wants to init custom values in 5 of them.. (Think winforms control or such, eg a grid) Should you create a constructor for each possible combination of properties that the user _might_ want to set? No way..

                                    My Blog

                                    D Offline
                                    D Offline
                                    Dan Neely
                                    wrote on last edited by
                                    #17

                                    Not to mention if they're all the same type you can't create a ctors for all of them. That said, this is just a return of optional parameters. Personally I'd prefer a syntax of FooBar myFooBar = new FooBar(1,2,,,5,,,8,,,,,,15,,,,19,20); and a ctor that looked like FooBar(optional int param1, optional int param2, optional int param3,.... ) {...}

                                    Today's lesson is brought to you by the word "niggardly". Remember kids, don't attribute to racism what can be explained by Scandinavian language roots. -- Robert Royall

                                    1 Reply Last reply
                                    0
                                    • realJSOPR realJSOP

                                      This falls neatly under the category of "Just because you *can* do it, doesn't mean you *should* do it". Why is that better than writing the appropriate constructor and using new Person("John", "Simmons");? Further, an appropriately designed class initializes all of its properties when it's instantiated. This new feature of .Net appears to propagate lazy programmers.

                                      "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                      -----
                                      "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                                      P Offline
                                      P Offline
                                      PIEBALDconsult
                                      wrote on last edited by
                                      #18

                                      Ten! Or we should be able to use something like the syntax that Attributes use.

                                      1 Reply Last reply
                                      0
                                      • P PIEBALDconsult

                                        Ah, more new "features" to avoid. I wish they'd add the features the I want.

                                        R Offline
                                        R Offline
                                        RugbyLeague
                                        wrote on last edited by
                                        #19

                                        I am still holding out for them to add a DoAllMyWork class ;P

                                        D 1 Reply Last reply
                                        0
                                        • R RugbyLeague

                                          I am still holding out for them to add a DoAllMyWork class ;P

                                          D Offline
                                          D Offline
                                          Dan Neely
                                          wrote on last edited by
                                          #20

                                          You can make one by inheriting HireRentACoder and implementing CheapOutsourcing().

                                          Today's lesson is brought to you by the word "niggardly". Remember kids, don't attribute to racism what can be explained by Scandinavian language roots. -- Robert Royall

                                          R 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups