0

Possible Duplicate:
Best Practice: Initialize class fields in constructor or at declaration?

this is just a simple and even a little stupid doubt that me and my friends raised while talking about our current project.

What I wanna know is the difference between calling a method to set a variable inside and outside the constructor of a class using C#, like in the example below:

Case 1:

public class Test
{
    string myVar = GetValue();

    public Test()
    {
    }
}

Case 2:

public class Test
{
    string myVar;

    public Test()
    {
        myVar = GetValue(); 
    }
}

Are there performance differences or any "pattern violations" when using any of these approaches? I would really appreciate if anyone could tell me which of these approaches is better and what really happens when I use them on a compiler level.

Thanks in advance!

Community
  • 1
  • 1

4 Answers4

1

AFAIK the only difference is the field initialization (your first example) is triggered first - It's still essentially treated as constructor code. There are no performance gains by choosing one over the other it's really a matter of preference.

One thing to be aware of is execution order as it can change based on your class hierarchy.

James
  • 80,725
  • 18
  • 167
  • 237
  • 1
    Just to mention - fields are initialized also before base class constructor invocation. When you initialize variable in derived class constructor, it will be initialized after base class constructor invocation. – Sergey Berezovskiy Jan 09 '13 at 12:14
  • 1
    @lazyberezovsky +1 yeah good point, that might not be immediately obvious. – James Jan 09 '13 at 12:17
1

If your method GetValue is a static method in your class then you can use it in Field Initialization. If its an instance method, you will get an error.

Your first code is using Field Initialization, whereas in your 2nd code you are initializing the field in the constructor.

Fields C#

Fields are initialized immediately before the constructor for the object instance is called, so if the constructor assigns the value of a field, it will overwrite any value given during field declaration.

As far as which one is better, I would say it depends on your requirement. Usually if you are passing some parameter to the constructor that you want to assign to some field then you can only do it in the constructor. But if you want to have some default value for the fields, before the execution of the constructor then its good to have Field Initializer.

Habib
  • 219,104
  • 29
  • 407
  • 436
0

One case in which field initialization may be feasible and gain readability is next case

class Test
{
    string myVar;
    string anotherVar;

    public Test()
    {
        myVar = "one default";
        anotherVar = "another default";
    }
    public Test(string s) //: this()
    {
        myVar = s;
        anotherVar = "another default";
    }
}

You probably don't want to call constructor by default, because it might be wrong in some cases to initialize some variable two times (in my case it is definitively ok); So in example above I would move anotherVar to field initialization.

Note: speaking about performance, which I don't on such nano-optimization levels - when you use field initialize your field receive it first value as desired. When you initialize it from constructor, it already have its default value, so technically speaking you assign a field twice. But this penalty is so small, that I can't imagine scenarios, in which it is plausible.

Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
0

The code you posted isn't compiling, so I went ahead and made several possible variations.

1. Static field and static method

public class Test
{
    static string myVar = GetValue();

    public Test()
    {
    }

    static string GetValue()
    {
        return String.Empty;
    }
}

In this case it doesn't really matter where you set a static field: in a static constructor (not presented in the code) or as a static field initialization. CLR will initialize both when a type is loaded into AppDomain. (There is a sequence, such as CLR calls static constructor first and then sets all the static fields or vice versa - this sequence is out of your control though).

2. Setting up property in a constructor

public class Test1
{
    string MyVar{get;set;}
        
    public Test1()
    {
        MyVar = GetValue();
    }

    string GetValue()
    {
        return String.Empty;
    }
}

This depends on the type and usage. In this particular case I would probably avoid doing this, as constructor meant to be lightweight. If you do any heavy processing it's better move this to an Initialize method with proper error handling and try-catch blocks. If you don't do any heavy-lifting to set up a property - just put a default value in the constructor, such as MyVar = "EMPTY".

3. Set property in another class

public class Test
{
    public string MyVar{get;set;}
        
    public Test(){ }

    public string GetValue()
    {
        return String.Empty;
    }
}

//somewere else 
Test t = new Test();
t.MyVar = t.GetValue();

This looks a bit odd, as class is providing a state (property) and means to get the current state (GetValue method). The two members (property and method) in this case shall be probably merged into a single getter.

Community
  • 1
  • 1
oleksii
  • 35,458
  • 16
  • 93
  • 163