i have following code
class A{
public void display()
{
Console.WriteLine("In class A");
}
}
class B:A{
public void display()
{
Console.WriteLine("In class B");
}
public static void show()
{
//base.display(); gives error
}
}
in above code base.display(); gives error.I have to call the base class method display() in method show() without creating object of class A.how can i do this? or I can't do this?
A static
method does not belong to an instance, hence it has no base
. You can only say A.display()
if A.display()
is also a static
method. You can also say new A().display()
to discard the instance after calling display()
.
You cannot use instance data in a static method.
A static method should be self-contained. This is to say that it will perform its function without requiring or saving any stateful data.
class A{
public static void display()
{
Console.WriteLine("In class A");
}
}
class B : A
{
public void display()
{
Console.WriteLine("In class B");
}
public static void show()
{
A.display();
}
}
You are getting error because you are calling an instance method from a static method which is not allowed.
You have 3 options here. You can choose whatever suits you well.
Option 1.
class A{
public void display()
{
Console.WriteLine("In class A");
}
}
class B:A{
public void display()
{
Console.WriteLine("In class B");
}
public void show()
{
base.display();
}
}
Option 2:
class A{
public static void display()
{
Console.WriteLine("In class A");
}
}
class B:A{
public void display()
{
Console.WriteLine("In class B");
}
public void show()
{
A.display();
}
}
Option 3:
class A{
public void display()
{
Console.WriteLine("In class A");
}
}
class B:A{
public void display()
{
Console.WriteLine("In class B");
}
public void show()
{
new A().display();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.