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.
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.