Advertisement
Guest User

Answer to closed question on SO

a guest
Jun 19th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. A constructor is called when the instance is created. This means a few things.
  2. 1. It's only called **once**
  3. 2. It's always the first thing that is called when creating an instance.
  4.  
  5. There might be more but these two are probably the ones that'll help you answer your question.
  6.  
  7. Point 2 is the most important one for your case.
  8.  
  9. Imagine something like this:
  10. ```
  11. class SomeClass
  12. {
  13. private string _myCoolString;
  14.  
  15. public SomeClass(string coolString)
  16. {
  17. _myCoolString = coolString;
  18. }
  19.  
  20. public void SomeCoolMethod()
  21. {
  22. Console.WriteLine(_myCoolString);
  23. }
  24. }
  25. ```
  26.  
  27. Here you can be 100% sure that when you call `SomeCoolMethod` on this instance, that `_myCoolString` will be initialized.
  28.  
  29. However if you have something like this..
  30.  
  31. ```
  32. class SomeClass
  33. {
  34. public string MyCoolString { get; set; }
  35.  
  36. public void SomeCoolMethod()
  37. {
  38. Console.WriteLine(MyCoolString);
  39. }
  40. }
  41. ```
  42.  
  43. .. you cannot be sure that `MyCoolString` will be initialized before calling `SomeCoolMethod`.
  44.  
  45. That's why for some cases you have to use the constructor like this instead of the property-initializer to ensure a variable is initialized as soon as (right after) the object is created.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement