473,545 Members | 2,196 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

static vars declared with class instantiation

Say I have Class1 which contains

static Class2 var1 = new Class2();

Is Class2 constructor code only executed if var1 is referenced in the
code-execution path ?

Or is Class2 constructor code executed on load of any class that references
Class1 ?

Or ... something else ...

Jun 2 '06 #1
10 1745

John A Grandy wrote:
Say I have Class1 which contains

static Class2 var1 = new Class2();

Is Class2 constructor code only executed if var1 is referenced in the
code-execution path ?

Or is Class2 constructor code executed on load of any class that references
Class1 ?

Or ... something else ...


I'm assuming, of course, that the code looks something like this:

public Class1
{
static Class2 var1 = new Class2();
}

So that "var1" is effectively a static member of Class1.

Jon Skeet is the instantiation guru, but if memory serves the instance
of Class2 will be constructed and assigned to var1 the first time that
the execution path makes mention of Class1, either by trying to create
an instance or mentioning any static member of Class1.

It's the same as creating a static constructor for Class1: the static
constructor runs on first "mention" of Class1, before anything in the
class is accessible.

I reserve the right to be wrong, though. :-)

Jun 2 '06 #2
Hmmm ...

So, I'm kindof guessing here, but seems that Singletons might be much less
relevant in .NET compared with , say , Java ?

A .NET class with a static constructor (or has all its data contained in
static vars that are instantiated on declaration) effectively replaces a
Singleton ... because any instantiation-related work is guaranteed to only
be performed once -- on first reference of the class.

"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ f6g2000cwb.goog legroups.com...

John A Grandy wrote:
Say I have Class1 which contains

static Class2 var1 = new Class2();

Is Class2 constructor code only executed if var1 is referenced in the
code-execution path ?

Or is Class2 constructor code executed on load of any class that
references
Class1 ?

Or ... something else ...


I'm assuming, of course, that the code looks something like this:

public Class1
{
static Class2 var1 = new Class2();
}

So that "var1" is effectively a static member of Class1.

Jon Skeet is the instantiation guru, but if memory serves the instance
of Class2 will be constructed and assigned to var1 the first time that
the execution path makes mention of Class1, either by trying to create
an instance or mentioning any static member of Class1.

It's the same as creating a static constructor for Class1: the static
constructor runs on first "mention" of Class1, before anything in the
class is accessible.

I reserve the right to be wrong, though. :-)

Jun 3 '06 #3
Not surprisingly .. Jon has a write up about it here
http://www.yoda.arachsys.com/csharp/...fieldinit.html

Cheers,

Greg Young
MVP - C#
http://geekswithblogs.net/gyoung
"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ f6g2000cwb.goog legroups.com...

John A Grandy wrote:
Say I have Class1 which contains

static Class2 var1 = new Class2();

Is Class2 constructor code only executed if var1 is referenced in the
code-execution path ?

Or is Class2 constructor code executed on load of any class that
references
Class1 ?

Or ... something else ...


I'm assuming, of course, that the code looks something like this:

public Class1
{
static Class2 var1 = new Class2();
}

So that "var1" is effectively a static member of Class1.

Jon Skeet is the instantiation guru, but if memory serves the instance
of Class2 will be constructed and assigned to var1 the first time that
the execution path makes mention of Class1, either by trying to create
an instance or mentioning any static member of Class1.

It's the same as creating a static constructor for Class1: the static
constructor runs on first "mention" of Class1, before anything in the
class is accessible.

I reserve the right to be wrong, though. :-)

Jun 3 '06 #4
<"John A Grandy" <johnagrandy-at-yahoo-dot-com>> wrote:
So, I'm kindof guessing here, but seems that Singletons might be much less
relevant in .NET compared with , say , Java ?

A .NET class with a static constructor (or has all its data contained in
static vars that are instantiated on declaration) effectively replaces a
Singleton ... because any instantiation-related work is guaranteed to only
be performed once -- on first reference of the class.


