473,513 Members | 2,633 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ASP.NET 2.0: static instance of reference type is not always set to null

We have several Web projects where we suddenly began experiencing various
problems after porting them to .NET 2.0. I debugged one of them and here's
what I've found:

In one of referenced assemblies there was a class with static members of
other class:

class A
{
...
static B b;

void Init()
{
if(b != null)
{
b = new B();
}
}
}

The problem was related to "b" instance, so I ran a debugger session and
discovered that I never entered code "b = new B()". The member variable "b"
has always been instantiated when I checked its value in debug session!

Then I slightly modified the code:

class A
{
...
static B b = null;

void Init()
{
if(b != null)
{
b = new B();
}
}
}

Then everything worked. But why? If we have a reference type, why does it
make any difference if we instantiate the variable of this type to null or
not? It shouldn't! Reference types instances must be set to null.

I also tried to run this code in non-Web project, but there it worked
without any problem. It has to be something related to ASP.NET.

Any info on this issue is appreciated.

Vagif Abilov
Oslo Norway
May 22 '06 #1
22 1647
ms-help://MS.VSExpressCC.v80/MS.NETFramework.v20.en/dv_csref/html/235614b5-1371-4dbd-9abd-b406a8b0298b.htm
:

--------------------------------------------------------------------------------------------------------------------------
Static members are initialized before the static member is accessed for
the first time, and before the static constructor, if any is called.
--------------------------------------------------------------------------------------------------------------------------

Therefore, supposing that member b is initialized only in the Init()
call, we have :
b=null before Init called.
This said, there's something strange in Init() routine :
I would say :
if (b==null)
{
b=new B();
}

May 22 '06 #2
Of course I misspelled Init routine - in real code it checks for equality to
null, as you wrote.

Regarding your quote:
Static members are initialized before the static member is accessed for
the first time, and before the static constructor, if any is called.

The big question: to WHAT they are initialized. I understand that all
unassigned reference types are initialized to null. And when I run this code
in debugger, I see that unless I explicitly assign them to null, they are
assigned to default constructor. And only when assembly is loaded in Web
project. I wonder why.

Vagif
"olrt" <ol**@ifrance.com> wrote in message
news:11**********************@u72g2000cwu.googlegr oups.com...
ms-help://MS.VSExpressCC.v80/MS.NETFramework.v20.en/dv_csref/html/235614b5-1371-4dbd-9abd-b406a8b0298b.htm
:

--------------------------------------------------------------------------------------------------------------------------
Static members are initialized before the static member is accessed for
the first time, and before the static constructor, if any is called.
--------------------------------------------------------------------------------------------------------------------------

Therefore, supposing that member b is initialized only in the Init()
call, we have :
b=null before Init called.
This said, there's something strange in Init() routine :
I would say :
if (b==null)
{
b=new B();
}

May 22 '06 #3
I wrote a simple test application with your classes A and B.
I declared
static B b
instead of
static B b=null;

When I test the application, I have b=null before Init().

So static variables are initialized to null by default...

Regards.

May 22 '06 #4
only in vb.net are un-initialozed variables set to null. in c# you need to
do it yourself, as the compiler doesn't emit and initalation code you don't
include. its a bug in your code. its just luck it worked in 1.1

-- bruce (sqlwork.com)

"olrt" <ol**@ifrance.com> wrote in message
news:11**********************@u72g2000cwu.googlegr oups.com...
I wrote a simple test application with your classes A and B.
I declared
static B b
instead of
static B b=null;

When I test the application, I have b=null before Init().

So static variables are initialized to null by default...

Regards.

May 22 '06 #5
Thanks for the effort. I also get this behavior in non-Web apps, and in some
Web apps. I will try to extract some code that demonstrates the weird
behaviour. If I manage, I will let post it.

Vagif

"olrt" <ol**@ifrance.com> wrote in message
news:11**********************@u72g2000cwu.googlegr oups.com...
I wrote a simple test application with your classes A and B.
I declared
static B b
instead of
static B b=null;

When I test the application, I have b=null before Init().

So static variables are initialized to null by default...

Regards.

May 22 '06 #6
Hmmm, if they are not implicitly set to null, then what value they are set
to? There must be deterministic algrorithm. And why then compiler does not
give an error? It gives an error if I try to use unassigned automatic
variable, shouldn't it do the same with member variables then?

Vagif

"bruce barker (sqlwork.com)" <b_*************************@sqlwork.com> wrote
in message news:%2****************@TK2MSFTNGP04.phx.gbl...
only in vb.net are un-initialozed variables set to null. in c# you need to
do it yourself, as the compiler doesn't emit and initalation code you
don't include. its a bug in your code. its just luck it worked in 1.1

-- bruce (sqlwork.com)

"olrt" <ol**@ifrance.com> wrote in message
news:11**********************@u72g2000cwu.googlegr oups.com...
I wrote a simple test application with your classes A and B.
I declared
static B b
instead of
static B b=null;

When I test the application, I have b=null before Init().

So static variables are initialized to null by default...

Regards.


May 23 '06 #7
I investigated further. Here is what happens.

I made a simlpe Web site consisting of an empty page. The page C# code file
looks like this:

using System;
using System.Web;

namespace StaticMemberTest
{
public class Test
{
static int A
{
get { _Default.a++; return _Default.a; }
}
}

public partial class _Default : System.Web.UI.Page
{
internal static int a = 0;

protected void Page_Load(object sender, EventArgs e)
{
Response.Write("A = " + a.ToString());
}
}
}

Steps to reproduce the problem:

1. Set the breakpoint within Page_Load
2. Start the debugger.
3. Once the breakpoint is reached, go to Watch window and type "Test.A".
4. This will trigger evaluation of Test.A getter which will increment the
value of _Default.a static variable.
5. Continue the execution, and you will see "A = 1" on the page.
6. Close the browser. Start the page now not in debug mode. It will still
display "A = 1".
7. Try to restart IIS and run the page without debugger. Still "A = 1".
8. If you try to run it in a debugger and evaluate Test.A, it will display
"A = 2". Etc.

The only way to reset the value of a static variable _Default.a is to change
the page source code, so Visual Studio will detect the change and rebuild
the page. Then _Default.a will be reset to 0.

I understand that assembly is compiled once and cached. But it looks that
also the state of static variables is stored. And this looks dangerous, and
this is not how it worked in .NET 1.1.

Vagif Abilov
Oslo Norway
May 23 '06 #8
Hello,
I'm afraid I have to disagree with you.
I'm using Visual C# 2005 Express and my test project compiles with no
error/warning.
So I persist to say that (with C# default compiling options) the
compiler initializes static members to null if not initialized
otherwise.

May 23 '06 #9
I wrote a test project like yours and :

- when I restart IIS, I stop the debugger then reconnect it (if not the
debugger doesn't stop on the breakpoint).
I have : A = 0 after IIS restart...

By the way, what kind of isolation does your application have ?
- Is it InProcess (IIS)
- Is it Medium
- Is it OutOfProcess

Mine is "Medium"...

May 23 '06 #10
I repeated the test with isolation "OutOfProcess" and same results...

May 23 '06 #11
You are right. This is what C# specs say:

The initial value of a static variable is the default value (Section 5.2) of
the variable's type.
For purposes of definite assignment checking, a static variable is
considered initially assigned.
The default value of a variable depends on the type of the variable and is
determined as follows:

· For a variable of a value-type, the default value is the same
as the value computed by the value-type's default constructor (Section
4.1.1).

· For a variable of a reference-type, the default value is
null.
"olrt" <ol**@ifrance.com> wrote in message
news:11**********************@i39g2000cwa.googlegr oups.com...
Hello,
I'm afraid I have to disagree with you.
I'm using Visual C# 2005 Express and my test project compiles with no
error/warning.
So I persist to say that (with C# default compiling options) the
compiler initializes static members to null if not initialized
otherwise.

May 23 '06 #12
I was using it with VS 2005 built-in Web hosting process, so it was not IIS
that controlled my site.

BTW, I received another suggestion to mark variables as ThreadStatic. This
way they will be allocated per thread. But this is probably not what I want.

"olrt" <ol**@ifrance.com> wrote in message
news:11**********************@j33g2000cwa.googlegr oups.com...
I wrote a test project like yours and :

- when I restart IIS, I stop the debugger then reconnect it (if not the
debugger doesn't stop on the breakpoint).
I have : A = 0 after IIS restart...

By the way, what kind of isolation does your application have ?
- Is it InProcess (IIS)
- Is it Medium
- Is it OutOfProcess

Mine is "Medium"...

May 23 '06 #13
Repeated the test with ASP.NET Built-in development server and no
difference with the test under IIS...

May 23 '06 #14
This is weird, because I have it now reproducible on several machines. Did
you follow all steps I described (including watch window)? In watch window
you had to see "A = 1". You mean that it got reset to "A = 0" next time you
run it?

Vagif

"olrt" <ol**@ifrance.com> wrote in message
news:11*********************@g10g2000cwb.googlegro ups.com...
Repeated the test with ASP.NET Built-in development server and no
difference with the test under IIS...

May 23 '06 #15
1°) Start the debugger
2°) The debugger breaks on Page_Load
3°) ? Test.A : returns 1
4°) Continue
5°) Page prints : 1
6°) Stop the Web dev server.
7°) Start the debugger
8°) The debugger breaks on Page_Load
9°) Continue
10°) Page prints : 0

May 23 '06 #16
As I said before, static variables are not very useful in a web application.

What is it that you want to accomplish using static variables?
Vagif Abilov wrote:
I was using it with VS 2005 built-in Web hosting process, so it was not IIS
that controlled my site.

BTW, I received another suggestion to mark variables as ThreadStatic. This
way they will be allocated per thread. But this is probably not what I want.

"olrt" <ol**@ifrance.com> wrote in message
news:11**********************@j33g2000cwa.googlegr oups.com...
I wrote a test project like yours and :

