Function in C# PDF
Function in C# PDF
C# functions are the essential parts of the C# program that can be consisting of a number of
elements, such as the function name that is used as the function’s reference, return types of the data
operated in the functions, logical body of the function, parameters that can be passed as arguments
for the function, and the Access Specifier for defining the accessibility of the function inside the
program. The different types of functions that can be integrated into a C# program are a combination
of functions with or without parameters, which can or cannot have the return values, depending on
the requirement provided.
<access-specifier><return-type>FunctionName(<parameters>)
{
// function body
// return statement
}
Note: In the above syntax, Return statements, parameters, and Access-
specifier are optional.
Function definition:
int display(int value)
{
statements;
return value;
}
Definition:
void display ()
{
statements;
}
Definition:
int display ( )
{
statements;
return value;
}
If the return value of a function is “void” then, it cannot return any values to the calling function.
Note: If the return value of the function such as “int, double, float, string, etc.” is other
than void then, it can return values to the calling function.
Using Without Parameters and Without Return Type
The function with no parameter and no return type, a function that does not return
any of the values here we specified as void type as a return type value. In this
program, there should not be passed any values to the function call Display(), and
also, there are no values that are returned from this function call to the main
function.
Example:
using System;
namespace FunctionSamples
{
class Program_A
{
// User defined function without return type and parameter
public void Display()
{
Console.WriteLine("Non Parameterized Function"); // No return statement
}
static void Main(string[] args) // Main Program
{
Program_A program = new Program_A (); // to create a new Object
program.Display(); // Call the Function
Console.ReadLine();
}
}
}
Example:
using System;
namespace FunctionSample
{
class Program_B
{
public void Display(string value) // User defined function without
return type
{
Console.WriteLine("Hello " + value); // No return statement
}
static void Main(string[] args) // Main function
{
Program_B program = new Program_B(); // Creating Objec
program.Display("Welcome to C# Functions"); // Calling Function
Console.ReadLine();
}
}
}
In this program, a string is passed as a parameter to the function. The return type of
this function is “string”, and the return value of the string can be returned from the
function. The value of the string is manipulated and displayed inside the function
itself.
Example:
using System;
namespace FunctionsSample
{
class Program_C
{
// User defined function
public string Show(string message)
{
Console.WriteLine("Inside the Show Function Call");
return message;
}
// Main function
static void Main(string[] args)
{
Program_C program = new Program_C();
string message = program.Show("C# Functions");
Console.WriteLine("Hello "+message);
Console.ReadLine();
}
}
}
Using Without Parameters (Arguments) and with Return Value
In this program, there will be not passed any arguments or parameters to the
function “calculate”, but to the main function, the values are returned from this
calculate () function call. The variables a and b values are calculated in the function
call “calculate”, and in the main function sum of these values is returned as a result.
Example:
using System;
namespace FunctionsSample
{
class Program_D
{
public void calculate()
{
int a = 50, b = 80, sum;
sum = a + b;
Console.WriteLine("Calculating the given to values: " +sum);
}
static void Main(string[] args) // Main function
{
Program_D addition =new Program_D();
addition.calculate();
Console.ReadLine();
}
}
}
Parameters Description
C# String Functions
1. Clone()
Clone returns an instance of String. In other words, it returns another copy of that data. The return
value will be merely another view of similar data. The Clone() method does not take any parameters.
Example:
String _string1="StringFunctions";
2. CompareTo()
CompareTo() method is used to compare the string instance with a particular String object. It checks
whether the String occurrence appears in the same position as the particular string or not. Once
comparing to strings it returns an integer value as output.
Example:
string _string1 = "Welcome";
string _string2 = " Welcome ";
string _string3 = "C# Coding";
Console.WriteLine(_string1.CompareTo(_string2));
Console.WriteLine(_string2.CompareTo(_string3));
3. Contains()
Contains() method is used to return a value signifying whether the particular substring presents within
this string or not. If the particular substring is found in this string, it returns true otherwise false. The
return value of this method is either true or false a Boolean value.
Example:
string _string1 = " Welcome ";
string _string2 = " Welcome ";
string _string3 = "StringFunctions";
Console.WriteLine(_string1. Contains(_string2));
Console.WriteLine(_string2. Contains(_string3));
4. EndsWith()
EndsWith() method is used to verify whether the particular string matches the end of this string or
not. If the particular string is present at the end of this string, then the result will be true otherwise
false. The return value of this method is either true or false a Boolean value.
Example:
string _string1 = " Welcome ";
string _string2 = " ome ";
string _string3 = "ing";
Console.WriteLine(_string1. EndsWith(_string2));
Console.WriteLine(_string2. EndsWith(_string3));
5. Equals()
Equals() method is used to compare whether two particular String objects have an identical value or
not. If both strings have similar value, it returns true otherwise false. The return value of the Equals()
method is either true or false a Boolean value.
Example:
string _string1 = " Welcome ";
string _string2 = " Welcome ";
string _string3 = "Strings";
Console.WriteLine(_string1. Equals(_string2));
Console.WriteLine(_string2. Equals(_string3));
6. GetType()
GetType() method is used to obtain the type of current object. It returns the System. Type of current
instance which is used for reflection.
Example:
string _string1 = "String Functions";
Console.WriteLine(_string1.GetType ());
7. IndexOf()
IndexOf() is used to get the index of the particular character present in the string. It returns the index
position of the first occurrence of a particular character as an integer value.
Example:
8. ToLower()
This C# string function is used to convert a string into lowercase. It returns a string in lower case. The
return value of ToLower () is a string.
Example:
9. ToUpper()
ToUpper() method is used to convert the string into uppercase. The return value of ToUpper () is a
string.
Example:
10. Insert()
Insert() method is used to insert the particular string at a specified index number. The index number
starts from 0. After inserting the particular string, it returns a new modified string. The return value of
Insert() is a new modified string.
Example:
11. Length
Length is a string property that returns a number of characters in a string and here spaces count as
characters.
Example:
12. Replace()
This string function in C# is used to replaces the character to get another string in which all
occurrences of a particular character in this string are replaced with another specified character.
Example:
13. Split()
Split() method is used to split the string based on the specified value of characters in an array. The
return value of this method is the string array.
Example:
string _string1 = "Welcome C Sharp";
string[] _string2 = _string1.Split(' ');
foreach (string _string3 in _string2)
{
Console.WriteLine(_string3);
There is no special syntax here, but we can observe that a function is calling itself in
providing the return result. And we must be very careful in passing those parameter
values into that recursive function as obviously we don’t want a running code which
doesn’t stop.
Execution of Factorization
using System;
class First {
static void Main() {
int result;
result = fact(7);
Console.WriteLine("Factorial is : " + result);
Console.ReadLine();
}
public static int fact(int num)
{
if(num==0)
{
return 1;
}
return num*fact(num-1);
}
}
Step by step process
1. First, we have created our own parameterized function to take an input value from main
function, for which we want to calculate the factorial.
2. Then, we made an if condition to check if the given number is zero. If the number is zero, then
we are returning 1 as our default value.
3. Else, we are multiplying the present number with the function taking in the number minus 1 as
its parameter.
4. So, this multiplication repeats itself until we get to number 0. As by default, we have written
our return output for zero as 1, the final result would be multiplied by 1.
Eg-2:
using System;
class First {
static void Main() {
int result,c;
string a;
Console.Write("Enter value for number :");
a = Console.ReadLine();
c = Convert.ToInt32(a);
result = fact(c);
Console.WriteLine("Factorial is : " + result);
Console.ReadLine();
}
public static int fact(int num)
{
if(num==0)
{
return 1;
}
return num*fact(num-1);
}
Examples-3
Write a recursive function in adding numbers continuously until the program finds
the second number that is given as input.
using System;
class First {
static void Main() {
int result,c,d;
string a,b;
Console.Write("Enter value for 1st number :");
a = Console.ReadLine();
c = Convert.ToInt32(a);
Console.Write("Enter value for 2nd number :");
b = Console.ReadLine();
d = Convert.ToInt32(b);
result = add(c,d);
Console.WriteLine("Add is : " + result);
Console.ReadLine();
}
public static int add(int num1,int num2)
{
int sum ;
sum=num1;
if (num1 < num2 )
{
num1++;
sum=sum+add(num1,num2);
return sum;
}
return sum;
}
}
C# Anonymous Functions
A type of function in C# which does not have a name is called anonymous function
which can also be expressed as a function without a name. Anonymous functions
are of two types in C# which are Lambda expressions in C# and Anonymous
methods in C# where the anonymous function used to create delegates is called
Lambda expression in C# using which local functions can be created and can be
passed as an argument and the queries of LINQ can also be written with the help of
Lambda expressions. The same functionality is provided by the Anonymous
methods as well except that it allows to no use the list of parameters.
Here,
1. Expression Lambda
2. Statement Lambda
Eg:
using System;
//a namespace called program is defined
namespace program
{
//a class called check is defined
class check
{
delegate int Findsquare(int number);
//main method is called
static void Main(string[] args)
{
//a lambda expression to find the square of a number is defined
Findsquare Obtainsquare = r => r * r;
int l = Obtainsquare(3);
Console.WriteLine("The Square of the given number is: " + l);
Console.ReadKey();
}
}
}
Passing Parameter in Method
using System;
class Program
{
static void Main()
{
// array containing integer values
int[] numbers = { 2, 13, 1, 4, 13, 5 };
2. Anonymous Methods
A method which does not have a name is called an anonymous method in C#.
The anonymous method was introduced in C# version 2.0.
We make use of anonymous methods when an inline method is to be created and parameters
also must be passed to the method similar to the way we pass parameters to any other
methods.
The keyword delegate is used to define an anonymous method and this method can be
assigned to a variable of type delegate.
The syntax of Anonymous method in C# is as follows:
Delegate(parameter_list)
{
//Block of code
};
Example #1
C# program to demonstrate an anonymous method in a program:
Code:
using System;
//a class called program is defined
class program
{
//a delegate is created by using delegate keyword
public delegate void subject(string favsubject);
// Main method is called
static public void Main()
{
// a parameter is passed to the anonymous method using delegate keyword
subject sub = delegate(string favsubject)
{
Console.WriteLine("{0} is my favourite subject", favsubject);
};
sub("C#");
}
}
Example #2
C# program to demonstrate an anonymous method in a program that can access a variable which is
defined in the outer method:
Code:
using System;
//a class called program is defined
class program
{
//anonymous method is declared using delegate keyword
public delegate void subject(string favsubject);
// Main method is called
static public void Main()
{
//a string variable is defined in the outside method from anonymous
method
string favsubject1 = "Coding_in_C#";
// a parameter is passed to the anonymous method using delegate keyword
subject sub = delegate(string favsubject)
{
Console.WriteLine("{0} is my favourite subject", favsubject);
Console.WriteLine("I also like {0}", favsubject1);
};
sub("C#");
}
}
Call by Value:
In Call by Value, a copy of the argument is passed to the method. Any
changes made to the argument inside the method do not affect the original
value of the argument outside the method.
For example:
class Program
{
static void Main(string[] args)
{
int x = 5;
Console.WriteLine("Before calling method: " + x);
IncrementValue(x);
Console.WriteLine("After calling method: " + x);
}
static void IncrementValue(int value)
{
value++;
Console.WriteLine("Inside method: " + value);
}
}
Output:
Before calling method: 5
Inside method: 6
After calling method: 5
Call by Reference:
In Call by Reference, a reference to the argument is passed to the method.
Any changes made to the argument inside the method affect the original
value of the argument outside the method.
For example
class Program
{
static void Main(string[] args)
{
int x = 5;
Console.WriteLine("Before calling method: " + x);
IncrementValue(ref x);
Console.WriteLine("After calling method: " + x);
}
static void IncrementValue(ref int value)
{
value++;
Console.WriteLine("Inside method: " + value);
}
}