.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

private static member variable is not instantiated until it is first referenced?

Posted By:      Posted Date: October 22, 2010    Points: 0   Category :.NET Framework

I expected that all static variables and initialization blocks are executed when class is accessed first time. But, when reading http://msdn.microsoft.com/en-us/library/ff650316.aspx, I found the following statement:

"Because the Singleton instance is referenced by a private static member variable, the instantiation does not occur until the class is first referenced by a call to the Instance property."

I searched MSDN website and got confused even more:

"The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor."


Can anyone please refer me to detailed description of initialization process.






View Complete Post

More Related Resource Links

Sharing of Non-Static member variables of a class using .NET Remoting

This kind of weird. I am trying to host an object of a class X (a class library class). This is a SAO and I have set the WellKnownMode as Singleton in the server configuration. <wellknown mode="Singleton" When multiple clients fetch the instance of the class X they can share the static member variables. Any changes made to the static variables are visible to each other. The problem is with the non-static member variables of the class. Each instance is having a local copy of the non-static variables. Why should that happen in case of a Singleton mode? Am I missing something for which this is happening? Any help will be appreciated.  A for apple, B for boy, C for c++

Cache vs Static variable


Well, I know the big difference, but one thing is confusing me. Cache works only on a single machine on webfarm and to make it globally we use Velocity or memcache.

So is static does same, or is it already work globally ?


Cache["someid"] = "value"; //this will only work on single machine cache,

static string abc = "value"; // will this work on single machine or globally ? 

static time variable


Hi all,

I'm not really much of a programmer but I've been working on something in visual web developer and VB...

I've got an asp.net page with a fileupload control and two buttons. One button is used to upload the file and then the other button does something else which involves accessing the file name of the uploaded file.

This is straight forward enough if you just use static text but I wanted to create a unique file name for the upload so thought about using a date/time value for this and delcaring it as a variable?

This works great but how does the second button then access this file name? If I use the same variable name declared earlier it just generates a new one especially if mins and secs were used?

I'm not sure if that makes sense? But I'm basically wanting to create a unique file name for the uploaded file and then store that in a variable so it can be accessed by the other button? Without the variable constantly updating to a new ID?

Thanks for any help.

Accessing static variable in global.ashx file


Hi All ,

I want to access the static variable in my global.ashx file  I am using classname.variable name for accessing the variable but the variable name dose not appear.Can someone tell me how to access static varialbe in *.ashx file.

Can't access static member in code, but while running "QuickWatch" sees it. What the?


HI everyone,

I'm working with two Visual Studio 2005 solutions.

The first is "WinX" with a project called "WinX". There's a class in the WinX project in a namespace called "WinX" with a class "frmMain". frmMain is the main form for the application, and is always open.

We have this static member declared as so in frmMain:

public static bool IsfrmViewTaskFormOpen = false;

Enter our second solution "TasksProcessScreen" with a project "TasksProcessScreen" which has a namespace of "TasksProcessScreen" with a public class frmViewTask. The solution has the "WinX" project added as a project.

In frmViewTask, there is the following code:

private void frmViewTask_FormClosed(object sender, FormClosedEventArgs e)


   //This does NOT compile! It says "WinX" does not exists in the current context.

   if (WinX.frmMain.IsfrmViewTaskFormOpen)

Application variable or static class for global string?


I need to keep a global variable throughout the whole time the user is at my site, but do I use Application or a static class? The string variable should store a region name and my site makes a few changes depending on which region that has been set.

I read that Application was mainly for classic ASP, but I also read that a static class cannot be instantiated at runtime (e.g. when the user has logged in).

So, have I got something wrong here and which solution do I use?



Enforce member on type (abstract static)


Hello all,

Already did some research but i'd like some verification.

What I want to achieve: I have a abstract BaseClass wich will have SubClasses. What I want is to give the SubClasses a name, but not per object but per type. So I was thinking a abstract static string in BaseClass, but ofcourse, no can do. And, static is not accepted in Interfaces. I want to call the name of the type without making a instance.

Little example:

public abstract BaseClass 
 public abstract string ClassName; //problem: still need a instance

public SubClass1 
 public override string ClassName = "SubClassNumberOne";

public SubClass2 
 public override string ClassName = "SubClassNumberTwo";

This way I can call the name of a type without a instance. But this is not possible is it?

Does anyone know a different solution? I was just thinking about a struct, but I cant enforce that either can I?


Derived class and try call private/protected base member


