0
Why is it impossible to work with non-static fields in a static method?
8 Respuestas
+ 2
static members are supposed to be able to work (methods) and usable (constants, enums etc.) without any need for an instance.
Non static members will require instantiation before they become available cause their existence are per instance.
static methods should be independent, they cannot and should not rely on non-static fields, or methods which require instance to exist.
+ 2
Thanks!
+ 1
I am assuming that you are referring to attributes and regular methods. It's because simply put, they require a context (object) unlike the static resources. They are allocated differently in memory.
+ 1
Andrey
static method can access only static data members because static method don't know where that non static variable exist in memory.
non static variable means instance variable and static method belongs to the class, not to an instance. So to access instance variables, the static method would first have to create an instance.
0
Example?
0
using System;
class Program
{
sbyte userAge = 30;
static void Main(string[] args)
{
Display();
}
static void Display()
{
Console.WriteLine(userAge);
}
}
0
That is, when we have a non-static method and a field, we must create an object, and this object will be common for both the method and the property?
0
Andrey
Yes
To access static method or variable no need of object because it is belongs to the class
But non static method or variable need an instance of class. You can not directly access using class
class Student {
public int id;
public static int collegeId = 100;
}
Student.id; //this will give error because id is non-static so it needs an object of the class
Student s = new Student ();
s.id; //now this is correct
----------
Student.collegeId; //this will not give error because collegeId is a static variable