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. The Lounge
  3. C# Object Initializer Syntax

C# Object Initializer Syntax

Scheduled Pinned Locked Moved The Lounge
csharpvisual-studio
45 Posts 22 Posters 47 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.
  • J Jacquers

    Just a personal preference, but I've come to dislike the look of this syntax. I think it's the indentation. StudentName student2 = new StudentName { FirstName = "Craig", LastName = "Playstead", }; vs StudentName student2 = new StudentName(); student2.FirstName = "Craig"; student2.LastName = "Playstead";

    M Offline
    M Offline
    megaadam
    wrote on last edited by
    #3

    In C++11 you can just (when you have declared the proper constructor)

    StudentName student2 = {"Craig", "Playstead"};

    It would surprise me if C# had no corresponding way...

    ... such stuff as dreams are made on

    P 1 Reply Last reply
    0
    • J Jacquers

      Just a personal preference, but I've come to dislike the look of this syntax. I think it's the indentation. StudentName student2 = new StudentName { FirstName = "Craig", LastName = "Playstead", }; vs StudentName student2 = new StudentName(); student2.FirstName = "Craig"; student2.LastName = "Playstead";

      OriginalGriffO Online
      OriginalGriffO Online
      OriginalGriff
      wrote on last edited by
      #4

      I like it when it's short enough to fit on a line:

      StudentName student2 = new StudentName{FirstName = "Craig", LastName = "Playstead"};

      But when it gets bigger than that I prefer the older form. Or, if it could indent it like this:

      StudentName student2 = new StudentName{FirstName = "Craig",
      LastName = "Playstead"};

      I'd be happy.

      Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      M 1 Reply Last reply
      0
      • OriginalGriffO OriginalGriff

        I like it when it's short enough to fit on a line:

        StudentName student2 = new StudentName{FirstName = "Craig", LastName = "Playstead"};

        But when it gets bigger than that I prefer the older form. Or, if it could indent it like this:

        StudentName student2 = new StudentName{FirstName = "Craig",
        LastName = "Playstead"};

        I'd be happy.

        Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

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

        I always use your second style here, all function calls are broken up with one param per line, all neatly lined up. (I am so anal about code tidyness :) )

        L K 2 Replies Last reply
        0
        • M megaadam

          In C++11 you can just (when you have declared the proper constructor)

          StudentName student2 = {"Craig", "Playstead"};

          It would surprise me if C# had no corresponding way...

          ... such stuff as dreams are made on

          P Offline
          P Offline
          phil o
          wrote on last edited by
          #6

          megaadam wrote:

          StudentName student2 = {"Craig", "Playstead"};

          It hasn't, at least not that direct. The closest attainable solution is to define a constructor with needed parameters.

          You always obtain more by being rather polite and armed than polite only.

          B 1 Reply Last reply
          0
          • J Jacquers

            Just a personal preference, but I've come to dislike the look of this syntax. I think it's the indentation. StudentName student2 = new StudentName { FirstName = "Craig", LastName = "Playstead", }; vs StudentName student2 = new StudentName(); student2.FirstName = "Craig"; student2.LastName = "Playstead";

            C Offline
            C Offline
            Chris C B
            wrote on last edited by
            #7

            Anything that gets rid of squirly brackets has got to be good. :-D

            Z 2 Replies Last reply
            0
            • C Chris C B

              Anything that gets rid of squirly brackets has got to be good. :-D

              Z Offline
              Z Offline
              ZurdoDev
              wrote on last edited by
              #8

              Chris C-B wrote:

              Anything that gets rid of squirly brackets has got to be good.

              VB! :thumbsup::cool:

              There are only 10 types of people in the world, those who understand binary and those who don't.

              1 Reply Last reply
              0
              • C Chris C B

                Anything that gets rid of squirly brackets has got to be good. :-D

                Z Offline
                Z Offline
                ZurdoDev
                wrote on last edited by
                #9

                Chris C-B wrote:

                Anything that gets rid of squirly brackets has got to be good.

                Long live VB! :thumbsup::cool:

                There are only 10 types of people in the world, those who understand binary and those who don't.

                Sander RosselS 1 Reply Last reply
                0
                • J Jacquers

                  Just a personal preference, but I've come to dislike the look of this syntax. I think it's the indentation. StudentName student2 = new StudentName { FirstName = "Craig", LastName = "Playstead", }; vs StudentName student2 = new StudentName(); student2.FirstName = "Craig"; student2.LastName = "Playstead";

                  R Offline
                  R Offline
                  realJSOP
                  wrote on last edited by
                  #10

                  StudentName student2 = new StudentName
                  {
                  FirstName = "Craig"
                  ,LastName = "Playstead"
                  };

                  Nothing at all wrong with that, and requires less typing than your preferred method. Of course, the ultimate in "less typing" is a constructor with a parameter for each property:

                  StudentName student2 = new StudentName("Craig", "Playstead");

                  In the end, your preference doesn't matter within the context of your employer's coding standards, and no matter which way you go, they all do essentially the same thing.

                  ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                  -----
                  You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                  -----
                  When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                  L Richard DeemingR F 3 Replies Last reply
                  0
                  • P phil o

                    megaadam wrote:

                    StudentName student2 = {"Craig", "Playstead"};

                    It hasn't, at least not that direct. The closest attainable solution is to define a constructor with needed parameters.

                    You always obtain more by being rather polite and armed than polite only.

                    B Offline
                    B Offline
                    Brady Kelly
                    wrote on last edited by
                    #11

                    Or the very subject of this topic, an object initializer: StudentName student2 = new StudentName {"Craig", "Playstead"};

                    Do what thou wilt shall be the whole of the Law. - Liber AL vel Legis 1:40, Aleister Crowley

                    D 1 Reply Last reply
                    0
                    • R realJSOP

                      StudentName student2 = new StudentName
                      {
                      FirstName = "Craig"
                      ,LastName = "Playstead"
                      };

                      Nothing at all wrong with that, and requires less typing than your preferred method. Of course, the ultimate in "less typing" is a constructor with a parameter for each property:

                      StudentName student2 = new StudentName("Craig", "Playstead");

                      In the end, your preference doesn't matter within the context of your employer's coding standards, and no matter which way you go, they all do essentially the same thing.

                      ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                      -----
                      You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                      -----
                      When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #12

                      You moved the comma in the initializer though; saves a keypress if one would copy/paste an entry :)

                      Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^][](X-Clacks-Overhead: GNU Terry Pratchett)

                      R 1 Reply Last reply
                      0
                      • J Jacquers

                        Just a personal preference, but I've come to dislike the look of this syntax. I think it's the indentation. StudentName student2 = new StudentName { FirstName = "Craig", LastName = "Playstead", }; vs StudentName student2 = new StudentName(); student2.FirstName = "Craig"; student2.LastName = "Playstead";

                        L Offline
                        L Offline
                        Lost User
                        wrote on last edited by
                        #13

                        Not only that. It does not introduce any real benefit. Sure, the inititialisation now is atomic, but that can become a pain when debugging (which one of those 4000 fields threw that exception during the initialisation?) and actually is not needed so often.

                        The language is JavaScript. that of Mordor, which I will not utter here
                        This is Javascript. If you put big wheels and a racing stripe on a golf cart, it's still a fucking golf cart.
                        "I don't know, extraterrestrial?" "You mean like from space?" "No, from Canada." If software development were a circus, we would all be the clowns.

                        J R Richard DeemingR I 4 Replies Last reply
                        0
                        • L Lost User

                          Not only that. It does not introduce any real benefit. Sure, the inititialisation now is atomic, but that can become a pain when debugging (which one of those 4000 fields threw that exception during the initialisation?) and actually is not needed so often.

                          The language is JavaScript. that of Mordor, which I will not utter here
                          This is Javascript. If you put big wheels and a racing stripe on a golf cart, it's still a fucking golf cart.
                          "I don't know, extraterrestrial?" "You mean like from space?" "No, from Canada." If software development were a circus, we would all be the clowns.

                          J Offline
                          J Offline
                          Jacquers
                          wrote on last edited by
                          #14

                          Yes, worth it to use the longer syntax just for better debugging :)

                          L 1 Reply Last reply
                          0
                          • J Jacquers

                            Yes, worth it to use the longer syntax just for better debugging :)

                            L Offline
                            L Offline
                            Lost User
                            wrote on last edited by
                            #15

                            I had that problem with a data object for a database table with about 150 columns (a monstrosity by itself). Somewhere in the initialisation a simple null reference exception occured, but for which column. But my cow-orkers insisted on using the initializers because they are soooo cool (why, exactly?), muuuuuch more readable (why, exactly?) and because they are atomic (which we needed for what reason, exactly?).

                            The language is JavaScript. that of Mordor, which I will not utter here
                            This is Javascript. If you put big wheels and a racing stripe on a golf cart, it's still a fucking golf cart.
                            "I don't know, extraterrestrial?" "You mean like from space?" "No, from Canada." If software development were a circus, we would all be the clowns.

                            1 Reply Last reply
                            0
                            • L Lost User

                              You moved the comma in the initializer though; saves a keypress if one would copy/paste an entry :)

                              Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^][](X-Clacks-Overhead: GNU Terry Pratchett)

                              R Offline
                              R Offline
                              realJSOP
                              wrote on last edited by
                              #16

                              I moved the comma because when you're typing that initializer, you need to type a space (or the first letter of a property name that hasn't already been initialized) for intellisense to work. Keeps things lined up as well until I can fiddle with it a little more to make it pretty. :)

                              ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                              -----
                              You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                              -----
                              When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                              1 Reply Last reply
                              0
                              • L Lost User

                                Not only that. It does not introduce any real benefit. Sure, the inititialisation now is atomic, but that can become a pain when debugging (which one of those 4000 fields threw that exception during the initialisation?) and actually is not needed so often.

                                The language is JavaScript. that of Mordor, which I will not utter here
                                This is Javascript. If you put big wheels and a racing stripe on a golf cart, it's still a fucking golf cart.
                                "I don't know, extraterrestrial?" "You mean like from space?" "No, from Canada." If software development were a circus, we would all be the clowns.

                                R Offline
                                R Offline
                                realJSOP
                                wrote on last edited by
                                #17
                                1. If you can't discern which of the properties is throwing the exception, maybe you should let someone else do the debugging. 1) If you have 400 properties that need to be initialized in an object, maybe you should rethink your design and pass a single model object (or a limited number of model objects) to a constructor and debug in the object being initialized. 2) After my first experience with a null reference exception as a result of a database query, I started writing my stored procs in such a way as to NOT return null values for any column.

                                ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                                -----
                                You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                                -----
                                When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                                L 1 Reply Last reply
                                0
                                • R realJSOP

                                  StudentName student2 = new StudentName
                                  {
                                  FirstName = "Craig"
                                  ,LastName = "Playstead"
                                  };

                                  Nothing at all wrong with that, and requires less typing than your preferred method. Of course, the ultimate in "less typing" is a constructor with a parameter for each property:

                                  StudentName student2 = new StudentName("Craig", "Playstead");

                                  In the end, your preference doesn't matter within the context of your employer's coding standards, and no matter which way you go, they all do essentially the same thing.

                                  ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                                  -----
                                  You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                                  -----
                                  When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                                  Richard DeemingR Online
                                  Richard DeemingR Online
                                  Richard Deeming
                                  wrote on last edited by
                                  #18

                                  John Simmons / outlaw programmer wrote:

                                  Nothing at all wrong with that,

                                  Except for the leading comma, which is an abomination. :) I see people use that in SQL queries, who argue that it makes it easier to rearrange the lines without having to remember to add/remove the comma. But it doesn't - you've just moved the problem from the end of the list to the start of the list. And in C#, that's not even a real problem. You can have a trailing comma on every item, including the last:

                                  StudentName student2 = new StudentName
                                  {
                                  FirstName = "Craig",
                                  LastName = "Playstead",
                                  };

                                  As for invoking Intellisense, Ctrl+Space will do the trick without having to insert extra spaces. :)


                                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                  "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                                  R 1 Reply Last reply
                                  0
                                  • L Lost User

                                    Not only that. It does not introduce any real benefit. Sure, the inititialisation now is atomic, but that can become a pain when debugging (which one of those 4000 fields threw that exception during the initialisation?) and actually is not needed so often.

                                    The language is JavaScript. that of Mordor, which I will not utter here
                                    This is Javascript. If you put big wheels and a racing stripe on a golf cart, it's still a fucking golf cart.
                                    "I don't know, extraterrestrial?" "You mean like from space?" "No, from Canada." If software development were a circus, we would all be the clowns.

                                    Richard DeemingR Online
                                    Richard DeemingR Online
                                    Richard Deeming
                                    wrote on last edited by
                                    #19

                                    CDP1802 wrote:

                                    It does not introduce any real benefit.

                                    Lambda expressions? LINQ? Anonymous types? There are plenty of cases where you need to initialize a new object but you can't use multiple statements to do it. If you've never encountered one, then feel free to ignore the syntax. But that doesn't mean they don't exist! :)


                                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                    "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                                    L 1 Reply Last reply
                                    0
                                    • R realJSOP
                                      1. If you can't discern which of the properties is throwing the exception, maybe you should let someone else do the debugging. 1) If you have 400 properties that need to be initialized in an object, maybe you should rethink your design and pass a single model object (or a limited number of model objects) to a constructor and debug in the object being initialized. 2) After my first experience with a null reference exception as a result of a database query, I started writing my stored procs in such a way as to NOT return null values for any column.

                                      ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                                      -----
                                      You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                                      -----
                                      When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                                      L Offline
                                      L Offline
                                      Lost User
                                      wrote on last edited by
                                      #20
                                      1. I did that by leaving the company. 1) Agreed, but it was not my design and the last survivor of the original 'designers' was the company's second in command who took any proposals as a personal insult. Another good reason to leave that place.

                                      The language is JavaScript. that of Mordor, which I will not utter here
                                      This is Javascript. If you put big wheels and a racing stripe on a golf cart, it's still a fucking golf cart.
                                      "I don't know, extraterrestrial?" "You mean like from space?" "No, from Canada." If software development were a circus, we would all be the clowns.

                                      1 Reply Last reply
                                      0
                                      • Richard DeemingR Richard Deeming

                                        CDP1802 wrote:

                                        It does not introduce any real benefit.

                                        Lambda expressions? LINQ? Anonymous types? There are plenty of cases where you need to initialize a new object but you can't use multiple statements to do it. If you've never encountered one, then feel free to ignore the syntax. But that doesn't mean they don't exist! :)


                                        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                        L Offline
                                        L Offline
                                        Lost User
                                        wrote on last edited by
                                        #21

                                        I try to avoid such an unreadable mess where I can. Initializing objects with many members within some other construct is an unreadable mess.

                                        The language is JavaScript. that of Mordor, which I will not utter here
                                        This is Javascript. If you put big wheels and a racing stripe on a golf cart, it's still a fucking golf cart.
                                        "I don't know, extraterrestrial?" "You mean like from space?" "No, from Canada." If software development were a circus, we would all be the clowns.

                                        T 1 Reply Last reply
                                        0
                                        • Richard DeemingR Richard Deeming

                                          John Simmons / outlaw programmer wrote:

                                          Nothing at all wrong with that,

                                          Except for the leading comma, which is an abomination. :) I see people use that in SQL queries, who argue that it makes it easier to rearrange the lines without having to remember to add/remove the comma. But it doesn't - you've just moved the problem from the end of the list to the start of the list. And in C#, that's not even a real problem. You can have a trailing comma on every item, including the last:

                                          StudentName student2 = new StudentName
                                          {
                                          FirstName = "Craig",
                                          LastName = "Playstead",
                                          };

                                          As for invoking Intellisense, Ctrl+Space will do the trick without having to insert extra spaces. :)


                                          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                          R Offline
                                          R Offline
                                          realJSOP
                                          wrote on last edited by
                                          #22

                                          I view the trailing unnecessary comma as an abomination. :)

                                          ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                                          -----
                                          You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                                          -----
                                          When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                                          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