Powered by Blogger.

Saturday, October 28, 2017

How to call non static method inside main in C#.Net console application?



Here we will discuss how we can call non static method inside main methof in C#.Net console application.

In my previous post, we have discussed about, What are the differences between Hashtable and Dictionary in C#.Net? and How to check string contains text in JavaScript? and how we can enable JavaScript in Internet Explorer?

The main method inside a console application is a static method. So we can call static methods directly by using method name. Here we will check how we can call non static method inside a main method.

Suppose we have a static method like below:

public static void MyStaticMethod()
        {
            //Method logic

        }

Then we can call the method directly by its name like below:


static void Main(string[] args)
        {
            MyStaticMethod();
        }

But suppose you have a non static method like below:

public void MyNONStaticMethod()
        {
            //Method logic
        }

Then we can call the non static method like below:
static void Main(string[] args)
        {
            var myProgram = new Program();
            myProgram.MyNONStaticMethod();

        }

Or you can call like below also:

static void Main(string[] args)
        {
            Program myProgram = new Program();
            myProgram.MyNONStaticMethod();

        }

Or you can also directly call like below:

static void Main(string[] args)
        {
            new Program().MyNONStaticMethod();

        }

Hope this will be helpful.





0 comments

Post a Comment