Hi, i often write a class derived from built in .NET class.

Unfortunately, there are many methods/properties/fields that marked private/internal (i decompile using net reflector),
so i call the members using reflection (get method/field/property, invoke method).

The reflection is damn slow!

Anyone knows how to solve my problem? Or have alternate method instead of using reflection?


*** the sealed, internal, and private keywords is enemy for me, it prevents the developer for derivering a class/type.

Static Class for Beginners

In general, the members of a class can be accessed by instance of that class when they are in public, but there comes a situation to access or call members of a class without an instance and this can be achieved by declaring them as static

Local variable scoping in C#

In my previous post, Compiler-generated scopes for local variable declarations, I briefly touched on the issue of multiple meanings applied to the same name. In this post, I'll aim to flush out the compiler's rules with regards to binding names in their local scopes.

Compiler-generated scopes for local variable declarations

I was tasked with understanding and fixing a bug on error reporting with foreach iteration variables the other day, and it got me thinking about local variable scoping rules in C# in general. First, the bug.

abstract away the source of the connection string using a class with a static property.

ASP.NET provides a configuration system we can use to keep our applications flexible at runtime. In this article we will examine some tips and best practices for using the configuration system for the best results.

The element of a web.config file is a place to store connection strings, server names, file paths, and other miscellaneous settings needed by an application to perform work. The items inside appSettings are items that need to be configurable depending upon the environment, for instance, any database connection strings will change as you move your application from a testing and staging server into production.

Let's abstract away the source of the connection string using a class with a static property.

Retrieving a variable from a previous page



I'm looking to have a search page where a user will select an item from a listview, then then taken to another page that wil display data based on their original selection.

A user will type in a string and be presented with a list of usernames that are like that string, when they select a user name who's profile they would like to view I would like the page that they're taken to, to be that users profile.

How would I transfer the variable from the search page to the profile page, and when I work on the profile page, how can I access that variable?


Embeb a variable number of videos


I need to provide some alternate content for my non-Flash users.

I have a directory of video files that is scanned using the DirectoryInfo() function, and I want to use the results to embed all files ending in ".mov" in QuickTime players on a web form.

How would you approach this? Right now I am using the count on the array of videos to determine how many times to repeat the embed code.  But this seems inelegant.

Is there a way to have a single QuickTime player.ascx control that gets duplicated according to the number of videos available for display?

How to take value of bound field of grid in a variable or in a textbox.


How to take value of bound field of grid in a variable or in a textbox.

 I m using this code in .aspx page for grid.

<asp:GridView ID="Grd_Mprocess" runat="server" AutoGenerateColumns="False"

                      Width="100%" AllowPaging="True"


                      AllowSorting="True" PageSize="5"  >

                 <RowStyle CssClass="odd" />


<asp:BoundField HeaderText="DOC_TYPE_PK" DataField="DOC_TYPE_PK"  Visible="true" >


  <asp:TemplateField HeaderText="DOC TYPE ID" Visible="true">  &nbs

Hidden variable has no value


I know I have a valid solution, but the js is telling me that the value in the hdnRecordSaved variable has no value!
Even when I specify in my function the following, it still tells me it has no value:
var myTextField = document.getElementById('hdnRecordSaved');

When I put the full value of the variable in (ctl00_ctl00_cphTopCenter_cphCenter_hdnRecordSaved.value), I get the correct contents back ("1"), which I set in my code behind. However, I would prefer to just put the short name in since the masterpages may change, etc. Unfortunately, I know I can get around this with VS2010, but we are using VS2008.

What am I doing wrong with the js naming conventions that can't give me the contents? Here is my below js.

<asp:Panel ID="pnlMapFields" runat="server" ScrollBars="Both" Height="430px">

<telerik:RadTreeView ID="RadTreeView1" runat="server" DataTextField="Description"

DataFieldParentID="MapFieldparentID" DataF

The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced. You must



This is frustrating, and I don't know how to solve it.

I have a strange problem. I am adding a LinqDatasource object, and set the context:

        protected void LinqDataSource_ContextCreating(object sender, LinqDataSourceContextEventArgs e)
            e.ObjectInstance = new KaruselaDataContext(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

Then I get this error:
The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Linq, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089'.


On web.config I already have this:
<add assembly="System.Data.Linq, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>

NOTE: The datacontext is in a different project (DLL proect) where I added a refernce to System.Data.Linq.

is there another way adding a refernce to a web project? or only though teh web.config?


ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend