I am much confused about static variable actually i am executing below program.
class ABC
{
public static int prop { get; set; }
const int i =5;
static int j;
public ABC()
{
prop = 8;
j = 9;
Console.WriteLine("Under ABC class's constructor.");
}
public int getValue()
{
j = 6;
prop = 89;
return j;
}
}
class Program
{
static void Main(string[] args)
{
ABC obj = new ABC();
Console.WriteLine(obj.getValue());
//Console.WriteLine(ABC.j);
Console.ReadLine();
}
}
And its executing without any compile or run time error.
I have following confusions.
can we assign static variable/property inside the non static constructor?
can we assign static variable/property inside the instance method also?
If we can do assignment in above two cases for static variable/property then what is the use of static constructor?
Finally what are the locations inside a class where we can assign/initialize a static variable/property?
can we assign static variable/property inside the non static
constructor?
Yes.
can we assign static variable/property inside the instance method
also?
Yes.
If we can do assignment in above two cases for static
variable/property then what is the use of static constructor?
A static constructor is also called a type initializer. It is responsible for initializing the type it is defined in. You may use it to perform calculations that can be done upfront and are the same for all instances of that type. You'll therefore save some execution time when creating an instance because the calculation has already been done by the type initializer. Note that the type initializer runs before the type is used the first time. So you cannot deterministically tell when it actually runs. You can also not catch exceptions thrown by it because you don't actually invoke the type initializer yourself. You therefore need to be careful not to put error prone operations inside type initializers (f.e. do not do IO operations inside them).
Finally what are the locations inside a class where we can
assign/initialize a static variable/property?
From anywhere. Note that, even across threads, you can read and write to a static member from anywhere. This makes it very hard to find bugs that may occure due to a programm mutation a static somewhere in memory.
As a side note: Try to avoid having mutable static memory to keep your application simpler. If you really need to ... you should consider locking access to the static resource to prevent data races.
Related
Do both of these code blocks do the same thing?
class A {
public static int s;
A(){}
static A(){s = 100;}
}
and
class A {
public static int s=100;
A(){}
//static A(){s = 100;} do not use
}
Do they do the same thing? I think so.
No, they don't behave quite the same way. Without the static constructor, the timing of exactly when the type initializer executes is much looser - it can happen earlier or later than you'd expect.
When there's a static constructor, the type initializer executes when the type is first used in terms of any static member being accessed or any instance being created.
When there isn't a static constructor, the only guarantee is that the initializer will be executed at some point before the first access of a static field (and still exactly once). Depending on the JIT, that might mean it's executed very early (e.g. when you first execute a method which might use a member) or very late (after calling static members which don't use any fields, or after creating and using an instance).
In IL, the difference is that a type without a static constructor has the beforefieldinit flag; one with a static constructor doesn't.
The effect is the same, but the actual order of execution may be different. When there is a static constructor, static fields are initialized immediately before the constructor is called or any of the static fields are accessed. If there is no static constructor, then the field initializers can be executed at any time prior to the first usage of one of the static fields.
Since your initializers have no side-effects and cannot throw exceptions, there would not be any discernable difference in the two, barring the use of reflection or some other outside observer (e.g. debugger)
Except for some edge cases such as beforefieldinit behavior, yes, they do the same thing. In fact, the compiled IL is nearly the same in the two cases. The only difference is the presence of beforefieldinit on the one without a static constructor.
class A
{
public static int s;
A() { }
static A() { s = 100; }
}
class B
{
public static int s = 100;
B() { }
}
Compiles to...
.class private auto ansi A
extends [mscorlib]System.Object
.class private auto ansi beforefieldinit B
extends [mscorlib]System.Object
With identical method/field definitions.
According to C# in a Nutshell the static constructor is executed when you first use of the property, and the most usage of this is when you want to calculate or read some data and set to the static property (Like a password from appconfig.config). without using the static constructor you must define a Init method and call it when your application has been started.
public static void callit(ref int var)
{
var++;
}
public static void main(Object sender, EventArgs e)
{
int num=6;
callit(ref num);
Console.WriteLine(num);
}
But if here method callit() would not be a static then I had to make object of class then call it.
That's correct. Non-static methods need to be called on an instance of an object. Even if the method doesn't actually use any other members of the object, the compiler still enforces the rule that instance methods require instances. Static methods, on the other hand, do not need to be called on an instance. That's what makes them static.
Exactly because that's the whole point of static methods.
Instance methods require to know which instance of the class you call the method on.
instance.Method();
and they can then reference instance variables in the class.
Static methods, on the other hand, don't require an instance, but can't access instance variables.
class.StaticMethod();
An example of this would be:
public class ExampleClass
{
public int InstanceNumber { get; set; }
public static void HelpMe()
{
Console.WriteLine("I'm helping you.");
// can't access InstanceNumber, which is an instance member, from a static method.
}
public int Work()
{
return InstanceNumber * 10;
}
}
You could create an instance of this class to call the Work() method on that particular instance
var example = new ExampleClass();
example.InstanceNumber = 100;
example.Work();
The static keyword though, means that you don't need an instance reference to call the HelpMe() method, since it's bound to the class, and not to a particular instance of the class
ExampleClass.HelpMe();
I think MSDN explains it very well
Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.
You can find more details about this topic here
This is simply a matter of C# syntax, if I understand your question correctly. There is no ambiguity in using callit(ref num); in your example. It is known exactly what method to call, since it is a static method and there is no object attached. On the other hand, if callit was not static, the compiler would not know the object on which to call the method, since you are calling it from a static method (which has no object). So, you would need to create a new object and call the method on that object.
Of course, if neither method was static, the method call would operate on itself, and again, the object would be known so there is no problem.
Because static methods are associated with the class itself, not with a specific object instance.
Static functions work on classes.
Member functions work on instances.
And yes, you can only call a member function of an object (instance). No instance, no member.
Static methods are called on the type (or class), whereas non-static methods are called on the instance of a type i.e. object of a class.
You cannot call non-static methods or non-static variables in a static method, as there can be multiple objects (i.e. instances of the same type).
Static functions access class variables that are just as accessible by any other static functions AND instance functions. Meaning if you have a class variable called static int count, in static method static increaseCount() { count++; } increases the variable count by 1, and in static method static decreaseCount() { count--; } decreases the variable count by 1.
Therefore, both a static function and an instance function may access a static variable, but a static function MAY NOT access an instance variable.
Static functions are also called class functions.
Non static functions are also called instance functions.
Static method are independent of instance, suppose there is man class in that there is eat method which is non static and there is sleep method which is static then when you create different instance of man lets say man m1, m2. m1 and m2 share same sleep methods but different eat method. In java all static variables are stored in heap memory which is shared all object instances suppose at runtime if static variable changes then it will share on all instances of the object in our case.m1 and m2. But if you change non-static varible it will for only that object instance
m1.anStaticvariable = 1; // changes value of m2.anStaticvariable also
But
m1.nonStaticvariable = 1; //wont change m2.nonStaticvariable
Hope this helps you
Is there anyway way to prevent a class having static instances of it created in C#. I don't think there is but it could be useful. E.g just some attribute to prevent it.
something like this
[NoStaticInstances]
public class MyClass {
}
so that
public static MyClass _myClass;
would cause an error?
There's no such thing as a "static instance" - there's only a static variable, which is assigned a value. And there's no way of preventing static variables of a particular type being declared, unless you make the type itself static, which will prevent any instances being created and any variables of that type from being declared.
Imagine if your desired feature did exist... how would you expect the following code to behave?
class Test
{
static object foo;
static void Main()
{
MyClass bar = new MyClass();
foo = bar;
}
}
Which line of that would cause an error, if any? If it's the assignment, imagine this instead:
class Test
{
static object foo;
static void Main()
{
MyClass bar = new MyClass();
object tmp = bar;
foo = tmp;
}
}
In short, I don't think you're going to be able to prevent static variables holding references to instances of your class. Out of interest, why do you want to?
What you can do is the following:
public class MyClass
{
public MyClass()
{
#if DEBUG // Only run in debug mode, because of performance.
StackTrace trace = new StackTrace();
var callingMethod = trace.GetFrames()[1].GetMethod();
if (callingMethod.IsStatic &&
callingMethod.Name == ".cctor")
{
throw new InvalidOperationException(
"You naughty boy!");
}
#endif
}
}
Static fields will 'normally' be created by static constructors. What the above code does is looking at the calling method to see if it is a static constructor and if that's the case, throw an exception.
Note however, that this check is quite fragile and smart users can easily work around this by refactoring the creation of this method to another method. In other words, I agree with every body else that there is no good way to do this.
Such a restriction would not make sense.
What if you write
static object something = new YourClass();
Not really, there is no language or compiler feature that supports this.
No, there's no way to dictate the scope or lifetime of object references in C#.
I'm trying to understand when exactly static fields come into existence and have been reading this MSDN article - http://msdn.microsoft.com/en-us/library/79b3xss3 - but it seems to contradict itself:
First it says:
Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called.
But then it goes on to say:
If your class contains static fields, provide a static constructor that initializes them when the class is loaded.
So, my question is basically this: When are static fields actually initialized and when do they first come into existence? Is it before the static constructor is called, during, or after?
Many thanks!
The C# Language specification states (in 10.5.5.1 Static field initialization):
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. If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class
I believe the guidance in your second line is actually to initialize static fields that are not done inline, using field initializers. In that case, you should use a static constructor to guarantee that they will be initialized prior to usage.
As you can see from the specification, the actual "time" they come into existence is implementation specific, and subject to change. The only guarantee is that they will exist prior to the static constructor being called, which will always occur prior to their usage in code. This specification states (in 10.12):
The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
· An instance of the class type is created.
· Any of the static members of the class type are referenced.
It's like "normal" fields. So before the static constructor. You can check with a very simple program.
The order is:
static fields
static constructor
"normal" fields
"normal" constructor
A sample program:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Start");
int b = A.B;
Console.WriteLine("Read A.B");
new A();
Console.WriteLine("Built A");
}
}
class A
{
public static int B = mystaticfunc();
static int mystaticfunc() {
Console.WriteLine("Static field");
return 1;
}
static A()
{
Console.WriteLine("Static constructor");
}
int C = myfunc();
static int myfunc()
{
Console.WriteLine("Field");
return 1;
}
public A()
{
Console.WriteLine("Constructor");
}
}
Output:
Start
Static field
Static constructor
Read A.B
Field
Constructor
Built A
Static fields are guaranteed to be initialized prior to the first use of the class.
Optionally, you can provide a static constructor to control static initialization at the time it occurs.
The CLR doesn't have separate concepts of static member initialization and static constructor. Instead, there's just a single type initializer.
The C# compiler writes this type initializer for you, first it does initialization of static members, then it includes your code from any static constructor you defined.
I have a static function in a class.
whenever I try to use non static data member, I get following compile error.
An object reference is required for the nonstatic field, method, or property member
Why is it behaving like that?
A non-static member belongs to an instance. It's meaningless without somehow resolving which instance of a class you are talking about. In a static context, you don't have an instance, that's why you can't access a non-static member without explicitly mentioning an object reference.
In fact, you can access a non-static member in a static context by specifying the object reference explicitly:
class HelloWorld {
int i;
public HelloWorld(int i) { this.i = i; }
public static void Print(HelloWorld instance) {
Console.WriteLine(instance.i);
}
}
var test = new HelloWorld(1);
var test2 = new HelloWorld(2);
HelloWorld.Print(test);
Without explicitly referring to the instance in the Print method, how would it know it should print 1 and not 2?
Instance methods rely on state of that particular instance in order to run.
Let's say you had this class which has the scenario you describe:
class Person
{
static PrintName()
{
// Not legal, but let's say it is for now.
Console.WriteLine(Name);
}
private Name { get; set; }
}
Hopefully, the problem is apparent now. Because Name is an instance member, you need an actual instance of the class, since Name can be different across different instances.
Because of this, the static method, which is not attached to an instance, doesn't know which instance to use. You have to be explicit in specifying which one.
A static method cannot directly access any non-static member variables of a class.
After all : a static method can be called without an instance of the class even being in existance. How do you want to access a member variable on a non-existing instance??
(of course, as Mehrdad pointed out: you could pass an instance of your class to a static method and access everything on that instance - but that's not what you're talking about, right?)
Static functions can only use static members, and call static functions.
As mentioned, a static function can operate on a class instance, but not from within a class instance (for lack of a more descriptive word). For example:
class MyClass
{
public int x;
public static int y;
public static void TestFunc()
{
x = 5; // Invalid, because there is no 'this' context here
y = 5; // Valid, because y is not associated with an object instance
}
public static void TestFunc2(MyClass instance)
{
instance.x = 5; // Valid
instance.y = 5; // Invalid in C# (valid w/ a warning in VB.NET)
}
}
The definition of a "non static data member" would be an "instance data member". In other words non static members belong to a created instance of your class.
A static method does not run in the context of any specific instance of the class. Hence when you ask such a method to use a non static member it will have no idea which of the 0 or more instances of the class it should try to get the data from.
You can't access non-static data from a static function. This is because the static function can be called irrespective of whether there are any instantiated objects of the class. The non-static data, however, is dependent on a specific object (instantiation) of the class. Since you can't be sure that there are any objects instantiated when calling a static function, it is illogical (and therefore not allowed) to access non-static data from it.
This question has been asked several times on SO in different forms / for different languages:
C#
Java
Python
PHP
Language-independent