#46 – There Is Only One Copy of Static Data

With instance data members of a class, there is a unique set of data that exists for each instance of the class that you create.  However, for static data members, there is always just one copy of the static data for that class.  Since the data is associated with no particular instance of the class, all references to that static data work with the same copy.

 // Create two new Person objects--two sets of instance data.
 Person p1 = new Person("Sean", 46);
 Person p2 = new Person("Fred", 28);

 // Change static data--one copy for entire Person class
 Person.Motto = "It's good to be human";
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #46 – There Is Only One Copy of Static Data

  1. Pingback: #1,044 – How Static Data Behaves in Generic Types | 2,000 Things You Should Know About C#

  2. Bil says:

    I know there is a response on how static data behaves in Generic but posting reply here. in case of generic class the there will be as many copies of a class as many generics version you have. check below code and result.

    using System;
    namespace ConsoleApp1
    {
    public class myGenericClass
    {
    public static int staticMember;
    }
    class Program
    {
    static void Main(string[] args)
    {
    myGenericClass.staticMember = 5;
    myGenericClass.staticMember = 3;
    Console.WriteLine(myGenericClass.staticMember);
    Console.WriteLine(myGenericClass.staticMember);
    Console.WriteLine(myGenericClass.staticMember);

    Console.ReadKey();
    }
    }
    }
    ===========
    Result:
    5
    3
    0

    • Sean says:

      The code that you posted does not behave as you describe. In your example, your “myGenericClass” has a static member that is accessed three times. Each Console.WriteLine() will output the same value–3, the last value that you set.

      Had “myGenericClass” actually been a generic class and then had you constructed it with different type arguments, then you’d have different copies of the static member. But that would be because you actually were dealing with different classes, i.e. different constructed types. Keep in mind that a “generic class” is just a template for a class. It doesn’t actually become an class until you construct it by providing any required type parameters. At that point, the constructed type is a class and therefore follows the rule that there is only one copy of each static member.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: