Function or Method in C#
DevSniper
158 Views
A method or Function is a block of code that perform a task.
Signature :-
<Access Modifier> <Return Type> <Method Name>(Parameter List) { // Method Body }
- Access Modifier :- it is used to define accessibility of the method. access modifier in c# are public , internal, protected and private
- Return Type :- it is used to define data type of value that method will return. if method is not returning any value it will be void.
- Method Name :- it is a unique name of the method that user define based on task/action that the method perform. and this method name is used to call this method. it is case sensitive.
- Parameter List :- it is used to pass or receive data from a method. it is optional i.e. we can define a method without a parameter.
- Method Body :- it is a block of code that perform action or task.
- it is used to perform specific action or task.
- it is used to write reusable code. define a method once and use that method in different place.
- A method can be called as many times as you want.
- A method or function without parameter is also known as non-parameterized method or function.
- it makes our code well structured.
- it enhance readability of the code.
C# Method : no return type and no parameter
using System; class FunClass { public void fun() { Console.WriteLine("no return type and non parameterized method "); } } class Program { static void Main() { var obj= new FunClass(); obj.fun(); } }
no return type and non parameterized method
C# method : return type and no parameter
using System; class FunClass { public int fun() { Console.WriteLine("return type and non parameterized method "); return 10; } } class Program { static void Main() { var obj = new FunClass(); var v = obj.fun(); Console.WriteLine("return value : "+v); } }
return type and non parameterized method return value : 10
C# method : no return type and parameter
using System; class FunClass { public void fun(string name) { Console.WriteLine("no return type and parameterized method"); Console.WriteLine("parameter name value : "+name); } } class Program { static void Main() { var obj = new FunClass(); obj.fun("C#_PARAM"); } }
no return type and parameterized method parameter name value : C#_PARAM
C# method : return type and parameter
using System; class FunClass { public int fun(string name) { Console.WriteLine("return type and parameterized method"); Console.WriteLine("parameter name value : "+name); return 10; } } class Program { static void Main() { var obj = new FunClass(); var v = obj.fun("C#_PARAM"); Console.WriteLine("return value : "+v); } }
return type and parameterized method parameter name value : C#_PARAM return value : 10