need clarification on C# static variables - c#

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.

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.
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)

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

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?

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

Related

C# question on a method signature of a class [duplicate]

I am really confused with the real meaning of the static keyword in C#. I have gone through different articles on internet but none of them are really helping me to understand it's meaning and other sources are not trusted. I know Stack Overflow has some brilliant minds who can help me understand the real meaning of static like
When they get initialized.
static methods, properties, classes and constructors
Static vs readonly vs constant
In short, static effectively means "associated with a type instead of any one instance of the type". So there's one set of static variables for a type (within an AppDomain) whether you have 0 instances or a million; you don't need an instance to access a static member, etc.
The exact point of initialization of static variables depends on whether there's also a static constructor or not, but very broadly speaking it's "once, usually before anything significant happens in the class". (See this blog post for a more detailed description.)
While readonly fields can be either static or instance (i.e. related to the type or related to an instance of the type), const values are always implicitly static (they're compile-time constants, so it wouldn't make sense to have one copy per instance).
You may sometimes see static being described as "shared between all instances of a type" - I personally dislike that description, as it suggests that there has to be at least one instance... whereas actually, you don't need any instances in order to use a static member. I prefer to think of them as entirely separate, rather than being "shared" between instances.
I can recommend this article, it seems pretty descriptive:
Static Keyword Demystified
I would also recommend an official c# Programming Guide article which covers the various uses of the static keyword. You can go from there since there are a lot of links to different MSDN articles.: Static Classes and Static Class Members (C# Programming Guide)
A little about constant (const) and readonly:
constant or const is variable which cannot be modified,and which value is known at compile time.
readonly is very similar to constant, this cannot be modified either, the difference is that a readonly field can be modified/initialized once in the constructor. After that readonly is the same as constant.
Using examples:
constant:
const int a=10; // value cannot be modified, value is known at compile time
But what to do when we want constant field whos value is not known at compile time?
e.g const PersonClass a=new PersonClass("name"); // error
The answer is a readonly field:
readonly:
readonly PersonClass a=new PersonClass("name"); // all correct
From documentation:
The static field variable initializers of a class correspond to a
sequence of assignments that are executed in the textual order in
which they appear in the class declaration
Static members are intializeed on first access to the class and are executed in textual order.
Static methods, properties are parts of the class and not instance.
Static has nothing to do with readonly or constant. Static is a way like a member acessed, readonly and constant is way like a member stored/managed.

Is it possible to declare a global varaible and initialize it in a function? c#

public Tiles[,] tiles;
Is a global variable, an array, I dare say, the size of which is yet to be discovered. That's why I wish to initialize it inside a function. Alas, after the function is done, so is the variable. How doth one fix that?
If you wrote something like this:
public void Init()
{
tiles = new Tiles[2, 5];
}
The instantiated array still exists. Because it was stored in the tiles variable, which is in the class scope, it's lifetime is that of the object. Thus, you have nothing to worry about. Subsequently accessing the tiles field (should have been a property...) will use the object created in Init.
As an aside, that variable is not global, it is scoped to the class. Aside from statics, there is no such thing as a "global" variable in C# (and even static members are still scoped to their class, which does have a global instance).
Note
Jon Skeet's answer indicates excellent practice for initializing variables, among other things. I am primarily trying to address the misunderstanding of variable scope/lifetime in this answer.
Sounds like you just want:
private readonly Tile[,] tiles = InitializeTileArray();
...
private static readonly Tile[,] InitializeTileArray()
{
Tile[,] array = ...;
// Whatever you want here
return array;
}
Note that the method has to be static - you can't call an instance method from a field initializer. If you need to do that, you need to put the call into your constructor instead.
Note that I've made the field itself private - and readonly, which may not be appropriate for you. I would recommend always (or at least nearly always) using private fields - you can expose the data via properties and indexers.

How ref & out works across methods with local variables?

