views:

62

answers:

2

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

Is there any difference between these two classes?

public class Test
{
    public Guid objectId = Guid.NewGuid();
}

public class Test2
{
    public Guid objectId;
    public Test2()
    {
        objectId = Guid.NewGuid();
    }
}

I'm curious if there is any speed or performance differences between them. Is one method preferred over the other? Personally I like the first better because it uses less lines but unless they are virtually identical as far as execution that is a poor reason to choose one over the other.

A: 

From a performance standpoint I don't think it matters at all. The most important thing is to be consistent. That way you and everybody reading your code will be able to follow along easily.

mpenrow
A: 

I think that in the first scenario, the member would be initialized in all constructors if you were using overloaded constructors. The second scenario would require that you either explicitly initialize the member in all constructors or specially make a call to the default constructor (or another constructor that also initialized members) in order to initialize.

I think from a performance perspective those two are pretty much the same, but I think it's a matter of simplicity vs flexibility. You gain more simplicity in the first scenario but you lose the ability NOT to initialize a member in a version of the constructor if you needed.

Mike

Mike C