Question : Problem: Writing simple C# method

Hi I am trying to write a simple C# method that would display a "Hello World" message as shown in the code snippet below However the compiler gives me an error on the method call i.e at the displayMessage(); line . The error message is

An object reference is required for the non-static field, method, or property

Note: I am moving from C++ to C#. So I tend to assume much of C# syntax is similar to C++


Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Message
{
    class Program
    {
        void displayMessage()
        {
            Console.WriteLine("Hello World");
        }
        static void Main(string[] args)
        {
            displayMessage();            
        }
    }
}
Open in New Window Select All

Answer : Problem: Writing simple C# method

Alternatively, if you so decide to make displayMessage a static method, then see below. Whether to make a method static or not is your design decision.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Message
{
    class Program
    {
        static void displayMessage()
        {
            Console.WriteLine("Hello World");
        }
        static void Main(string[] args)
        {
            Program.displayMessage();            
        }
    }
}
Open in New Window Select All
Random Solutions  
 
programming4us programming4us