c# - Preferred method to set the value of a get only Property: constructor vs backing field -


edit : Although I have accepted the answer, the answer should also be considered correct.

Which method is preferred for setting the read-only value? Property: Using the backing field or using Constructor? Assuming that the design is for a property and there is no area (in the future, there may be an update for which the property needs to set up a setter which has to be stopped using a field).

Given the simple example, which method is preferred? If someone is favorite over another, then why?

Option 1 (backing field) :

  class some object {// logic} square fu {Private SomeObject _myObject; Public SomeObject MyObject {get {if (_myObject == empty) {_myObject = new SomeObject (); } Back _myObject; }} Public Foo () {// logic}}  

Option 2 (constructor) :

  class SomeObject {/ / Logic} class Foo {public SomeObject MyObject {get; Private set; } Public Foo () {MyObject = new SomeObject (); // logic}}  

It depends on the time required by the new SomeObject () , "And the probability is that the recipient is being called.

If MyObject is expensive to make, and every time you make an example of Fu (), option 1 is a good idea, and that the lazy preliminary startup time is to reduce Google Programs like Chrome are very heavy to use.

If you are going every time to create MyAbages every time, and the recipient is often called, then you will compare with each option on option 2.


Comments

Popular posts from this blog

c++ - Linux and clipboard -

What is expire header and how to achive them in ASP.NET and PHP? -

sql server - How can I determine which of my SQL 2005 statistics are unused? -