Reputation: 21
I know that Static means that variable or method belongs to class itself and we can use it with ClassName.StaticMethodName. So the question is: We can use a non static method inside another nonstatic method but we cannot use a non static method in a static method. I just do not understand why we can use a non static method inside another non static method? Do not we need an object to use non static method? For Static methods we need to use Class name and it is enough. But, why we do not need an object to use a method? For example:
//This code will not generate any error. There is something else which I do not know? Maybe C# add a hidden object before methodB()?
ClassA()
{
public void methodA()
{
methodB();
}
public void methodB()
{
}
}
Upvotes: 1
Views: 835
Reputation: 156
Take for example a situation where you have a class with static and non-static method:
public class A { private int a; public A(int value) { this.a = value; } public static int MethodA() { return MethodB(); } public int MethodB() { return a; } }
Imagine that we are able to compile this, and we try to use this class without constructing it (creating an instance of a class). We would not know the value of 'a' at run time. Therefore we cannot use instance methods inside static methods.
Upvotes: 0
Reputation: 5133
Static
basically means that you don't have to create a new instance of an object to use its methods.
public static class ClassA
{
public static void Run()
{
}
}
This can be called like ClassA.Run();
.
public class ClassB
{
public void Run()
{
}
}
To execute Run
you need to do this:
ClassB b = new ClassB(); //Create a new Instance of type ClassB
b.Run();
So when you got another method in ClassB
which is invoked inside of Run()
this.AnyOtherMethod();
(while this
is redundant) will use the same instance Run()
was invoked from.
Upvotes: 1
Reputation: 2166
I just do not understand why we can use a non static method inside another non static method?
To call a non-static method, you need an object instance which you can call the method on. In this example, MethodA cannot be called without an instantiated instance of ClassA.
For this reason, we know that if we are inside MethodA, there must be an existing instance this function is being executed on. For this reason, calling MethodB is valid as it is being called on the same object MethodA is currently running against.
Upvotes: 5