Friday, 15 May 2015

oop - Difference in instancing object - C# basic -



oop - Difference in instancing object - C# basic -

this question has reply here:

initialize class fields in constructor or @ declaration? 10 answers

i beginner in object oriented programming , have 1 simple question. 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 { { _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 { { _externalobject.calculate(firstparameter, secondparameter, thirdparameter); } } }

i want larn how should write optimal code.

in particular case, there isn't measurable difference.

if, however, had more 1 constructor, have initialize field in each constructor if didn't straight in field declaration.

it more matter of personal style anything.

note on class design , integration - if have external dependency that, oop require utilize di (dependency injection) instead of instantiating value within class directly. constructor injection choice:

private externalclass _externalobject; public calculation(externalclass externalclass) { _externalobject = externalclass; }

the above allows modification of behaviour without changing actual class , makes class more testable.

c# oop object properties constructor

No comments:

Post a Comment