0

Why is it impossible to work with non-static fields in a static method?

3rd Jun 2022, 1:45 PM
‎أندريه‎
‎أندريه‎ - avatar
8 Réponses
+ 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.
3rd Jun 2022, 2:00 PM
Ipang
+ 2
Thanks!
4th Jun 2022, 11:22 AM
‎أندريه‎
‎أندريه‎ - avatar
+ 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.
3rd Jun 2022, 1:59 PM
Mustafa A
Mustafa A - avatar
+ 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.
3rd Jun 2022, 2:11 PM
A͢J
A͢J - avatar
0
Example?
3rd Jun 2022, 1:48 PM
A͢J
A͢J - avatar
0
using System; class Program { sbyte userAge = 30; static void Main(string[] args) { Display(); } static void Display() { Console.WriteLine(userAge); } }
3rd Jun 2022, 1:55 PM
‎أندريه‎
‎أندريه‎ - avatar
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?
4th Jun 2022, 5:21 AM
‎أندريه‎
‎أندريه‎ - avatar
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
4th Jun 2022, 5:54 AM
A͢J
A͢J - avatar