Static in C# for Former VB developers

By Peter Bromberg

One of the biggest problems classic VB developers migrating to .NET and C# face is understanding STATIC. Static constructors, static data, static member functions, static properties.

To a  classic VB developer, "static" meant a variable inside a function (method) whose value remains "live" between function calls, but which is invisible outside the function. In C#, there is no such concept, because it's not necessary when you can define member fields instead.

Let's run through the concept of STATIC and explore its major uses.

In C#, whenever you declare a variable which is bound to an instance (object) of a class, your variable by default gets its own copy of all the fields in the class. So for example, if you write:

CreditCardAccountPremium cp1 = new CreditCardAccountPremium();
CreditCardAccountPremium cp2 = new CreditCardAccountPremium();
cp1.setFirstName("George");
cp2.setFirstName("Harry");

The instances cp1 and cp2 each contain their own string called FirstName. Changing the FirstName in cp2 has no effect on the value of the FirstName in cp1. However, there are some cases where you do not want this behavior. Maybe you would like to set a maximum value for a CashAdvance that is common to the entire CreditCardAccountPremium class. This would be universally applied to all instances of CreditCardAccountPremium.

We really want the "maxCashAdvance" to be stored in memory only once, no matter how many instances of the class we instantiate. To do this, we place the keyword static before the field declaration:
public class CreditCardAccountPremium
{
      private static uint maxCashAdvance = 300;
      private string FirstName;
      private string LastName;
      ....

Fields declared with the static keyword are referred to as static fields or static data., while the other fields like FirstName are called instance fields. So an instance field belongs to an object, and a static field belongs to the class as a whole. Static fields exist from the moment the assembly containing the class is loaded, and are initialized by the runtime, independent of whether you actually declare any instances of the class. Consequently, we can also have static constructors, which serve no other purpose than to assign initial values to static data:

public class CreditCardAccountSuper
{
     private static uint maxCashAdvance;
    staticCreditCardAccountSuper()
       {
           maxCashAdvance = 300;
       }

If you were to invoke a CreditCardAccountSuper.maxCashAdvance property, there is no need to assign an initial value within the Main() method; the static constructor does this automatically. Note that the static constructor in which the maxCashAdvance default value is set has the same name as the class, and cannot take any arguments.

Just as is the case with fields, you can declare methods as static provided they don't try to access instance data or any other instance methods. You might want to provide a method to allow users of the class to view the maxCashAdvance value:

public class CreditCardAccountPremium
{
      private static uint maxCashAdvance = 300;
      private string FirstName;
      private string LastName;
public static uint GetMaxCashAdvance()
     {
       return maxCashAdvance;
     }  

You access static methods and fields associated with a class differently that you access them as objects (instances of a class). Instead of specifying the name of the instance to access the method (cp1.GetMaxCashAdvance) you will specify the name of the class: CreditCardAccountPremium.GetMaxCashAdvance(). The static modifier can be used with fields, methods, properties, operators, and constructors, but cannot be used with indexers, destructors, or types.   C# trashes the whole concept of global functions, variables, and constants. Instead, you can create static class members, making your C# code not only easier to read, but less likely to cause naming and other conflicts.

Static Classes

A class can be marked static, indicating that it must be composed solely of static members and cannot be subclassed. The System.Console and System.Math classes are good examples of static classes.  Debug and Trace are static classes that provide basic logging and assertion capabilities.

Static constructors and field initialization order

Static field initializers run just before the static constructor is called. If a type has no static constructor, field initializers will execute just prior to the type being used— or anytime earlier at the whim of the runtime. (This means that the presence of a static constructor may cause field initializers to execute later in the program than they would otherwise.)

I hope this all didn't give you too much static.

Popularity  (4132 Views)
Picture
Biography - Peter Bromberg
Peter Bromberg is a C# MVP, MCP, and .NET expert who has worked in banking, financial and telephony for over 20 years. Pete focuses exclusively on the .NET Platform, and currently develops SOA and other .NET applications for a Fortune 500 clientele. Peter enjoys producing digital photo collage with Maya,playing jazz flute, the beach, and fine wines. You can view Peter's UnBlog and IttyUrl sites. Follow Microsoft MVP
Create New Account
Article Discussion: Static in C# for Former VB developers
Peter Bromberg posted at Friday, April 29, 2011 7:41 PM
reply
Tom Wilson replied to Peter Bromberg at Monday, May 30, 2011 7:08 PM
I really don't see the difference between C# and VB. In C# you use the keyword "Static".  In VB you use the keyword "Shared". 
reply
Peter Bromberg replied to Tom Wilson at Monday, May 30, 2011 7:08 PM
You are of course referring to VB.NET. I am talking about classic Visual Basic.
reply
pete rainbow replied to Peter Bromberg at Monday, May 30, 2011 7:08 PM
and it should be noted that using statics should be avoided wherever possible as it breaks the golden rules of low coupling and high cohesion in programming

it was so so bad when the GoF put the static singleton pattern example in their book and has caused chaos since

also almost impossible to unit test programs that use statics
reply