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 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
                        • D Dan Neely

                          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 Offline
                          R Offline
                          RugbyLeague
                          wrote on last edited by
                          #21

                          Do you implement CheapOutsourcing() in VB thus: Me = Nothing

                          D 1 Reply Last reply
                          0
                          • R RugbyLeague

                            Do you implement CheapOutsourcing() in VB thus: Me = Nothing

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

                            Note quite. Me.SelfWorth = Nothing

                            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
                            • G Giorgi Dalakishvili

                              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 Offline
                              L Offline
                              led mike
                              wrote on last edited by
                              #23

                              Giorgi Dalakishvili wrote:

                              That's why it is a subtle bug

                              Sure. It's a bug that is created by a developer that does not understand that Properties are NOT the same thing as member variables.

                              led mike

                              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

                                J Offline
                                J Offline
                                Jorgen Sigvardsson
                                wrote on last edited by
                                #24

                                It translates to

                                Foo foo = new Foo();
                                foo.Description = "Blah";
                                foo.Name = "name";

                                How's that bad programming technique?

                                -- Kein Mitleid Für Die Mehrheit

                                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

                                  R Offline
                                  R Offline
                                  Redwan Albougha
                                  wrote on last edited by
                                  #25

                                  Really subtle !! I changed the properties order as Mirko1980 said, Visual Studio is telling me 'Description' does not exist in the current context.:confused: I tend to think that if you do a one step initialization, you can put just one member of your object at the most left side of the assignment, one and just one; why don't ask me :wtf:

                                  Best wishes, Redwan Al-Bougha

                                  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

                                    J Offline
                                    J Offline
                                    Jamie Nordmeyer
                                    wrote on last edited by
                                    #26

                                    I look at it as one of those "if you don't like it, don't use it" things. Frankly, I think it'll make code cleaner and more concise. Instead of 10 different constructors for various combination's of things you MIGHT pass in, this syntax allows you to explicitly initialize the object how you want it. The only real change I've seen in C# so far since its creation that truly scares me is the 'dynamic' keyword in C# 4. I like the idea of it when you're trying to work with interop (like access the Excel object library, for instance), but like the 'unsafe' keyword, you should have to tell the compiler explicitly that you mean it. And THEN, it should only be usable on interop types. You should also never be able to return a dynamic type from methods or properties. In other words:

                                    // Allowed, if a DYNAMIC compiler flag is enabled.
                                    dynamic range = Excel.Application.CurrentWorkbook.CurrentSheet.Range("A1:B3");

                                    // NEVER allowed.
                                    dynamic x = 3;

                                    Kyosa Jamie Nordmeyer - Taekwondo Yi (2nd) Dan Portland, Oregon, USA

                                    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