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. General Programming
  3. C#
  4. Initiate properties at the creation of the object.

Initiate properties at the creation of the object.

Scheduled Pinned Locked Moved C#
question
2 Posts 2 Posters 0 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
    Gilbert Consellado
    wrote on last edited by
    #1

    I know that the code snippet below is equal, but which is better?

    Sample sm = new Sample()
    {
    prop1 = 1,
    prop2 = 2
    };

    and

    Sample sm = new Sample();
    sm.prop1 = 1;
    sm.prop2 = 2;

    Is there any advantage and disadvantage on both of them? what's your thought about this? thanks

    P 1 Reply Last reply
    0
    • G Gilbert Consellado

      I know that the code snippet below is equal, but which is better?

      Sample sm = new Sample()
      {
      prop1 = 1,
      prop2 = 2
      };

      and

      Sample sm = new Sample();
      sm.prop1 = 1;
      sm.prop2 = 2;

      Is there any advantage and disadvantage on both of them? what's your thought about this? thanks

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

      In the example you show, there is no difference between the two. The object initializer approach was introduced initially to cope with creating anonymous objects - it was the only way to define the "shape" of the object if it was anonymous.

      This space for rent

      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