Yes (for suitably detailed values of "on first reference") but I'm not
sure why you think that's different to Java, which has broadly the same
semantics.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jun 3 '06 #5

John A Grandy wrote:
Hmmm ...

So, I'm kindof guessing here, but seems that Singletons might be much less
relevant in .NET compared with , say , Java ?

A .NET class with a static constructor (or has all its data contained in
static vars that are instantiated on declaration) effectively replaces a
Singleton ... because any instantiation-related work is guaranteed to only
be performed once -- on first reference of the class.


With one hugely important caveat: you can't get a reference to a static
class, so you can't pass it as an argument, return it as a method
result, store it in a collection, etc. Sometimes you want to do these
things with a singleton class. That's why I usually prefer the
singleton pattern to a static class.

As well, if I make something a static class and then later decide my
design was wrong, I'm in for a nightmare. If I make it a singleton and
then decide, for example, that I need to inherit from it and benefit
from polymorphism, well that's easy to fix.

Jun 3 '06 #6

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
<"John A Grandy" <johnagrandy-at-yahoo-dot-com>> wrote:
So, I'm kindof guessing here, but seems that Singletons might be much
less
relevant in .NET compared with , say , Java ?

A .NET class with a static constructor (or has all its data contained in
static vars that are instantiated on declaration) effectively replaces a
Singleton ... because any instantiation-related work is guaranteed to
only
be performed once -- on first reference of the class.


Yes (for suitably detailed values of "on first reference") but I'm not
sure why you think that's different to Java, which has broadly the same
semantics.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Jun 4 '06 #7
Hmmm ... well, it looks like I've obtained a misunderstandin g of how Java
handles static vars from a design patterns book I won't name.

This book states that the traditional Singleton will have its static vars'
assignment constructors invoked on load of the class ... which I understand
to mean load of the class' assembly.

I'm referring to the example I gave above (which Bruce correctly augmentd).
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
<"John A Grandy" <johnagrandy-at-yahoo-dot-com>> wrote:
So, I'm kindof guessing here, but seems that Singletons might be much
less
relevant in .NET compared with , say , Java ?

A .NET class with a static constructor (or has all its data contained in
static vars that are instantiated on declaration) effectively replaces a
Singleton ... because any instantiation-related work is guaranteed to
only
be performed once -- on first reference of the class.


Yes (for suitably detailed values of "on first reference") but I'm not
sure why you think that's different to Java, which has broadly the same
semantics.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Jun 4 '06 #8
<"John A Grandy" <johnagrandy-at-yahoo-dot-com>> wrote:
Hmmm ... well, it looks like I've obtained a misunderstandin g of how Java
handles static vars from a design patterns book I won't name.

This book states that the traditional Singleton will have its static vars'
assignment constructors invoked on load of the class ... which I understand
to mean load of the class' assembly.


There's no such concept of "assembly" in Java, so that can't be right.

However, the semantics of when a type's initialization occurs is in the
Java language specification. From section 12.4.1:

<quote>
A class or interface type T will be initialized immediately before the
first occurrence of any one of the following:

* T is a class and an instance of T is created.
* T is a class and a static method declared by T is invoked.
* A static field declared by T is assigned.
* A static field declared by T is used and the reference to the
field is not a compile-time constant (§15.28). References to compile-
time constants must be resolved at compile time to a copy of the
compile-time constant value, so uses of such a field never cause
initialization.
</quote>

In other words, it's pretty similar to the C# behaviour when there's a
static constructor present. (When there's no static constructor present
in C#, the CLR has more discretion in terms of exactly when type
initialization occurs.)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jun 4 '06 #9
Once initialized , a static ref to a type retains its instantiated object in
memory until the containing app domain is recycled (either as part of worker
process recycle , or otherwise ) ...

For an asp.net app , I want to use the singleton strictly within the
processing of a single page request ...

