Functions in C#
A function allows you to encapsulate a piece of code and call it from other parts of your code. You may very soon run into a situation where you will need to repeat a piece of code again an again, from multiple places, and this is where functions come in. we basically declare functions like as below.
<visibility> <return type> <name>(<parameters>)
{
<function code>
}
For Example
public void name()
{
Console.WriteLine("Rohit ");
}
To call a function, you simply write its name, an open parenthesis, then parameters, if any, and then a closing parenthesis, as bellow.
name();
Output = Rohit
So let's see the program below which demonstrate how to implement a function in the program.
Program
using System;
namespace Function
{
public class Program
{
/*Creating User Defined function */
public void Name() /*Function Name*/
{
Console.WriteLine("Rohit");
/*Display the statement*/
}
/* Main function */
static void Main(string[] args)
{
Program Display = new Program(); /* Creating Object refrence*/
Display.Name(); /* Calling Function */
Console.ReadKey();
}
}
}
Output-Rohit
A function allows you to encapsulate a piece of code and call it from other parts of your code. You may very soon run into a situation where you will need to repeat a piece of code again an again, from multiple places, and this is where functions come in. we basically declare functions like as below.
<visibility> <return type> <name>(<parameters>)
{
<function code>
}
For Example
public void name()
{
Console.WriteLine("Rohit ");
}
To call a function, you simply write its name, an open parenthesis, then parameters, if any, and then a closing parenthesis, as bellow.
name();
Output = Rohit
So let's see the program below which demonstrate how to implement a function in the program.
Program
using System;
namespace Function
{
public class Program
{
/*Creating User Defined function */
public void Name() /*Function Name*/
{
Console.WriteLine("Rohit");
/*Display the statement*/
}
/* Main function */
static void Main(string[] args)
{
Program Display = new Program(); /* Creating Object refrence*/
Display.Name(); /* Calling Function */
Console.ReadKey();
}
}
}
Output-Rohit