How to create and use static members by using Visual C# .NET or Visual C# 2005 (815705)



The information in this article applies to:

  • Microsoft Visual C# 2005, Express Edition
  • Microsoft Visual C# .NET (2003)
  • Microsoft Visual C# .NET (2002)

SUMMARY

This article describes how to implement static members within a class, as well as how to reference other class members from static methods and static properties.

Visual C# .NET or Visual C# 2005 provides the necessary language features to enable object-oriented programming. Central to this approach is the class that implements its functionality using methods (functions and procedures), properties, and fields. These are referred to as members.

Static members are not associated with a specific instance of a class. To call a static member, you qualify the static member with the class name. Because static members are not associated with object instances, they do not have access to non-static members (which are accessed through "this," which represents the current object instance).

Non-static members are called instance members because they are associated with individual object instances. Think of static members as belonging to the class and instance members belonging to instances of the class (that is, objects).
back to the top

Requirements


This article assumes that you are familiar with the following topics:
  • Object-oriented concepts
  • Creating classes in Visual C# .NET or in Visual C# 2005
  • Visual C# .NET or Visual C# 2005 properties

back to the top

Create a New Visual C# .NET or Visual C# 2005 Project and Class


The code in this project demonstrates how to implement static methods, static properties, and instance methods. Some of the following code contains deliberate errors to illustrate key points about how to access other members from static members. As a result, the code compiles only after you comment out or remove the lines that cause the error.
  1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
  2. On the File menu, point to New, and then click Project.
  3. Under Project types, select Visual C# Projects. Under Templates, select Console Application.

    Note In Visual Studio 2005, Visual C# Projects is changed to Visual C#.
  4. In the Name box, type staticMethod, and then click OK. By default, Class1 is created.
  5. On the Project menu, click Add Class, and then click Open. Class2 is created.
  6. Add the following two private instance fields to the Class2.
    //Instance variables
    private int  myInt ;
    private string myStr; 
  7. Use the static keyword to add the following two private static fields to the Class2.
    //Class variables
    private static int  staticInt; 
    private static string staticPropValue;
    
  8. Save the project.
back to the top

Create the Instance Method, Static Method, and Static Property

  1. Add the following instance method named mySub to the Class2:
    //An instance method
    public void mySub()
    {
          myInt = 1;       // Ok, same as this.myInt = 1
          staticInt = 1;   // Ok, same as Class2.staticInt = 1
    }
    
  2. Use the static keyword to add the following static method named staticSub to the Class2.

    Note Remember that static methods can only access other static members and cannot access instance members.
    //A class method
    public static void staticSub()
    {
         myInt = 1;       // Error, cannot access this.myInt
         staticInt = 1 ;  // Ok, same as Class2.staticInt = 1
    }
  3. Use the static keyword to add the following static, read-write string property named staticProp to the Class2.
    //A class property
    public static string staticProp
    {
          get
          {
               //Can refer only to static variables
               return myStr;            //Error, cannot access this.myStr
               return staticPropValue;  //Ok, same as Return Class2.staticPropValue
          }
          set
          {
               //Can refer  only to static variables
               myStr = value;              //Error, cannot access this.myStr
               staticPropValue = value;    //Ok, same as Class2.staticPropValue = Value		
          }
    }
  4. Save Class2.cs.
back to the top

Compile the Class

  1. On the Build menu, click Build Solution. Notice the error messages that appear in the Task List window.
  2. The first error occurs at the following line of code in the staticSub method:
    myInt = 1; 
    staticSub is a static member. Therefore, staticSub is associated with the class and can access only static members. You cannot use the this keyword here because instance members are not accessible from in a static member. Remove the offending line of code.
  3. The second error occurs at the following line of code in the staticProp property:
     return myStr;        //Error, cannot access this.myStr
    Remove the offending line of code.
  4. The last error occurs at the following line of code in the staticProp property:
     myStr = value;              //Error, cannot access this.myStr
    Remove the offending line of code.
  5. Rebuild the class.
back to the top

Create the Test Module

  1. Open Class1.cs.
  2. Add the following code (it uses the class name to reference Class2 members) to the Main procedure:
    string outStr;
    //Use class to refer to members
    Class2.staticSub();              //Ok
    Class2.staticProp = "Class";     //Ok
    outStr = Class2.staticProp ;     //Ok
    Class2.mySub();               //Error only available to an instance
  3. Save the project.
back to the top

Compile the Test Module

  1. On the Build menu, click Build Solution.
  2. Notice that an error message appears in the Task List window. This error occurs in the following line of code:
    Class2.mySub();               //Error only available to an instance
    mysub is an instance method and thus is only available to an instance of a Class2 object. Remove the offending line of code.
  3. Save, rebuild, and run the project.
back to the top

Troubleshoot

  • You can only invoke instance methods and properties on an object instance. Within the instance method, you can refer both instance and static members.
  • To invoke static members, you can use only the class itself. Within the static member, you can only reference other static members.
  • You cannot refer to an instance member of a class from within a static method. The this keyword is valid only within an instance method.
back to the top

REFERENCES

For additional information, click the following article number to view the article in the Microsoft Knowledge Base:

319265 HOW TO: Define and Use Properties in Visual C# .NET

back to the top

Modification Type:MajorLast Reviewed:1/18/2006
Keywords:kbProperties kbHOWTOmaster KB815705 kbAudDeveloper