Creating and Calling Method in C#

(Last Updated On: January 29, 2019)

Learn how to create and define method in C# language and how to call methods in C# program. Also, learn defining multiple methods and why to use methods in C# with example.

Syntax of method in C#

In below example,

public” is modifier

Void” is return type

Orange () – Orange is method name, () can be empty or can have list of parameters

We will read modifier and return types and about “public static void” in details later.

For now, lets focus on method with empty parameter and void return type, void means, method returns nothing.

NOTE: Method in C# always has bracket () after the method name with / without parameters and must have return type.

 

Example of Creating and Defining a Method in C#

This is how we create and define a method in a C# program. Notice the bracket () after the method named orange or after main method.

In below example, main() and orange() are methods. They are not returning anything. So, preceded with “void” return type.

Focus on method and its body. It does not have semi colon; after method name e.g. orange (); but orange () {}

How to call a method in C#?

As an example, in main() method, we are calling orange() method using syntax orange();

IN BRIEF,

Method has modifiers like private and public etc. to restrict access of methods from outside of the class.

Return type shows what value a method is returning. If it does not return anything, then we write “void” keyword before method. If it returns int value then return type will be “int”, if it returns String value then, return type will be “String”.

Note that we will discuss “public static void” , meaning modifiers and return type in detail later. However, you will learn return type and parameters of method in C# language as the next post after understanding methods in C#.

 

WARNING:

We CANNOT define a method inside another method. But, we can call a method from any method.

For example, Below, apple() method definition is wrong as it has been defined inside the orange() method.

Correct way to do this is :

 

Defining multiple methods in C#

We can create and define multiple methods. In below example, two methods orange () and apple () has been defined and called in main () method.

Notice closely, how methods have been defined and called in main() method

NOTE: You can call a method from any other method.

 

Why to use Methods in C#?

We use method for readability and maintainability of an application.

#Bad Code

#Good Code