Unable to call main function in VS 2022

61 Views Asked by At

In VS 2022, the entry point of the code public static void main no longer exist.

I was trying to implement a simple delegate but no output is shown on the console:

using System;

namespace ConsoleApp1
{
    public delegate void SomeMethodPointer(); // delegate definition

    public class MyClassDel
    {
        // function which I am trying to call through a delegate
        public void DoSomething()
        {
            Console.WriteLine("In the function");
        }
    }

    public class Program
    {
        // created this here as program,cs is empty in my console app
        public static void Main(string[] args)
        {
            // Initialize the delegate with a method reference
            SomeMethodPointer obj = new SomeMethodPointer(DoSomething); 

            // Call the delegate
            obj.Invoke(); 
        }
    }
}
1

There are 1 best solutions below

3
Idle_Mind On

In Main(), you need to create an INSTANCE of your class MyClassDel, and then make your delegate point to the the DoSomething() method of that particular instance:

static void Main(string[] args)
{
    MyClassDel mcd = new MyClassDel();
    SomeMethodPointer obj = new SomeMethodPointer(mcd.DoSomething);
    obj.Invoke(); // Call the delegate
    Console.ReadLine();
}

Alternatives...

(1) Make DoSomething() a static method in class MyClassDel:

namespace ConsoleApp1
{
    public delegate void SomeMethodPointer(); // delegate definition
    
    public class MyClassDel
    {
        public static void DoSomething() // function which i am trying to call through delegate
        {
            Console.WriteLine("In the function");
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            SomeMethodPointer obj = new SomeMethodPointer(MyClassDel.DoSomething); // Initialize the delegate with a method reference
            obj.Invoke(); // Call the delegate
            Console.ReadLine();
        }
    }

}

(2) Make DoSomething() a static method in class Program:

namespace ConsoleApp1
{
    public delegate void SomeMethodPointer(); // delegate definition

    internal class Program
    {
        static void Main(string[] args)
        {
            SomeMethodPointer obj = new SomeMethodPointer(DoSomething); // Initialize the delegate with a method reference
            obj.Invoke(); // Call the delegate
            Console.ReadLine();
        }

        public static void DoSomething() // function which i am trying to call through delegate
        {
            Console.WriteLine("In the function");
        }

    }

}