Dan Beaulieu
Dan Beaulieu

Reputation: 19954

need clarification on C# static variables

I've tried searching this but I cant find a clear answer to my question.

When can you actually alter a static variable?

From my understanding you can only change it within the static constructor. But I'm not sure, any help on this would be greatly appreciated.

Upvotes: 0

Views: 249

Answers (4)

Binesh Nambiar C
Binesh Nambiar C

Reputation: 162

Static variables can edit any where with respect to access permission. Its like non-static variable only. but having common memory(class level memory)

If you are a beginner i will give an example

class Person
{
    static int NumberOfPersons;
    string name;
    int age;
}

In this above example individual memory is required for each person.

But NumberOfPersons case is different. When new person comes you will be simply adding 1 to NumberOfPersons. If you are not keeping a common class level variable for this you will have lots of head ache like you need to go to each object increment one, memory waste etc.

But in case of Name and Age individual memories are required. One persons name shouldn't over written by another object. So that is non-static

In theory- Static will be having common memory and loads while class loads. Non-static will allot memory when object creates

Hopes clear

Thanks & Regards Binesh Nambiar C

Upvotes: 0

John
John

Reputation: 6553

Static can be changed anywhere, it is essentially a global variable that you don't need to instantiate.

You should be very careful about using them because they can cause you many headaches and should only be used for specific reasons.

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

Upvotes: 0

Manil Liyanage
Manil Liyanage

Reputation: 255

If the Static Member Variable is not Readonly, Variable will be altered at the time of assigning the value to the variable. And it will stay during the life cycle of the application, unchanged.

Also you don't need any instance to assign a value to the variable

Upvotes: 1

ShayD
ShayD

Reputation: 930

  1. Static fields/properties can be changed anywhere - according to their visibility (public, private, internal, etc.). for example, a private static field can be changed by all instances of the class.
  2. If a variable is static, it is not a member variable, because it does not belong to a specific instance. Better call them static variables (and not static member variables)

Upvotes: 4

Related Questions