Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
255 views

Function in C# PDF

C# functions allow programmers to organize code into reusable blocks. Functions can take parameters as input and return values. There are different types of functions such as those with and without parameters or return values. Functions have several components including a name, return type, body, parameters, and access specifier. Functions are defined using a syntax that specifies these components such as the return type, name, parameters, and body. Functions allow code to be reused and modularized in programs.

Uploaded by

Monti Saini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
255 views

Function in C# PDF

C# functions allow programmers to organize code into reusable blocks. Functions can take parameters as input and return values. There are different types of functions such as those with and without parameters or return values. Functions have several components including a name, return type, body, parameters, and access specifier. Functions are defined using a syntax that specifies these components such as the return type, name, parameters, and body. Functions allow code to be reused and modularized in programs.

Uploaded by

Monti Saini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Introduction to C# Functions

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.

There are several components in functions that follow as-

 To make a function call, we have a unique name called Function name.


 To specify the data type of return value, we will use the Return Type.
 The block of statements that contains the executable statements is called Body.
 We can pass the functions during the function call as a list of arguments called Parameters.
 To specify the accessibility of function in the application, we can use the Access specifier.
 C# Function Syntax

<access-specifier><return-type>FunctionName(<parameters>)
{
// function body
// return statement
}
Note: In the above syntax, Return statements, parameters, and Access-
specifier are optional.

Functional Aspects Syntax(Function)

With parameters and with Declaration: int display ( int );


return values Function call: display ( value );

Function definition:
int display(int value)
{
statements;
return value;
}

With parameters and without Declaration: void display ( int );


return values Call: display (value);
Function definition:
void display ( int value)
{
statements;
}

Without parameters and without Declaration: void display ();


return values Call: display ();

Definition:
void display ()
{
statements;
}

Without parameters and with Declaration: int display ( );


return values Call: display ( );

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();

}
}
}

Using With Parameters (Arguments) and Without Return Type

In this program, a string is passed as a parameter to the function. This function’s


return type is “void”, and no values can be returned from the function. The value of
the string is manipulated and displayed inside the function itself.

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();

}
}
}

Using With Parameters (Arguments) and with Return Type

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();
}
}
}

C# Passing Parameters to Methods


When we are creating a method with arguments/parameters in c#, we must pass
arguments/parameters to that specified method when calling our application’s
function. We have several ways to pass parameters to the method; let’s see the
parameters/arguments.

Parameters Description

Value Parameters Value parameters are called the “input parameters”.


Instead of the original parameters, the input
parameters will pass a copy of the original value;
due to that, there will not be any cause or changes
made to the parameter during the called method,
and it will not affect on original values while the
control passes to the caller function.

Reference Parameters Reference parameters are called the “input/output


parameters”. The reference parameter will pass the
reference memory of the original parameters. Thus,
the changes/alteration made to the parameters in
called method, while the control returns to the
caller function, affects the original values.

Output Parameters It is an “output parameter”; these are like the


reference type parameters. The only difference is
there is no need to initialize it before passing the
data.

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";

String _string2 = (String)_string1.Clone();


// To display both strings
Console.WriteLine("String : {0}", _string1);
Console.WriteLine("Clone String : {0}", _string2);

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:

string _string1 = "String Functions";


int index = _string1.IndexOf('t');
Console.WriteLine(index);

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:

string _string1 = "String Functions";


string _string2 = _string1.ToLower();
Console.WriteLine(_string2 );

9. ToUpper()
ToUpper() method is used to convert the string into uppercase. The return value of ToUpper () is a
string.

Example:

string _string1 = "String Functions";


string _string2 = _string1.ToUpper();
Console.WriteLine(_string2 );

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:

string _string1 = "String Functions";


string _string2 = _string1.Insert(6,"-");
Console.WriteLine(_string2 );

11. Length
Length is a string property that returns a number of characters in a string and here spaces count as
characters.

Example:

string _string1 = "String Functions";


Console.WriteLine(_string1.Length);

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:

string _string1 = "Strings in F#";


string _string2 = _string1.Replace('F','C');
Console.WriteLine(_string2 );

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);

Syntax of Recursive functions in C#

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.

Types of Anonymous Functions


1. Lambda Expressions
 Delegates can be created by using a type of anonymous function called Lambda Expressions.
 Local functions can be created using Lambda expressions which can be passed as an argument.
 The queries of the LINQ can be written with the help of Lambda expressions.
 The syntax of lambda expression in C# is as follows:

 (parameterList) => lambda body

Here,

 parameterList - list of input parameters


 => - a lambda operator
 lambda body - can be an expression or statement

Types of Lambda Expression


The two types of lambda expressions are:

1. Expression Lambda
2. Statement Lambda

1. Expression Lambda: Expression lambda contains a single expression in the lambda


body. For example,
(int num) => num * 5;

2. Statement Lambda: Statement lambda encloses one or more statements in the


lambda body. We use curly braces {} to wrap the statements. For example,
(int a, int b) =>
{
var sum = a + b;
return sum;
};

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 };

// lambda expression as method parameter


// returns the total count of 13 in the numbers array
int totalCount = numbers.Count(x => x == 13);

Console.WriteLine("Total number of 13: " + totalCount);


}
}

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

In this example, we pass the value of x to the IncrementValue method. The


method increments the value of the copy of x (i.e., the value parameter), but
the original value of x outside the method is not affected.

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);
}
}

You might also like