0% found this document useful (0 votes)
34 views28 pages

Chap2.. Main Method

The document discusses various control flow statements in C# including if, if-else, if-else if-else, switch, nested switch statements, while loops, for loops, and do-while loops. Code examples are provided to demonstrate the syntax and usage of each statement. Key conditional statements like if, if-else, if-else if-else are used to execute code based on boolean expressions. Switch statements allow checking a variable against multiple case values. Loops like while, for, and do-while are used to repeatedly execute a block of code as long as or until a condition is met.

Uploaded by

Rohit Mohite
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views28 pages

Chap2.. Main Method

The document discusses various control flow statements in C# including if, if-else, if-else if-else, switch, nested switch statements, while loops, for loops, and do-while loops. Code examples are provided to demonstrate the syntax and usage of each statement. Key conditional statements like if, if-else, if-else if-else are used to execute code based on boolean expressions. Switch statements allow checking a variable against multiple case values. Loops like while, for, and do-while are used to repeatedly execute a block of code as long as or until a condition is met.

Uploaded by

Rohit Mohite
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Chap-2

Control Statements –

1) If Statement -
If the boolean expression evaluates to true, then the block of code inside the if statement is executed.
If boolean expression evaluates to false, then the first set of code after the end of the if
statement(after the closing curly brace) is executed.

Flow Diagram

Example-
using System;

namespace DecisionMaking {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;

/* check the boolean condition using if statement */


if (a < 20) {
/* if condition is true then print the following */
Console.WriteLine("a is less than 20");
}
Console.WriteLine("value of a is : {0}", a);
Console.ReadLine();
}
}
}
result −

a is less than 20;


value of a is : 10

2.) if...else statement –

Syntax −

if(boolean_expression) {
/* statement(s)
} else {
/* statement(s)
}

If the boolean expression evaluates to true, then the if block of code is executed, otherwise else
block of code is executed.

Flow Diagram

Example-
using System;

namespace DecisionMaking {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 100;

/* check the boolean condition */


if (a < 20) {
/* if condition is true then print the following */
Console.WriteLine("a is less than 20");
} else {
/* if condition is false then print the following */
Console.WriteLine("a is not less than 20");
}
Console.WriteLine("value of a is : {0}", a);
Console.ReadLine();
}
}
}
result −

a is not less than 20;


value of a is : 100

3) The if...else if...else Statement


An if statement can be followed by an optional else if...else statement, which is very useful to test
various conditions using single if...else if statement.
When using if, else if, else statements there are few points to keep in mind.
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax

if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */
} else {
/* executes when the none of the above condition is true */
}
Example-
using System;

namespace DecisionMaking {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 100;

/* check the boolean condition */


if (a == 10) {
/* if condition is true then print the following */
Console.WriteLine("Value of a is 10");
}
else if (a == 20) {
/* if else if condition is true */
Console.WriteLine("Value of a is 20");
}
else if (a == 30) {
/* if else if condition is true */
Console.WriteLine("Value of a is 30");
} else {
/* if none of the conditions is true */
Console.WriteLine("None of the values is matching");
}
Console.WriteLine("Exact value of a is: {0}", a);
Console.ReadLine();
}
}
}
result −

None of the values is matching


Exact value of a is: 100

4) switch statement-
A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each switch case.
Syntax
switch(expression) {

case constant-expression1 :

statement(s);

break;

case constant-expression2 :

case constant-expression3 :

statement(s);

break;

/* you can have any number of case statements */

default : /* Optional */

statement(s);

Flow Diagram -

Example-
using System;

namespace DecisionMaking {
class Program {
static void Main(string[] args) {
/* local variable definition */
char grade = 'B';

switch (grade) {
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
case 'C':
Console.WriteLine("Well done");
break;
case 'D':
Console.WriteLine("You passed");
break;
case 'F':
Console.WriteLine("Better try again");
break;
default:
Console.WriteLine("Invalid grade");
break;
}
Console.WriteLine("Your grade is {0}", grade);
Console.ReadLine();
}
}
}
result −

Well done
Your grade is B

5) nested switch statement –


It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case
constants of the inner and outer switch contain common values, no conflicts will arise.

