Reputation: 19954
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
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
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.
Upvotes: 0
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
Reputation: 930
Upvotes: 4