Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in instancing object - C# basic [duplicate]

I am beginner in object oriented programming and I have one simple question. What is difference between:

public class Calculation
{
     private _externalObject = new ExternalClass();

     public int FirstParameter {get;set;}
     public int SecondParameter {get;set;}
     public int ThirdParameter {get;set;}
     public int FourthParameter 
     {
          get
          {
               _externalObject.Calculate(FirstParameter, SecondParameter, ThirdParameter);
          }
     }
} 

and

public class Calculation
{

     private _externalObject;

     public Calculation()
     {
           _externalObject = new ExternalClass();
     }

     public int FirstParameter {get;set;}
     public int SecondParameter {get;set;}
     public int ThirdParameter {get;set;}
     public int FourthParameter 
     {
          get
          {
               _externalObject.Calculate(FirstParameter, SecondParameter, ThirdParameter);
          }
     }
} 

I want to learn how should I write optimal code.

like image 909
user1955466 Avatar asked Jan 15 '23 05:01

user1955466


1 Answers

In this particular case, there isn't any measurable difference.

If, however, you had more than one constructor, you would have to initialize the field in each constructor if you didn't do it directly in the field declaration.

It is more a matter of personal style than anything.


Note on class design and integration - if you have an external dependency like that, good OOP would require you to use DI (Dependency Injection) instead of instantiating the value within the class directly. Constructor injection is a good choice:

 private ExternalClass _externalObject;

 public Calculation(ExternalClass externalClass)
 {
       _externalObject = externalClass;
 }

The above allows for modification of behaviour without changing the actual class and makes the class more testable.

like image 130
Oded Avatar answered Jan 28 '23 05:01

Oded