简体   繁体   中英

C# Is there any benefit to assigning class properties in the class constructor?

For instance, if I have a class like this:

namespace Sample
{
     public Class TestObject
     {
          private Object MyAwesomeObject = new MyAwesomeObject();
     }
}

Is there any benefit to set it up so that the property is set in the constructor like this?

namespace Sample
{
     public Class TestObject
     {
          private Object MyAwesomeObject;

          public TestObject()
          {
                MyAwesomeObject = new MyAwesomeObject()
          }
     }
}

The two are (nearly) identical.

When you define the initializer inline:

private Object MyAwesomeObject = new MyAwesomeObject(); 

This will happen prior to the class constructor code. This is often nicer, but does have a couple of limitations.

Setting it up in the constructor lets you use constructor parameters to initialize your members. Often, this is required in order to get more information into your class members.

Also, when you setup values in your constructors, you can use your class data in a static context, which is not possible to do with inlined methods. For example, if you want to initialize something using an expression tree, this often needs to be in a constructor, since the expression tree is in a static context, which will not be allowed to access your class members in an inlined member initializer.

  1. It makes it easier to do step by step debugging

  2. It makes it easier to control the order in which you call constructors

  3. It makes it possible to send parameters to the constructors based on some logic or passed in argument to the object you are working on.

Another nice property of initializing stuff at the declaration site is that doing so on readonly fields guarantees that the field is not observable in its default (initiaized to zero) state.

Here's my article on the subject:

http://blogs.msdn.com/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx

The only benefit is that you can be a bit more dynamic in the constructor, where inline initialization requires that you only use static values for constructor arguments and such. For example, if MyAwesomeObject needs the value from a config file, you would have to set that in the constructor

Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration.

See Fields (C# Programming Guide) .

In your particular example, there's no advantage.

There is, however, lazy instantiation, which reduces your memory footprint in many cases:

namespace Sample
{
     public Class TestObject
     {
          private Object m_MyAwesomeObject;

          public TestObject()
          {

          }

          public Object MyAwesomeObject
          {
              get
              {
                  if (m_MyAwesomeObject == null)
                      m_MyAwesomeObject = new Object();

                  return m_MyAwesomeObject;
              }
          }
     }
}

I like to keep all initialization for any class property whether primitive or object in the class constructor(s). Keeps the code easier to read. Easier to debug. Plus the intention of a constructor is to initialize your classes properties.

Also for clients developing against your classes it's nice to make sure that all your properties get a default value and all objects get created. Avoids the NullReferenceExceptions, when a client is using your class. For me putting this all in constructors makes it easier to manage.

I do not like to duplicate code, even if it is among a (hopefully) small number of constructors. To that end I tend to favor inline initialization wherever it makes sense.

Generally, requiring a non-default constructor ensures that the instance is in something other than the default state. This also allows immutable classes, which have their own advantages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM