Methods in C#

Rumman Ansari   Software Engineer   2022-10-28   5802 Share
☰ Table of Contents

Table of Content:


In C#, Console Application or a Windows Application needs to have starting point for the program. The Main Method is defined as the entry point of a “.exe” program, i.e. the program starts execution from the Main Method.

One class should contain a Main Method. Since the execution starts from the Main Method and it is invoked without creating an object of the Class, the Main method should be defined using the "static" keyword.

Main Method should also specify a return type. The return type can be either "void" type which means returns nothing or “int” datatype which means returns an integer value by the completion of Main method.

Main Method can be defined with or without parameters. The Parameter are used to take the Command line Arguments and the parameters are defined using string[] args.

The syntax of the Main Method can be given as follows:


static void Main()
{
//code here
}

Or


static void Main(string[] args)
{
//code here
}

Program

Here we will see the Class program with the Main Method creating the objects of class customer and using the members defined inside.


 class Program
{
	static void Main(string[] args)
	{
	Customer customer = new Customer();
	Console.WriteLine("{0} :: {1}", customer.ID, customer.Name);
	Customer newCustomer = new Customer(100, "Jack");
	Console.WriteLine("{0} :: {1}", newCustomer.ID, newCustomer.Name);
	Console.ReadKey();
	}
}

class Customer
{
	//Declaration of Variable
	private int _id = 0;
	//Property for ID restricted from assigning new values
	public int ID
	{
		get { return _id; }
	}
	
//Declare Variable for name & use Property for Read & Write
	private string _name = string.Empty;
	public string Name
	{
	get { return _name; }
		set { _name = value; }
	}
	
//Constructor for passing the initial value(as parameter) to the variables
	public Customer(int id, string name)
	{
	//variable = parameter
	_id = id;
	_name = name;
	}
	
//Constructor with 0 arguments
	public Customer()
	{
	//
	}
}