We cannot specify access modifiers for fields in a method, The reason I suspect for this is that the fields inside a method (i.e local variables) should have scope only inside that particular method so there is no need to specify the access modifiers.
class Program
{
public static void Main()
{
int Y;
Test(out Y);
}
private static void Test(out int X)
{
X = 17;
}
}
Question:
If scope of method field is within that method then how ref and out works across methods? I know they are passed by reference but how CLR can pass that variables address(reference) when its scope is limited to that particular method?
If scope of method field is within that method then how ref and out works across methods? I know they are passed by reference but how CLR can pass that variables address(reference) when its scope is limited to that particular method?
The variable address is not bound to it's scope.When you have the address, you can access the object in that address from whereever you want.This address is used whenever you make changes in the ref or out parameter. Compiler uses that to access and manipulate the actual data.So the scope has nothing to do with it.
It makes no sense to try and declare a private variable in a method . Because by default you can't acces a variable outside a method. Variables that you declare in a method are called local variables. So it wouldn't make any sense to be allowed to give it an acces modifier
These are local variables which are accessible in the method's code block (methodName{..code-block-here..}) scope only and you can't specify any other accessibility level to them - there is no sence to access them from the outside world.
Modifiers are meant to control external class access to variables.
For example, you might not want any class other than your own to access a variable, or you just want subclasses and classes in the same package to access it. Thats the job of modifiers.
A method variable, however, is not accessible by anything outside of that method, and won't live for longer than the time it takes for the method to complete, so there really no point to having modifiers inside the method. The variable access is fixed as its scope is very limited.

What does .Net do when you declare an object without an instance?

I wonder to know how the .Net Framework handles the declared but not instantiated object situation.
For example i declare an object like
DropDownList ddl;
and do nothing about it. I know that i should do something with this variable and get a warning about it, but what i don't know is the where it will be stored.
Is there a lookup table that stores the data of all declared variables? Or is there a virtual reference for every declaration?
Edit : I just wanted to know how the memory allocated for this object declaration.
Edit2 : Whether it's a local variable or not, i'm just talking about the memory allocation structure. I wonder to know where this references stored.
If ddl is a field, then the value of ddl will be null, as it is a reference type.
Any attempt to call a member on it will result in a NullReferenceException.
If it is a local variable it will simply be unassigned.
Value types will get the default(T) of their type.
The compiler itself may remove the call completely, depending on where it was declared, but this is an implementation detail.
If you are talking about a local variable then the compiler can simply optimize it out of existence since noone can be using it (if you attempted to use it without initializing the compiler would have protested with an error). In fact the .NET 4 compiler did this for me when I tested just moments ago.
If you are talking about a field in a class then it is initialized with the default value for its type as part of the object construction.
From your description, it sounds like you're talking about a local variable. When you declare a local variable in usual implementations and without any optimizations, then space is reserved for it on the stack (most probably), with a null reference as its value.
You could look into the StackFrame class if you want to inspect further (I've never used it).
The variable is stored in your assembly. It will always have it's default value null.
In release mode (compiler is set to optimize) it's optimized and it is not stored anywhere.
If you want to know more about IL and how the compiler works, wikipedia has a good article to start.
All variables are stored into a class or method. Variables declared into a class can be listed using .NET Reflection :
class Class1 { private int i; public string s; }
typeof(Class1).GetFields(BindingFlags.Instance); // returns all instance fields
typeof(Class1).GetFields(); // returns all instance public fields
typeof(Class1).GetProperties(); // returns all instance public properties
Variables declared into a method cannot be inspected with .NET Reflection mechanisms.

C# What is the difference between static and constant?

As it says. I am about to define a constant, or static, value in a program I am writing and am confused as to why you would use one or the other. As the only related question i get when asking this question deals with someone who wants to mark something as both static and constant at once I suspect I am not the only person a bit lost with these concepts.
So why would I use static and why would I use constant? What's the distinction? Are they synonymous? If so, that's cool, but if not why not? Thanks!
const is dealt with at compile time. Every reference to that constant is replaced by the constant value.
static is very different. It is a variable which exists only once but belongs to all objects of that type. It can be edited unless marked as readonly (or given a getter but no setter). If it is marked as readonly then it is essentially a constant, but it is handled at runtime, not by the compiler.
First off, they are not synonymous.
static marks a member as belonging to the type.
const means the member value cannot be changed. The value is determined at compile time and substituted wherever it appears.
For better understanding of how static is to be used, read Static Classes and Static Members.
And wouldn't you know it five minutes later I find this.
Any other comments?

Categories

Resources