Syntax
switch(ch1) {

case 'A':

Console.WriteLine("This A is part of outer switch" );

switch(ch2) {

case 'A':

Console.WriteLine("This A is part of inner switch" );

break;

case 'B': /* inner B case code */

break;

case 'B': /* outer B case code */

}
Example
using System;

namespace DecisionMaking {
class Program {
static void Main(string[] args) {
int a = 100;
int b = 200;

switch (a) {
case 100:
Console.WriteLine("This is part of outer switch ");

switch (b) {
case 200:
Console.WriteLine("This is part of inner switch ");
break;
}
break;
}
Console.WriteLine("Exact value of a is : {0}", a);
Console.WriteLine("Exact value of b is : {0}", b);
Console.ReadLine();
}
}
}
result −

This is part of outer switch


This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200

Loops Statements-
There may be a situation, when you need to execute a block of code several number of times. In
general, the statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution
paths.
A loop statement allows us to execute a statement or a group of statements multiple times and
following is the general from of a loop statement in most of the programming languages −
1) While Loop -
A while loop statement in C# repeatedly executes a target statement as long as a given condition is
true.

Syntax

while(condition) {
statement(s);
}

Flow Diagram

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and
the result is false, the loop body is skipped and the first statement after the while loop is executed.

Example
using System;

namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;

/* while loop execution */


while (a < 20) {
Console.WriteLine("value of a: {0}", a);
a++;
}
Console.ReadLine();
}
}
}
result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

2) For Loop Statement –


A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.

Syntax
for ( init; condition; increment ) {
statement(s);
}
Here is the flow of control in a for loop −
 The init step is executed first, and only once. This step allows you to declare and initialize any
loop control variables. You are not required to put a statement here, as long as a semicolon
appears.
 Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement just after
the for loop.
 After the body of the for loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control variables. This
statement can be left blank, as long as a semicolon appears after the condition.
 The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again testing for a condition). After the
condition becomes false, the for loop terminates.

Flow Diagram

Example
using System;

namespace Loops {
class Program {
static void Main(string[] args) {
/* for loop execution */
for (int a = 10; a < 20; a = a + 1) {
Console.WriteLine("value of a: {0}", a);
}
Console.ReadLine();
}
}
}
result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

3) do...while loop –
Unlike for and while loops, which test the loop condition at the start of the loop, the do...while loop
checks its condition at the end of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax

do {
statement(s);
} while( condition );
Flow Diagram

Example
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;

/* do loop execution */
do {
Console.WriteLine("value of a: {0}", a);
a = a + 1;
}
while (a < 20);
Console.ReadLine();
}
}
}
result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
break statement –
The break statement in C# has following two usage −
 When the break statement is encountered inside a loop, the loop is immediately terminated
and program control resumes at the next statement following the loop.
 It can be used to terminate a case in the switch statement.
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the
execution of the innermost loop and start executing the next line of code after the block.

Syntax
break;

Example
using System;

namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;

/* while loop execution */


while (a < 20) {
Console.WriteLine("value of a: {0}", a);
a++;

if (a > 15) {
/* terminate the loop using break statement */
break;
}
}
Console.ReadLine();
}
}
}
result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

continue statement –
The continue statement in C# works somewhat like the break statement. Instead of forcing
termination, however, continue forces the next iteration of the loop to take place, skipping any code in
between.
For the for loop, continue statement causes the conditional test and increment portions of the loop to
execute. For the while and do...while loops, continue statement causes the program control passes to
the conditional tests.

Syntax
continue;
Flow Diagram

Example

using System;

namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;

/* do loop execution */
do {
if (a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
Console.WriteLine("value of a: {0}", a);
a++;
}
while (a < 20);
Console.ReadLine();
}
}
}
result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Array -
An array stores a fixed-size sequential collection of elements of the same type. An array is used to store
a collection of data, but it is often more useful to think of an array as a collection of variables of the
same type stored at contiguous memory locations.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.

To declare an array in C#, you can use the following syntax −

datatype[] arrayName;

where,

datatype is used to specify the type of elements in the array.

[ ] specifies the rank of the array. The rank specifies the size of the array.

arrayName specifies the name of the array.

For example,

double[] balance

Example -

using System;

