C#
  Home arrow C# arrow C# - Static Members
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

C# - Static Members
By: Rajesh V S
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 24
    2003-04-08

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    This article will help you understand the concepts relating to static members in C#. Once you have read this article you'll be able you utilise the static member properties.

    A C# class can contain both static and non-static members. When we declare a member with the help of the keyword static, it becomes a static member. A static member belongs to the class rather than to the objects of the class. Hence static members are also known as class members and non-static members are known as instance members.

    In C#, data fields, member functions, properties and events can be declared either as static or non-static. Remember that indexers in C# can't declared as static.

    Static Fields

    Static fields can be declared as follows by using the keyword static.

     class MyClass
    {
    public static int x;
    public static int y = 20;
    }
    When we declare a static field inside a class, it can be initialized with a value as shown above. All un-initialized static fields automatically get initialized to their default values when the class is loaded first time.

    For example

    // C#:static & non-static
    // Author: rajeshvs@msn.com
    using System;
    class MyClass
    {
    public static int x = 20;
    public static int y;
    public static int z = 25;
    public MyClass(int i)
    {
    x = i;
    y = i;
    z = i;
    }
    }
    class MyClient
    {
    public static void Main()
    {
    Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);
    MyClass mc = new MyClass(25);
    Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);
    }
    }
    The C# provides a special type of constructor known as static constructor to initialize the static data members when the class is loaded at first. Remember that, just like any other static member functions, static constructors can't access non-static data members directly.

    The name of a static constructor must be the name of the class and even they don't have any return type. The keyword static is used to differentiate the static constructor from the normal constructors. The static constructor can't take any arguments. That means there is only one form of static constructor, without any arguments. In other way it is not possible to overload a static constructor.

    We can't use any access modifiers along with a static constructor.

    // C# static constructor
    // Author: rajeshvs@msn.com
    using System;
    class MyClass
    {
    public static int x;
    public static int y;
    static MyClass ()
    {
    x = 100;
    Y = 200;
    }
    }
    class MyClient
    {
    public static void Main()
    {
    Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y);
    }
    }
    

    Note that static constructor is called when the class is loaded at the first time. However we can't predict the exact time and order of static constructor execution. They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class is called.

    Static Member Functions

    Inside a C# class, member functions can also be declared as static. But a static member function can access only other static members. They can access non-static members only through an instance of the class.

    We can invoke a static member only through the name of the class. In C#, static members can't invoked through an object of the class as like in C++ or JAVA.

    // C#:static & non-static
    // Author: rajeshvs@msn.com
    using System;
    class MyClass
    {
    private static int x = 20;
    private static int y = 40;
    public static void Method()
    {
    Console.WriteLine("{0},{1}",x,y); 
    }
    }
    class MyClient
    {
    public static void Main()
    {
    MyClass.Method();
    }
    }
    

    Static Properties

    The properties also in C# can be declared as static. The static properties are accessing using the class name. A concrete example is shown below.

    // C#:static & non-static
    // Author: rajeshvs@msn.com
    using System;
    class MyClass
    {
    public static int X
    {
    get
    {
    Console.Write("GET");
    return 10;
    }
    set
    {
    Console.Write("SET");
    }
    }
    }
    class MyClient
    {
    public static void Main()
    {
    MyClass.X = 20; // calls setter displays SET
    int val = MyClass.X;// calls getter displays GET
    }
    }

    Static Indexers

    In C# there is no concept of static indexers, even though static properties are there.

    Static Members & Inheritance

    A derived class can inherit a static member. The example is shown below.

    // C#:static 
    // Author: rajeshvs@msn.com
    using System;
    class MyBase
    {
    public static int x = 25;
    public static void Method()
    {
    Console.WriteLine("Base static method"); 
    }
    }
    class MyClass : MyBase
    {
    }
    class MyClient
    {
    public static void Main()
    {
    MyClass.Method(); // Displays 'Base static method'
    Console.WriteLine(MyClass.x);// Displays 25
    }
    }
    

    But a static member in C# can't be marked as override, virtual or abstract. However it is possible to hide a base class static method in a derived class by using the keyword new.

    An example is shown below.

    // C#:static & non-static
    // Author: rajeshvs@msn.com
    using System;
    class MyBase
    {
    public static int x = 25;
    public static void Method()
    {
    Console.WriteLine("Base static method"); 
    }
    }
    class MyClass : MyBase
    {
    public new static int x = 50;
    public new static void Method()
    {
    Console.WriteLine("Derived static method"); 
    }
    }
    class MyClient
    {
    public static void Main()
    {
    MyClass.Method(); // Displays 'Derived static method'
    Console.WriteLine(MyClass.x);// Displays 50
    }
    }
    

    Finally remember that it is not possible to use this to reference static methods.

    Conclusion

    I've given you enough information to use static members in your code and shown you some examples. The feedback is always welcome. Feel free to contact me for any questions or comments you may have about this article at rajeshvs@msn.com


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More C# Articles
    More By Rajesh V S

     

    IBM® developerWorks developerWorks - FREE Tools!


    Be the first to hear about i5/OS V6R1!

    Hold your calendar on January 30, 2008 for this free webcast on the new i5/OS. Rational's Enterprise Modernization products will be discussed at this webcast as they help to drive the application development environment for this new System i OS. <br />And learn how i5/OS will take you to the next step of efficient, resilient business processing. You will hear about the new i5/OS capabilities as it will be the most significant i5/OS release in years. If you cannot join the webcast on 1/30/08 you can still use this link to listen to the replay.<br />
    FREE! Go There Now!


    NEW! IBM – Taking Web 2.0 to Work

    David Barnes, Lead Evangelist for IBM Emerging Internet Technologies will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! A Layered approach to delivering security-rich Web applications

    As businesses grow increasingly dependent upon Web applications to provide services to customers, employees and partners, these complex applications become more difficult to secure. Although traditional security solutions protect Internet infrastructure layers, they do not guard against HTTP and HTML attacks. Many organizations that conduct security testing still deploy applications that allow attackers to manipulate their logic and wreak havoc on their business. To mitigate this risk, development and delivery teams must address Web application security throughout the lifecycle, addressing the many layers detailed in this paper.
    FREE! Go There Now!


    NEW! Accelerating Software Innovation on i on Power Systems

    Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, for an overview of Rational’s new software offerings and resources to help modernize and accelerate software innovation on i on Power Systems – while ensuring past application investments are protected and continue to grow. Learn how these solutions are helping customers extend their core i5/OS solutions toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time.
    FREE! Go There Now!


    NEW! IBM Rational AppScan Standard Edition V7.7

    Secure your Web applications with IBM Rational AppScan Standard Edition V7.7, previously known as Watchfire AppScan. This Web application security testing tool automates vulnerability assessments and scans and tests for common Web application vulnerabilities. Visit IBM developerWorks to download a free trial of IBM Rational AppScan Standard Edition V7.7.
    FREE! Go There Now!


    NEW! Info 2.0: Harnessing the power of Web 2.0 and Enterprise Mashups

    Listen to this webcast to get an overview of Info 2.0 and a technical demo of how to quickly build an enterprise mashup. IBM's Info 2.0 technology leverages emerging Web 2.0 technologies such as mashups, feeds, AJAX, and JSON in order to simplify assembly of information using feeds and services. Come learn about the technical elements of Info 2.0 including the Feed Generation framework, Mashup Engine, and mashup assembly components. Learn how to pull information from databases, departmental information, and the Web to create mashups critical to your company’s success. We will also discuss best practices to help you get started.
    FREE! Go There Now!


    NEW! Rational 'Talks to You' Teleconference Series

    This Fall, IBM Rational talks to you directly through a special teleconference series giving you access to the best minds in IBM Rational - product experts and market thought leaders who will answer your questions during these pre-scheduled telephone conference calls. Register today!
    FREE! Go There Now!


    NEW! Rational Talks to You: Grady Booch on Architecture

    Join this Rational Talks to You teleconference on November 29 at 1:00 pm ET to participate in an interactive discusssion with Grady Booch around architecture and reuse. Get your questions answered!
    FREE! Go There Now!


    NEW! Try the IBM SOA Sandbox for Connectivity

    Visit IBM developerWorks to try the IBM SOA Sandbox for connectivity. The SOA Sandbox for connectivity provides a trial environment with the tooling and components to help you explore how to effectively connect your infrastructure and integrate all of the people, processes and information in your company. Use the hosted sandbox to explore SOA techniques that streamline connecting existing IT assets together, as well as learn how to connect them to new business logic.
    FREE! Go There Now!


    NEW! Webcast: Accelerating Software Innovation with System z

    Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, where he will overview Rational’s new offerings and programs to help customers accelerate software innovation on System z. He will discuss how these solutions help organizations extend their core business processes toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    C# ARTICLES

    - Introduction to Objects and Classes in C#, P...
    - Visual C#.NET, Part 1: Introduction to Progr...
    - C# - An Introduction
    - Hotmail Exposed: Access Hotmail using C#
    - Razor Sharp C#
    - Introduction to Objects and Classes in C#
    - Making Your Code CLS Compliant
    - Programming with MySQL and .NET Technologies
    - Socket Programming in C# - Part II
    - Socket Programming in C# - Part I
    - Creational Patterns in C#
    - Type Conversions
    - Creating Custom Delegates and Events in C#
    - Inheritance and Polymorphism
    - Understanding Properties in C#







    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 7 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek