Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- A constructor is called when the instance is created. This means a few things.
- 1. It's only called **once**
- 2. It's always the first thing that is called when creating an instance.
- There might be more but these two are probably the ones that'll help you answer your question.
- Point 2 is the most important one for your case.
- Imagine something like this:
- ```
- class SomeClass
- {
- private string _myCoolString;
- public SomeClass(string coolString)
- {
- _myCoolString = coolString;
- }
- public void SomeCoolMethod()
- {
- Console.WriteLine(_myCoolString);
- }
- }
- ```
- Here you can be 100% sure that when you call `SomeCoolMethod` on this instance, that `_myCoolString` will be initialized.
- However if you have something like this..
- ```
- class SomeClass
- {
- public string MyCoolString { get; set; }
- public void SomeCoolMethod()
- {
- Console.WriteLine(MyCoolString);
- }
- }
- ```
- .. you cannot be sure that `MyCoolString` will be initialized before calling `SomeCoolMethod`.
- 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