( Complex conditional logic in the page processing means that the "Instance"
method or property on the singleton won't necessarily be called , and so the
private member won't necessarily be instantiated. )

If I provide a function that can be called to set the static ref to null (
to dispose of the referred to object before page unload ) , what
complications are there to proper design of a scalable singleton ?
Or is a singleton not the best solution for my design goal .... ?
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
<"John A Grandy" <johnagrandy-at-yahoo-dot-com>> wrote:
Hmmm ... well, it looks like I've obtained a misunderstandin g of how Java
handles static vars from a design patterns book I won't name.

This book states that the traditional Singleton will have its static vars'
assignment constructors invoked on load of the class ... which I
understand
to mean load of the class' assembly.


There's no such concept of "assembly" in Java, so that can't be right.

However, the semantics of when a type's initialization occurs is in the
Java language specification. From section 12.4.1:

<quote>
A class or interface type T will be initialized immediately before the
first occurrence of any one of the following:

* T is a class and an instance of T is created.
* T is a class and a static method declared by T is invoked.
* A static field declared by T is assigned.
* A static field declared by T is used and the reference to the
field is not a compile-time constant (§15.28). References to compile-
time constants must be resolved at compile time to a copy of the
compile-time constant value, so uses of such a field never cause
initialization.
</quote>

In other words, it's pretty similar to the C# behaviour when there's a
static constructor present. (When there's no static constructor present
in C#, the CLR has more discretion in terms of exactly when type
initialization occurs.)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jun 7 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2196
by: Connell Gauld | last post by:
Hi, I'm using VC++. I have a class called exClass defined in exClass.h exClass has a static variable, declared like this in the public section. static int exStaticVar; Below the class definition I have initialised (right word?) it like this int exClass::nextFree; Now below is a code fragment from a non-static function in another class...
7
2466
by: Drew McCormack | last post by:
I have a C++ template class which contains a static variable whose construction registers the class with a map. Something like this: template <typename T> class M { static Registrar<M> registrar; }; The constructor of Registrar does the registering when it is initialized.
18
5735
by: Erik Arner | last post by:
Hi, I really need some help here. After upgrading to g++ 3.4 I have run into all sorts of troubles that I'm sure depends on my lack of proper understanding of C++. I would now like to get it right once and for all, if possible. Most severe is the problem illustrated by the code below. It's based on the "pluggable factory pattern" described...
10
2187
by: Chris Clement | last post by:
I didn't write this code so I'm not sure what is going on with this error. checkedListBox1 is a public object. Why does the error say that it is expecting a 'class' in a for loop? Is it because the method is static? Here is the error and the code: C:\...\Form1.cs(1130): 'APP.mainForm.checkedListBox1' denotes a 'field' where a 'class' was...
8
3001
by: Robert A Riedel | last post by:
I have an application that requires a DLL and an executable that uses the DLL, both of which were implemented in Visual C++ using unmanged code. Both the executable and the DLL are linked with functions that are stored in a static library. During initialization of the executable, classes and static globals within functions linked from the...
6
4069
by: Maya | last post by:
Hello guys, in C#, is using "static" would be the most proper way to get around calling methods located in different classes? for instance, a method caller in class A wouldn't see a method in class B unless that method is declared as public static. This works fine (i guess!) for me, and i have been doing this for a long time, just came to...
9
8626
by: CDMAPoster | last post by:
About a year ago there was a thread about the use of global variables in A97: http://groups.google.com/group/comp.databases.ms-access/browse_frm/thread/fedc837a5aeb6157 Best Practices by Kang Su Gatlin, casual mention was made about using static variables as an alternative to using global variables. This caused me to think of the...
55
6165
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in C# in some way? Or maybe no, because it is similar to a global variable (with its scope restricted) which C# is dead against? Zytan
17
8355
by: Juha Nieminen | last post by:
As we know, the keyword "inline" is a bit misleading because its meaning has changed in practice. In most modern compilers it has completely lost its meaning of "a hint for the compiler to inline the function if possible" (because if the compiler has the function definition available at an instantiation point, it will estimate whether to...
0
7398
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7656
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
5969
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
4944
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3449
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1878
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1013
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
701
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.