Initializing objects in ctor or class

  • Thread starter Thread starter Razzie
  • Start date Start date
R

Razzie

Hello all,

This may seem like a silly question but I suddenly wondered about this. Is
there any difference between the following 2 situations?

1)

class A
{
private SomeObject o = new SomeObject();

public A()
{}
}

2)

class A
{
private SomeObject o;

public A()
{
this.o = new SomeObject();
}
}


Is there any difference at all? If there is, what is it, maybe memory
allocation wise, or something, what method is 'better'? Or would it only
matter (obviously) if you have multiple constructors? Or am I questioning
myself the most weird and useless things ;)

Thanks!
 
I think the second is better.
Because Csharp is a OOP language .
This is a feeling , please follow the feeling .
 
ttl_web said:
I think the second is better.
Because Csharp is a OOP language .

What does that have to do with it? I don't see why either approach is
more OO than the other.
 
There is a rather subtle difference due to the order at which the
assignments happen, which is:

target class field initialization -> base class field initialization -> base
class constructor -> target class constructor

If the base class or the target class is finalizable, you may want to
consider the state of fields at finalization if an exception occurs before
the object is completely constructed. If you pre-initialize the fields,
they will have assigned values at finalization even if an error occurs in
either of the constructors. This may cause some unexpected problems at
finalization, including potential security issues. See
http://blogs.msdn.com/cbrumme/archive/2004/02/20/77460.aspx for details.
 
ttl_web said:
I think the second is better.

why would you favor :
this.o = new SomeObject();
Using the this is redundant becahse the ctor is the default on (no name
clashing with parameters) and there are no local variables (yet) in the ctor
method, so no name clashing with parameters here either. It seems to be
just a bit noisy, and instead of making the code cleaner, more readable - it
seems to be a bit obfuscating - eschew obfuscation !
Because Csharp is a OOP language .

No it is not -- you must be thinking of smalltalk

regards
roy fine
 
Back
Top