- when I restart IIS, I stop the debugger then reconnect it (if not the
debugger doesn't stop on the breakpoint).
I have : A = 0 after IIS restart...

By the way, what kind of isolation does your application have ?
- Is it InProcess (IIS)
- Is it Medium
- Is it OutOfProcess

Mine is "Medium"...


May 23 '06 #17
Ah ?
Could you elaborate please ?

May 23 '06 #18
Correct. If I stop Web dev server it will then print 0. But if not, then it
will keep value of 1 unless I recompile the app. I expected static data to
be recycled at least when all sessions were closed.

Vagif

"olrt" <ol**@ifrance.com> wrote in message
news:11**********************@i40g2000cwc.googlegr oups.com...
1°) Start the debugger
2°) The debugger breaks on Page_Load
3°) ? Test.A : returns 1
4°) Continue
5°) Page prints : 1
6°) Stop the Web dev server.
7°) Start the debugger
8°) The debugger breaks on Page_Load
9°) Continue
10°) Page prints : 0
May 23 '06 #19
I don't have much of what I couldn't turn into non-static data. Just few
class instances that did not change and were cached for performance reasons.
I discovered this when one of those instance were incorrectly initialized, I
updated its configuration and expected it to be renewed. It did not until I
recycled the ASP.NET hosting process.

I guess the lesson is to avoid singletons in Web applications.

Vagif

"Göran Andersson" <gu***@guffa.com> wrote in message
news:%2***************@TK2MSFTNGP03.phx.gbl...
As I said before, static variables are not very useful in a web
application.

What is it that you want to accomplish using static variables?
Vagif Abilov wrote:
I was using it with VS 2005 built-in Web hosting process, so it was not
IIS that controlled my site.

BTW, I received another suggestion to mark variables as ThreadStatic.
This way they will be allocated per thread. But this is probably not what
I want.

"olrt" <ol**@ifrance.com> wrote in message
news:11**********************@j33g2000cwa.googlegr oups.com...
I wrote a test project like yours and :

- when I restart IIS, I stop the debugger then reconnect it (if not the
debugger doesn't stop on the breakpoint).
I have : A = 0 after IIS restart...

By the way, what kind of isolation does your application have ?
- Is it InProcess (IIS)
- Is it Medium
- Is it OutOfProcess

Mine is "Medium"...


May 23 '06 #20
I'm still convinced that the behaviour of ASP.NET in respect to code
invoking static members is coherent with the documentation of the
static C# keyword...
By the way, you can also exploit ASP.NET "Application" context object
to store objects that are shared between all users of your Web
application...
But you'll have to ensure that all calls to methods of the object leave
it in a coherent state (that is you'll have to synchronize the threads
that call the methods which affect the state of the object).
I think that's what you did with your static methods...

May 23 '06 #21
Statics are per app domains. App domains are per process. With Web
Farms and/or Web Gardens you'll have multiple app domains and hence the
potential for multiple static classes and/or values per AD. In
addition, static classes have changed between 1.x and 2.0. You should
read up on singletons for the correct implemantion. Happy hacking...

May 24 '06 #22
Excuse me but if you read the initial post, there's no mention of such
an environment.
But maybe Vagif could describe his environment... ?

May 24 '06 #23

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

Similar topics

5
15338
by: Chris | last post by:
Hi I have a scenario where I've created another AppDomain to dynamically load a DLL(s) into. In this newly loaded DLL I want to call a static method on a class. The problem arise is that I have...
33
3314
by: Chris Capel | last post by:
What is the rationale behind the decision not to allow abstract static class members? It doesn't seem like it's a logically contradictory concept, or that the implementation would be difficult or...
2
2643
by: superseed | last post by:
Hi, I'm pretty new to C#, and I'm quite stuck on the following problem. I would like to add to my application a Windows.Form (singleton) on which I could display a message of one of the...
11
3797
by: Kevin Prichard | last post by:
Hi all, I've recently been following the object-oriented techiques discussed here and have been testing them for use in a web application. There is problem that I'd like to discuss with you...
14
33228
by: Dave Booker | last post by:
It looks like the language is trying to prevent me from doing this sort of thing. Nevertheless, the following compiles, and I'd like to know why it doesn't work the way it should: public class...
7
8204
by: Jo | last post by:
Hi, How can i differentiate between static and dynamic allocated objects? For example: void SomeFunction1() { CObject *objectp = new CObject; CObject object;
15
34578
by: archana | last post by:
Hi all, can anyone tell me differene between public static and private static method. how they are allocated and access?. thanks in advance.
3
22563
by: =?Utf-8?B?SmltSGVhdmV5?= | last post by:
I want to invoke a static method of a static class using a TEXT variable which has the namespace and class name which should be executed. I looked at the "CreateInstance" method, but this looks...
8
5689
by: aarklon | last post by:
Hi all, see:- http://linuxgazette.net/issue51/pramode.html
0
7257
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7157
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...
0
7379
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,...
0
7535
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7098
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5682
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,...
0
3232
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...
0
3221
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1591
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 ...

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.