Why can't I just put everything in the constructor and why does the sample below call the initialize method?
You can put all this into the constructor. In this simple case you should. Constructors are designed to initialize your object.
Sometimes you have something more complicated:
- Sometimes you will need a separate
Initialize method, because you want to call it at a separate time from construction. - Sometimes you need one because you write several constructors and you want to share some implementation with them.
- Sometimes your initialization is complicated, and you want to give bits of its good names so that you know what your code does. Thus, you break these parts into separate methods.
None of them apply to this code, so I just skipped it and threw the code into the constructor.
Is there an agreement that is commonly used?
Not. People do what is easiest to read and understand, regardless of what is required to write the least additional code, and which causes the least duplication of code.
However, if you make the Initialize method public and do not call it from the constructor, I highly recommend that you call it Initialize . Create it only once.
In this example, I need the word "this." in the Initialize method?
Not. You do not need to use this to access class members unless you have another local variable with the same name. Here is a case like this:
public class Something { private string someValue; public class Something(string someValue) {
source share