0

How can be call the method from another class inherited

let's see my code please:

class Program : classA
{
    static void Main(string[] args)
    {
        // how i can call method ToDo without create an instance like below
        //classA c = new classA();
        //c.ToDo();
        Console.ReadLine();
    }
}
class Program2 : classB
{
    static void Main(string[] args)
    {
        // how i can call method ToDo
        //ToDo()
        Console.ReadLine();
    }
}

public abstract class classB
{
    public void ToDo()
    {
        Console.WriteLine("classB");
    }
}
public class classA
{
    public void ToDo()
    {
        Console.WriteLine("classA");
    }
}

how i can call the method in Either way, please help me.

  • 4
    The problem is that you are trying to call `instance` method from the `static` one. That is not possible. – Johnny Feb 08 '19 at 22:10
  • @Johnny Can you explain me more? not have any static keyword in my answer – Søśø ÐålợȜà ZåȜră Feb 08 '19 at 22:14
  • 2
    Elaborating on @Johnny's answer. A class can have two categories of members, `static` and _instance_ (those not marked `static`). In order to access an instance member, you need an instance of the class. Within an instance method, the instance that is used to call the method is available as `this` (which can usually be omitted). A `static` member can be thought of as a member associated with the class (rather than with an instance). You call it using the class name: `ClassName.MethodName();` It can't call other instance members (since it has no `this` reference). – Flydog57 Feb 08 '19 at 22:15
  • @Flydog57 Can you show me on the example as answer please – Søśø ÐålợȜà ZåȜră Feb 08 '19 at 22:18
  • Possible duplicate of [What's a "static method" in C#?](https://stackoverflow.com/questions/4124102/whats-a-static-method-in-c) – Fabjan Feb 08 '19 at 22:25

2 Answers2

1

There are a couple ways to do what you want to do (they're kind of similar or even the same). One way is to create a class with a static method:

public class classA
{
    public static void ToDo()
    {
        Console.WriteLine("classA");
    }
}

then call it like:

classA.ToDo();

Another way is to add another static method to the class that contains Main:

class Program2 : classB
{
    static void Main(string[] args)
    {
        ToDo()
        Console.ReadLine();
    }

    static void Todo()
    {
        // do stuff here
    }
}
Christo
  • 292
  • 1
  • 7
0

If u want to call ToDo() function into [class Program : classA] and [class Program : classB] Without creating Instance. U have to Define ToDo() function as static, then u can call this method with class name in anywhere. public static void ToDo(){}

Nour Khashan
  • 5
  • 2
  • 6