namespace ArrayApplication {

class MyArray {

static void Main(string[] args) {

int [] n = new int[10]; /* n is an array of 10 integers */

int i,j;

/* initialize elements of array n */

for ( i = 0; i < 10; i++ ) {

n[ i ] = i + 100;

}
/* output each array element's value */

for (j = 0; j < 10; j++ ) {

Console.WriteLine("Element[{0}] = {1}", j, n[j]);

Console.ReadKey();

result −

Element[0] = 100

Element[1] = 101

Element[2] = 102

Element[3] = 103

Element[4] = 104

Element[5] = 105

Element[6] = 106

Element[7] = 107

Element[8] = 108

Element[9] = 109

Multidimensional Array -

C# allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array. You can
declare a 2-dimensional array of strings as −

string [,] names;

or, a 3-dimensional array of int variables as −

int [ , , ] m;

Two Dimensional array -

using System;

namespace ArrayApplication {

class MyArray {
static void Main(string[] args) {

/* an array with 5 rows and 2 columns*/

int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };

int i, j;

/* output each array element's value */

for (i = 0; i < 5; i++) {

for (j = 0; j < 2; j++) {

Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);

Console.ReadKey();

When the above code is compiled and executed, it produces the following result −

a[0,0]: 0

a[0,1]: 0

a[1,0]: 1

a[1,1]: 2

a[2,0]: 2

a[2,1]: 4

a[3,0]: 3

a[3,1]: 6

a[4,0]: 4

String -

In C#, you can use strings as array of characters, However, more common practice is to use the string
keyword to declare a string variable. The string keyword is an alias for the System.String class.

Creating a String Object


You can create string object using one of the following methods −

By assigning a string literal to a String variable

By using a String class constructor

By using the string concatenation operator (+)

By retrieving a property or calling a method that returns a string

By calling a formatting method to convert a value or an object to its string representation

example
using System;

namespace StringApplication {

class Program {

static void Main(string[] args) {


//from string literal and string concatenation
string fname, lname;
fname = "Rowan";
lname = "Atkinson";

char []letters= { 'H', 'e', 'l', 'l','o' };


string [] sarray={ "Hello", "From", "Tutorials", "Point" };

string fullname = fname + lname;


Console.WriteLine("Full Name: {0}", fullname);

//by using string constructor { 'H', 'e', 'l', 'l','o' };


string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);

//methods returning string { "Hello", "From", "Tutorials", "Point" };


string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);

//formatting method to convert a value


DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = String.Format("Message sent at {0:t} on {0:D}", waiting);
Console.WriteLine("Message: {0}", chat);
}
}
}
result −

Full Name: RowanAtkinson


Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 5:58 PM on Wednesday, October 10, 2012
Main Method in C#

C# applications have an entry point called Main Method. It is the first method which gets
invoked whenever an application started and it is present in every C# executable file. The
application may be Console Application or Windows Application. The most common entry point
of a C# program is static void Main() or static void Main(String []args).

Different Declaration of Main() Method

Below are the valid declarations of Main Method in a C# program:

1. With command line arguments: This can accept n number of array type parameters
during the runtime.

Example:

using System;

class GFG {

// Main Method
static public void Main(String[] args)
{

Console.WriteLine("Main Method");
}
}

Output:

Main Method

Meaning of the Main Syntax:

static: It means Main Method can be called without an object.


public: It is access modifiers which means the compiler can execute this from
anywhere.
void: The Main method doesn’t return anything.
Main(): It is the configured name of the Main method.
String []args: For accepting the zero-indexed command line arguments. args is
the user-defined name. So you can change it by a valid identifer. [] must come
before the args otherwise compiler will give errors.

2. Without Command line arguments: It is up to the user whether he wants to take


command line arguments or not. If there is a need for command-line arguments then the
user must specify the command line arguments in the Main method.

Example:

using System;

class GFG {

// Main Method
static public void Main()
{
Console.WriteLine("Main Method");
}
}

Output:

Main Method

3. Applicable Access Modifiers: public, private, protected, internal, protected internal


access modifiers can be used with the Main() method. The private protected access
modifier cannot be used with it.

Example:

using System;

class GFG {

// Main Method
protected static void Main()
{

Console.WriteLine("Main Method");
}
}

Output:

Main Method

Example:

using System;

class GFG {

// Main Method
private protected static void Main()
{

Console.WriteLine("Main Method");
}
}

Compiler Error:

More than one protection modifier specified

4. Without any access modifier: The default access modifier is private for a Main()
method.

Example:

using System;

class GFG {

// Main Method without any


// access modifier
static void Main()
{

Console.WriteLine("Main Method");
}
}

Output:

Main Method

5. Order of Modifiers: The user can also swap positions of static and applicable modifiers
in Main() method.

Example:

using System;

class GFG {

// Main Method
public static void Main()
{

Console.WriteLine("Main Method");
}
}

Output:

Main Method

Example:

using System;

class GFG {

// Main Method with swapping of modifiers


static internal void Main()
{

Console.WriteLine("Main Method");
}
}

Output:

Main Method

6. Return Type: The Main Method can also have integer return type. Returning an integer
value from Main() method cause the program to obtain a status information. The value
which is returned from Main() method is treated as the exit code for the process.

Example:

using System;
class GFG {

// Main Method with int return type


static int Main()
{

Console.WriteLine("Main Method");

// for successful execution of code


return 0;
}
}

Output:

Main Method

Example:

using System;

class GFG {

// Main Method with int return type


static int Main(String[] args)
{

Console.WriteLine("Main Method");

// for successful execution of code


return 0;
}
}

Output:

Main Method

Important Points:

 The Main() method is the entry point a C# program from where the execution starts.
 Main() method must be static because it is a class level method. To invoked without any
instance of the class it must be static. Non-static Main() method will give a compile-time
error.
 Main() Method cannot be overridden because it is the static method. Also, the static
method cannot be virtual or abstract.
 Overloading of Main() method is allowed. But in that case, only one Main() method is
considered as one entry point to start the execution of the program.

Stack and Heap :-


Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the
computer's RAM .

Variables allocated on the stack are stored directly to the memory and access to this memory is very
fast, and it's allocation is dealt with when the program is compiled. When a function or a method calls
another function which in turns calls another function etc., the execution of all those functions remains
suspended until the very last function returns its value. The stack is always reserved in a LIFO order, the
most recently reserved block is always the next block to be freed. This makes it really simple to keep
track of the stack, freeing a block from the stack is nothing more than adjusting one pointer.

Variables allocated on the heap have their memory allocated at run time and accessing this memory is a
bit slower, but the heap size is only limited by the size of virtual memory . Element of the heap have no
dependencies with each other and can always be accessed randomly at any time. You can allocate a
block at any time and free it at any time. This makes it much more complex to keep track of which parts
of the heap are allocated or free at any given time.

You can use the stack if you know exactly how much data you need to allocate before compile time and
it is not too big. You can use heap if you don't know exactly how much data you will need at runtime or
if you need to allocate a lot of data.

In a multi-threaded situation each thread will have its own completely independent stack but they will
share the heap. Stack is thread specific and Heap is application specific. The stack is important to
consider in exception handling and thread executions.

Value Type
Value type variables can be assigned a value directly. They are derived from the class System.ValueType.
The value types directly contain data. When you declare an int type, the system allocates memory to
store the value.
Value Type variables are stored in the stack.
Examples are int, char, and float, which stores numbers, alphabets, and floating point numbers,
respectively. bool

Reference Type
It refers to a memory location. Using multiple variables, the reference types can refer to a memory
location. If the data in the memory location is changed by one of the variables, the other variable
automatically reflects this change in value.
Reference Type variables are stored in the heap.
Example of built-in reference types are −

 object
 dynamic
 string
Type Casting
Type conversion happens when we assign the value of one data type to another. If the data types
are compatible, then C# does Automatic Type Conversion. If not comparable, then they need to
be converted explicitly which is known as Explicit Type conversion. For example, assigning an
int value to a long variable.

Implicit Type Casting / Automatic Type Conversion

It happens when:

 The two data types are compatible.


 When we assign value of a smaller data type to a bigger data type.

For Example, in C#, the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other. Before converting, the compiler first checks the compatibility
according to the following figure and then it decides whether it is alright or there some error.

Following table shows the implicit types of conversion that is supported by C# :

Convert from Data Type Convert to Data Type

byte short, int, long, float, double

short int, long, float, double

int long, float, double

long float, double

float double

Example :

// C# program to demonstrate the

// Implicit Type Conversion

using System;

namespace Casting{

class GFG {

// Main Method

public static void Main(String []args)

int i = 57;
// automatic type conversion

long l = i;

// automatic type conversion

float f = l;

// Display Result

Console.WriteLine("Int value " +i);

Console.WriteLine("Long value " +l);

Console.WriteLine("Float value " +f);

}} }

Output:

Int value 57
Long value 57
Float value 57

Explicit Type Casting

There may be compilation error when types not compatible with each other. For example,
assigning double value to int data type:

// C# program to illustrate incompatible data

// type for explicit type conversion

using System;

namespace Casting{

class GFG {

// Main Method

public static void Main(String []args)

double d = 765.12;

// Incompatible Data Type

int i = d;

// Display Result

Console.WriteLine("Value of i is ", +i);

} } }

Error :
prog.cs(14,21): error CS0266: Cannot implicitly convert type `double' to
`int'.
An explicit conversion exists (are you missing a cast?)

So, if we want to assign a value of larger data type to a smaller data type we perform explicit
type casting.

 This is useful for incompatible data types where automatic conversion cannot be done.
 Here, target-type specifies the desired type to convert the specified value to.
 Sometimes, it may result into the lossy conversion.

Example :

// C# program to demonstrate the

// Explicit Type Conversion

using System;

namespace Casting{

class GFG {

// Main Method

public static void Main(String []args)

double d = 765.12;

// Explicit Type Casting

int i = (int)d;

// Display Result

Console.WriteLine("Value of i is " +i);

} } }

Output:

Value of i is 765

Explanation :
Here due to lossy conversion, the value of i becomes 765 and there is a loss of 0.12 value.

C# provides built-in methods for Type-Conversions as follows :

Method Description

ToBoolean It will converts a type to Boolean value

ToChar It will converts a type to a character value


ToByte It will converts a value to Byte Value

ToDecimal It will converts a value to Decimal point value

ToDouble It will converts a type to double data type

ToInt16 It will converts a type to 16-bit integer

ToInt32 It will converts a type to 32 bit integer

ToInt64 It will converts a type to 64 bit integer

ToString It will converts a given type to string

ToUInt16 It will converts a type to unsigned 16 bit integer

ToUInt32 It will converts a type to unsigned 32 bit integer

ToUInt64 It will converts a type to unsigned 64 bit integer

Example :

// C# program to demonstrate the

// Built- In Type Conversion Methods

using System;

namespace Casting{

class GFG {

// Main Method

public static void Main(String []args)

int i = 12;

double d = 765.12;

float f = 56.123F;

// Using Built- In Type Conversion

// Methods & Displaying Result

Console.WriteLine(Convert.ToString(f));

Console.WriteLine(Convert.ToInt32(d));

Console.WriteLine(Convert.ToUInt32(f));

Console.WriteLine(Convert.ToDouble(i));

Console.WriteLine("GeeksforGeeks");
} } }

Output:

56.123
765
56
12

ma

Passing By Reference
When the parameters are passed by reference to a method, new memory variables are not created for
these parameters. Rather, the reference parameters point to the original parameters so that the
changes done in the reference variables reflect back to the original values.

The reference parameters can be declared using the ref keyword in C#. A program that demonstrates
this is as follows:

Source Code: Program that demonstrates passing by reference in C#

using System;
namespace PassByRefDemo
{
class Example {
static void Swap(ref int m, ref int n)
{
int temp;
temp = m;
m = n;
n = temp;
}
static void Main(string[] args)
{
int a = 5;
int b = 10;
Console.WriteLine("Passing By Reference");
Console.WriteLine("Before Swap method is called");
Console.WriteLine("a = {0}", a);
Console.WriteLine("b = {0}", b);
Swap(ref a, ref b);
Console.WriteLine("After Swap method is called");
Console.WriteLine("a = {0}", a);
Console.WriteLine("b = {0}", b);
}}}

The output of the above program is as follows:

Passing By Value
Before Swap method is called
a=5
b = 10
After Swap method is called
a = 10
b=5

In the above output, you can see the values get swapped successfully.

Output Parameters
The output parameters are useful in transferring data out of the method. They can be used to return
multiple values while the return statement can only return one value at a time. The out keyword is used
to declare an output parameter.

A program that demonstrates this is as follows:

Source Code: Program that demonstrates output parameters in C#

using System;
namespace OutputDemo
{
class Example {
static void OutValue(out int val )
{
val = 7;
}
static void Main(string[] args)
{
int num = 4;
Console.WriteLine("Value of num before calling OutValue: {0}", num);
OutValue(out num);
Console.WriteLine("Value of num after calling OutValue: {0}", num);
} }}

The output of the above program is as follows:


Value of num before calling OutValue: 4
Value of num after calling OutValue: 7

You might also like