C # Is there any use for assigning class properties in a class constructor?

For example, if I have a class like this:

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

Is there any use for setting it up so that the property is set in the constructor as follows?

namespace Sample
{
     public Class TestObject
     {
          private Object MyAwesomeObject;

          public TestObject()
          {
                MyAwesomeObject = new MyAwesomeObject()
          }
     }
}
+3
source share
9 answers

These two are (almost) identical.

When you define the inline initializer:

private Object MyAwesomeObject = new MyAwesomeObject(); 

This will happen before the class constructor code. This is often better, but has several limitations.

A setting in the constructor allows you to use constructor options to initialize your members. Often this is required in order to obtain additional information about the members of your class.

, , , . , - , , , .

+10
  • ,

  • , .

+4

, , inline- , .. , MyAwesomeObject ,

+1

. , , .

. ( #).

+1

.

, , , :

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;
              }
          }
     }
}
+1

, . . . , .

, , , , . NullReferenceExceptions, . .

+1

, () . , .

+1

, , , , - . , .

0

Source: https://habr.com/ru/post/1727277/


All Articles