Static Method -- Is it usual behavior?
Have a small doubt with static method.
Documentation says that "Static method can't access instance member variable OR static methods and properties can only access static fields and stat开发者_开发百科ic events since it's gets executed much before an instance is created". So, the below code fails to compile
class staticclass
{
int a = 20; //Private member
public static void staticmethod()
{
Console.WriteLine("Value Of Instance member variable is: {0}",a); // Error
}
}
But we also know that, inside a static method we can create an instance of the same class.
So, changing the above code a bit I can access the instance variable in static method
class staticclass
{
int a = 20; //PRivate Memeber
public static void staticmethod()
{
staticclass sc = new staticclass();
Console.WriteLine("Value Of Instance member variable is: {0}",sc.a);
}
}
This Compiles fine and displays the result Value Of Instance member variable is: 20
.
Is this a normal behavior? OR I am not able to understand it correctly?
I mean, if this the case then How the statements holds true static methods can only access static fields
?
Thanks.
You're misunderstanding what static means – it means that you only have access to static members of this
. It doesn't restrict you accessing another object's non-static members.
The fact that the "other" object you're accessing in your static method happens to be an instance of the same class does not matter.
精彩评论