tarabyte
tarabyte

Reputation: 19172

Initialize Private Object in Declaration or Constructor in C#

I keep on bouncing back and forth and would like to standardize on the best one:

private MyOtherClass mc = new MyOtherClass(); // up here OK?

public MyClass()
{
  // or down here?, mc = new MyOtherClass();
}

At what time does the initialization at the declaration happen? When the program first starts up?

Upvotes: 2

Views: 1482

Answers (5)

Marco Forberg
Marco Forberg

Reputation: 2644

Both ways are okay. For me i put up the following rule:

If an attribute is always initilized the same way no matter which constructor was used i initilize it on declaration so i have this only once. Keeps constructors a tiny bit cleaner.

If there are different ways to initialize it depending on chosen constructor i initialize in the constructor body.

public class SomeClass
{
    private List<String> content = new List<String>();
    private String searchKey;

    public SomeClass()
    {
        searchKey = String.Empty;
    }

    public SomeClass(String searchKey)
    {
        this.seachKey = searchKey;
    }

    // some more code
}

Finally to answer your question about the point in time, when things get initilized:

  1. static fields will be initialized when the first instance of a class is constructed.

  2. all non static fields will be initialized when an instance of this class is constructed, starting with the fields that have a value in their declaration and then the constructor body is executed to initialize the rest.

Upvotes: 0

T.S.
T.S.

Reputation: 19330

I would say Like this: It doesn't matter where you initialize if this is just a stand-alone class. When this class will become a base class, it might be matter at that time. Specifically speaking, I am talking of order of execution. If you want your base init something first, move that initialization to constructor. There could be different variants of chain of execution depending on how constructors declared, etc. so the answer is, it may be matter or may be doesn't matter. Definitely doesn't matter if sealed class. But as soon as inheritance involved, the answer is volatile.

Upvotes: 0

user799755
user799755

Reputation:

In your post, you asked "At what time does the initialization at the declaration happen? When the program first starts up?".

The other answers are correct, but I just wanted to emphasize that:

private MyOtherClass mc = new MyOtherClass();

is declaring an instance field, and is initialized when the instance is instantiated, not when the program starts up.

If you declared a static field:

private static MyOtherClass mc = new MyOtherClass();

This would be initialized when the type constructor is run, which happens when any member of a class is first accessed (modulo some complication that Jon Skeet and Eric Lippert would do a better job of explaining than I would).

In neither case is the field initialized when the program starts up.

Upvotes: 0

leviathanbadger
leviathanbadger

Reputation: 1712

There is very little real difference. They both compile to almost the same thing. Mostly it depends on your coding style. You should know that the fields are initialized before the super constructor is called, but relying on this fact would be bad practice.

I prefer to initialize all of my fields in the constructor, so that I have more control over what order they are initialized in.

Upvotes: 2

McGarnagle
McGarnagle

Reputation: 102743

Either is fine: it's really a matter of preference or how you want to organize the construction logic.

Note that the inline value gets set first, before even the constructor runs. Ie, the following outputs bar:

public class MyClass
{
    private string _member = "foo";
    public string Member { get { return _member; } }

    public MyClass()
    {
        _member = "bar";
    }
}

class Program
{
    static void Main(string[] args)
    {
        var myClass = new MyClass();
        Console.WriteLine(myClass.Member);
        Console.ReadLine();
    }
}

Upvotes: 1

Related Questions