construction order [Archive] - C Board

PDA

View Full Version : construction order


George2
04-14-2008, 06:49 AM
Hello everyone,


For the following code, it is correct to say that,

1. obj1 will be instialized when .NET Runtime loads class Foo and before any instance is created?

2. obj2 will be created each time we create an instance of Foo, and obj2 will be called before constructor?

My question is whether my understanding (1) and (2) are correct?


class Foo
{
static private object obj1 = new object();
private object obj2 = new object();
public Foo()
{
}
}



thanks in advance,
George

DanFraser
04-14-2008, 09:40 AM
I know (2) is incorrect. There is no order. It's just a list of items in the class in no particular order other than which you typed first. It's correct that obj2 will be created each time you create an instance of Foo().

And correct me if i'm wrong, but for the static obj1 to work, the class must be static, otherwise it'll just act like obj2.

George2
04-15-2008, 07:40 AM
Thanks DanFraser,


Your answer is clear.

I know (2) is incorrect. There is no order. It's just a list of items in the class in no particular order other than which you typed first. It's correct that obj2 will be created each time you create an instance of Foo().

And correct me if i'm wrong, but for the static obj1 to work, the class must be static, otherwise it'll just act like obj2.


regards,
George

TheRaven
04-29-2008, 10:41 PM
You could also use conditionals like if - else and switch cases in the Foo method to control the instantiation of objects as well. In C# an object can be created from within a method albeit it should be derived from a virtual or abstract type.

Something fun to think about...

George2
04-30-2008, 08:16 AM
Thanks TheRaven,


I am interested in "albeit it should be derived from a virtual or abstract type". Could you show some pseudo code please or more description (so that I can write some code)?

You could also use conditionals like if - else and switch cases in the Foo method to control the instantiation of objects as well. In C# an object can be created from within a method albeit it should be derived from a virtual or abstract type.

Something fun to think about...


regards,
George