0% found this document useful (0 votes)
19 views24 pages

C# Unit II

Uploaded by

luckymule4
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
19 views24 pages

C# Unit II

Uploaded by

luckymule4
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 24

C# basics

Compiling and Running the Program


The Hello World! program is the most basic and first program when you dive into a new programming
language. This simply prints the Hello World! on the output screen. In C#, a basic program consists of the
following:
 A Namespace Declaration
 Class Declaration & Definition
 Class Members(like variables, methods etc.)
 Main Method
 Statements or Expressions

// C# program to print Hello World!


using System;

// namespace declaration
namespace HelloWorldApp {

// Class declaration
class Geeks {

// Main Method
static void Main(string[] args) {

// statement
// printing Hello World!
Console.WriteLine("Hello World!");

// To prevents the screen from


// running and closing quickly
Console.ReadKey();
}
}
}

Explanation:
 using System: System is a namespace which contains the commonly used types. It is specified with
a using System directive.
 namespace HelloWorldApp: Here namespace is the keyword which is used to define the
namespace. HelloWorldApp is the user-defined name given to namespace. For more details, you can
refer to C# | Namespaces
 class Geeks: Here class is the keyword which is used for the declaration of classes. Geeks is the
user-defined name of the class.
 static void Main(string[] args): Here static keyword tells us that this method is accessible without
instantiating the class. void keyword tells that this method will not return anything. Main() method is the
entry point of our application. In our program, Main() method specifies its behavior with the
statement Console.WriteLine(“Hello World!”);.
 Console.WriteLine(): Here WriteLine() is a method of the Console class defined in the System
namespace.
 Console.ReadKey(): This is for the VS.NET Users. This makes the program wait for a key press and
prevents the screen from running and closing quickly.
Running the program using Visual Studio IDE: Microsoft has provided an IDE(Integrated Development
Environment) tool named Visual Studio to develop applications using different programming languages
such as C#, VB(Visual Basic) etc.
Running the program using Using Command-Line: You can also use command line options to run a C#
program. Below steps demonstrate how to run a C# program on Command line in Windows Operating
System:
 First, open a text editor like Notepad or Notepad++.
 Write the code in the text editor and save the file with .cs extension.
 Open the cmd(Command Prompt) and run the command csc to check for the compiler version. It
specifies whether you have installed a valid compiler or not. You can avoid this step if you confirmed
that compiler is installed.

 To compile the code type csc filename.cs on cmd. If your program has no error then it will create a
filename.exe file in the same directory where you have saved your program. Suppose you saved the
above program as hello.cs. So you will write csc hello.cs on cmd. This will create a hello.exe.

 Now you have to ways to execute the hello.exe. First, you have to simply type the filename i.e hello on
the cmd and it will give the output. Second, you can go to the directory where you saved your program
and there you find filename.exe. You have to simply double-click that file and it will give the output.
The using Keyword
The first statement in any C# program is

using System;

The using keyword is used for including the namespaces in the program. A program can include multiple using
statements.

The class Keyword

The class keyword is used for declaring a class.

Variables

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in
C# has a specific type, which determines the size and layout of the variable's memory the range of values
that can be stored within that memory and the set of operations that can be applied to the variable.

Defining Variables
Syntax for variable definition in C# is −
<data_type> <variable_list>;

Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined
data type, and variable_list may consist of one or more identifier names separated by commas.

Some valid variable definitions are shown here −


int i, j, k;
char c, ch;
float f, salary;
double d;

You can initialize a variable at the time of definition as −


int i = 100;

Initializing Variables
Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The
general form of initialization is −
variable_name = value;

Variables can be initialized in their declaration. The initializer consists of an equal sign followed by a
constant expression as −
<data_type> <variable_name> = value;

Some examples are −

int d = 3, f = 5; /* initializing d and f. */

byte z = 22; /* initializes z. */

double pi = 3.14159; /* declares an approximation of pi. */


char x = 'x'; /* the variable x has the value 'x'. */

The following example uses various types of variables −

using System;

namespace VariableDefinition {
class Program {
static void Main(string[] args) {
short a;
int b ;
double c;

/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}

Data Types

Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed
programming language because in C#, each type of data (such as integer, character, float, and so
forth) is predefined as part of the programming language and all constants or variables defined for a
given program must be described with one of the data types.

Data types in C# is mainly divided into three categories


 Value Data Types
 Reference Data Types
 Pointer Data Type
Value Data Types : In C#, the Value Data Types will directly store the variable value in memory and it will
also accept both signed and unsigned literals. The derived class for these data types are System.ValueType.
Following are different Value Data Typesin C# programming language:

 Signed & Unsigned Integral Types : There are 8 integral types which provide support for 8-bit,
16-bit, 32-bit, and 64-bit values in signed or unsigned form.

SIZE(BITS DEFAULT
ALIAS TYPE NAME TYPE ) RANGE VALUE

sbyte System.Sbyte signed integer 8 -128 to 127 0

-32768 to
short System.Int16 signed integer 16 32767 0

Int System.Int32 signed integer 32 -231 to 231-1 0

long System.Int64 signed integer 64 -263 to 263-1 0L

unsigned
byte System.byte integer 8 0 to 255 0

ushor System.UInt1 unsigned


t 6 integer 16 0 to 65535 0

System.UInt3 unsigned
uint 2 integer 32 0 to 232 0

System.UInt6 unsigned
ulong 4 integer 64 0 to 263 0

 Floating Point Types :There are 2 floating point data types which contain the decimal point.
 Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize a
float variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use then it is
treated as double.
 Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To
initialize a double variable, use the suffix d or D. But it is not mandatory to use suffix because
by default floating data types are the double type.

ALIAS TYPE NAME SIZE(BITS) RANGE (APROX) DEFAULT VALUE

float System.Single 32 3.4 × 1038to +3.4 × 1038 0.0F

double System.Double 64 ±5.0 × 10-324 to ±1.7 × 10308 0.0D

 Decimal Types : The decimal type is a 128-bit data type suitable for financial and monetary
calculations. It has 28-29 digit Precision. To initialize a decimal variable, use the suffix m or M.
Like as, decimal x = 300.5m;. If the suffix m or M will not use then it is treated as double.
ALIAS TYPE NAME SIZE(BITS) RANGE (APROX) DEFAULT VALUE

decimal System.Decimal 128 -7.9 × 1028to 7.9 × 1028 0.0M

 Character Types : The character types represents a UTF-16 code unit or represents the 16-bit
Unicode character.
ALIAS TYPE NAME SIZE IN(BITS) RANGE DEFAULT VALUE

char System.Char 16 U +0000 to U +ffff ‘\0’

Boolean Types : It has to be assigned either true or false value. Values of type bool are not converted
implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion
code.
ALIAS TYPE NAME VALUES

bool System.Boolean True / False

Reference Data Types : The Reference Data Types will contain a memory address of variable
value because the reference types won’t store the variable value directly in memory. The built-in
reference types are string, object.
 String : It represents a sequence of Unicode characters and its type name is System.String. So,
string and String are equivalent.
Example :

 string s1 = "hello"; // creating through string keyword


 String s2 = "welcome"; // creating through String class

Object: In C#, all types, predefined and user-defined, reference types and value types, inherit directly
or indirectly from Object. So basically it is the base class for all the data types in C#. Before assigning
values, it needs type conversion. When a variable of a value type is converted to object, it’s
called boxing. When a variable of type object is converted to a value type, it’s called unboxing. Its
type name is System.Object.

// C# program to demonstrate
// the Reference data types
using System;
namespace ValueTypeTest {

class GeeksforGeeks {

// Main Function
static void Main()
{
// declaring string
string a = "Geeks";

//append in a
a+="for";
a = a+"Geeks";
Console.WriteLine(a);

// declare object obj


object obj;
obj = 20;
Console.WriteLine(obj);

// to show type of object


// using GetType()
Console.WriteLine(obj.GetType());
}
}
}

Pointer Data Type : The Pointer Data Types will contain a memory address of the variable value.
To get the pointer details we have a two symbols ampersand (&) and asterisk (*).
ampersand (&): It is Known as Address Operator. It is used to determine the address of a variable.
asterisk (*): It also known as Indirection Operator. It is used to access the value of an address.
Syntax :
type* identifier;
Example :
int* p1, p; // Valid syntax
int *p1, *p; // Invalid

C# supports pointers in a limited extent. ... Unlike reference types, pointer types are not tracked by the default
garbage collection mechanism. For the same reasonpointers are not allowed to point to a reference type or
even to a structure type which contains a reference type.

Flow Control

In C# language there are several keywords that are used to alter the flow of the program. When the
program is run, the statements are executed from the top of the source file to the bottom. One by one.
This flow can be altered by specific keywords. Statements can be executed multiple times. Some
statements are called conditional statements. They are executed only if a specific condition is met.

C# if statement

The if statement has the following general form:

if (expression)
{
statement;
}
The if keyword is used to check if an expression is true. If it is true, a statement is then executed. The
statement can be a single statement or a compound statement. A compound statement consists of
multiple statements enclosed by the block. A block is code enclosed by curly brackets.

using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 10;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}

}
}

C# else statement

We can use the else keyword to create a simple branch. If the expression inside the square brackets
following the if keyword evaluates to false, the statement following the else keyword is automatically
executed.

using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 11;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}

}
}

C# else if

We can create multiple branches using the else if keyword. The else if keyword tests for another
condition if and only if the previous condition was not met. Note that we can use multiple else if keywords
in our tests.

using System;
public class IfExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number to check grade:");
int num = Convert.ToInt32(Console.ReadLine());

if (num <0 || num >100)


{
Console.WriteLine("wrong number");
}
else if(num >= 0 && num < 50){
Console.WriteLine("Fail");
}
else if (num >= 50 && num < 60)
{
Console.WriteLine("D Grade");
}
else if (num >= 60 && num < 70)
{
Console.WriteLine("C Grade");
}
else if (num >= 70 && num < 80)
{
Console.WriteLine("B Grade");
}
else if (num >= 80 && num < 90)
{
Console.WriteLine("A Grade");
}
else if (num >= 90 && num <= 100)
{
Console.WriteLine("A+ Grade");
}
}
}

C# switch statement

The switch statement is a selection control flow statement. It allows the value of a variable or expression
to control the flow of program execution via a multi-way branch. It creates multiple branches in a
simpler way than using the combination of if/else if/else statements.

We have a variable or an expression. The switch keyword is used to test a value from the variable or the
expression against a list of values. The list of values is presented with the case keyword. If the values
match, the statement following the case is executed. There is an optional default statement. It is executed
if no other match is found.am i

using System;
public class SwitchExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());

switch (num)
{
case 10: Console.WriteLine("It is 10"); break;
case 20: Console.WriteLine("It is 20"); break;
case 30: Console.WriteLine("It is 30"); break;
default: Console.WriteLine("Not 10, 20 or 30"); break;
}
}
}
C# while statement

The while statement is a control flow statement that allows code to be executed repeatedly based on a
given boolean condition.

This is the general form of the while loop:

while (expression)
{
statement;
}

The while keyword executes the statements inside the block enclosed by the curly brackets. The
statements are executed each time the expression is evaluated to true.

using System;
public class WhileExample
{
public static void Main(string[] args)
{
int i=1;
while(i<=10)
{
Console.WriteLine(i);
i++;
}
}
}

Do-while statement

It is possible to run the statement at least once. Even if the condition is not met. For this, we can use
the do while keywords.

using System;
public class DoWhileExample
{
public static void Main(string[] args)
{
int i = 1;

do{
Console.WriteLine(i);
i++;
} while (i <= 10) ;

}
}
C# for statement

When the number of cycles is known before the loop is initiated, we can use the for statement. In this
construct we declare a counter variable which is automatically increased or decreased in value during
each repetition of the loop.

using System;
public class ForExample
{
public static void Main(string[] args)
{
for(int i=1;i<=10;i++){
Console.WriteLine(i);
}
}
}
Nested for loops

For statements can be nested; i.e. a for statement can be placed inside another for statement. All
cycles of a nested for loops are executed for each cycle of the outer for loop.

using System;
public class ForExample
{
public static void Main(string[] args)
{
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
Console.WriteLine(i+" "+j);
}
}
}
}

C# foreach statement

The foreach construct simplifies traversing over collections of data. It has no explicit counter.
The foreach statement goes through the array or collection one by one and the current value is copied to
a variable defined in the construct.

using System;

namespace ForeachStatement
{
class Program
{
static void Main(string[] args)
{
string[] planets = { "Mercury", "Venus",
"Earth", "Mars", "Jupiter", "Saturn",
"Uranus", "Neptune"};

foreach (string planet in planets)


{
Console.WriteLine(planet);
}
}
}
}

C# break statement

The break statement can be used to terminate a block defined by while, for or switch statements.

using System;
public class BreakExample
{
public static void Main(string[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
}
}

C# continue statement

The continue statement is used to skip a part of the loop and continue with the next iteration of the loop.
It can be used in combination with for and while statements.

using System;
public class ContinueExample
{
public static void Main(string[] args)
{
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
Console.WriteLine(i);
}
}
}
Boxing and Unboxing

C# Type System contains three Types , they are Value Types , Reference Types and Pointer Types.
C# allows us to convert a Value Type to a Reference Type, and back again to Value Types . The
operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation
is called Unboxing.

1. // int (value type) is created on the Stack


2. int stackVar = 12;
3.
4. // Boxing = int is created on the Heap (reference type)
5. object boxedVar = stackVar;
6.
7. // Unboxing = boxed int is unboxed from the heap and assigned to an int stack variable
8. int unBoxed = (int)boxedVar;

Enum
An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is
used to declare an enumeration. It is a primitive data type, which is user defined.

Enums type can be integer (float, int, byte, double etc.). But if you used beside int it has to be cast.

enum is used to create numeric constants in .NET framework. All member of enum are of enum type. There must be a
numeric value for each enum type.

The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the
value of each successive enumerator is increased by 1.

enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri}

Program to demonstrate how to create and Use an Enum:

using System;

namespace example_enum
{
class Program
{
public enum DayofWeek
{
Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}

static void Main(string[] args)


{
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Sunday,DayofWeek.Sunday);
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Monday,DayofWeek.Monday);
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Tuesday,DayofWeek.Tuesday);
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Wednesday,DayofWeek.Wednesday);
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Thursday,DayofWeek.Thursday);
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Friday,DayofWeek.Friday);
Console.WriteLine("Day of week {0} {1}", (int)DayofWeek.Saturday,DayofWeek.Saturday);
Console.ReadLine();
}
}
}

Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C# has
rich set of built-in operators and provides the following type of operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators

Arithmetic Operators
Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10 and
variable B holds 20 then –

Operator Description Example

+ Adds two operands A + B = 30

- Subtracts second operand from the first A - B = -10

* Multiplies both operands A * B = 200

/ Divides numerator by de-numerator B/A=2

% Modulus Operator and remainder of after an integer division B%A=0

++ Increment operator increases integer value by one A++ = 11

-- Decrement operator decreases integer value by one A-- = 9

Relational Operators
Following table shows all the relational operators supported by C#. Assume variable A holds 10 and
variable B holds 20, then −
Operator Description Example

== Checks if the values of two operands are equal or not, if yes then condition (A == B) is not
becomes true. true.

!= Checks if the values of two operands are equal or not, if values are not equal (A != B) is true.
then condition becomes true.

> Checks if the value of left operand is greater than the value of right operand, if (A > B) is not
yes then condition becomes true. true.

< Checks if the value of left operand is less than the value of right operand, if (A < B) is true.
yes then condition becomes true.

>= Checks if the value of left operand is greater than or equal to the value of right (A >= B) is not
operand, if yes then condition becomes true. true.

<= Checks if the value of left operand is less than or equal to the value of right (A <= B) is true.
operand, if yes then condition becomes true.

Logical Operators
Following table shows all the logical operators supported by C#. Assume variable A holds Boolean value true
and variable B holds Boolean value false, then −

Operator Description Example

&& Called Logical AND operator. If both the operands are non zero then condition (A && B) is false.
becomes true.

|| Called Logical OR Operator. If any of the two operands is non zero then condition (A || B) is true.
becomes true.

! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a !(A && B) is true.
condition is true then Logical NOT operator will make false.

Assignment Operators
There are following assignment operators supported by C# −

Operator Description Example

= Simple assignment operator, Assigns values from right side operands to left side C=A+B
operand assigns value of
A + B into C

+= Add AND assignment operator, It adds right operand to the left operand and C += A is
assign the result to left operand equivalent to C =
C+A
-= Subtract AND assignment operator, It subtracts right operand from the left C -= A is
operand and assign the result to left operand equivalent to C =
C-A

*= Multiply AND assignment operator, It multiplies right operand with the left C *= A is
operand and assign the result to left operand equivalent to C =
C*A

/= Divide AND assignment operator, It divides left operand with the right operand C /= A is
and assign the result to left operand equivalent to C =
C/A

%= Modulus AND assignment operator, It takes modulus using two operands and C %= A is
assign the result to left operand equivalent to C =
C%A

<<= Left shift AND assignment operator C <<= 2 is same


as C = C << 2

>>= Right shift AND assignment operator C >>= 2 is same


as C = C >> 2

&= Bitwise AND assignment operator C &= 2 is same


as C = C & 2

^= bitwise exclusive OR and assignment operator C ^= 2 is same


as C = C ^ 2

|= bitwise inclusive OR and assignment operator C |= 2 is same as


C=C|2

C# - Arrays
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.
Declaring Arrays
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;

Initializing an Array
Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can
assign values to the array.

Array is a reference type, so you need to use the new keyword to create an instance of the array. For example,

double[] balance = new double[10];

Assigning Values to an Array


You can assign values to individual array elements, by using the index number, like −

double[] balance = new double[10];

balance[0] = 4500.0;

You can assign values to the array at the time of declaration, as shown −

double[] balance = { 2340.0, 4523.69, 3421.0};

You can also create and initialize an array, as shown −

int [] marks = new int[5] { 99, 98, 92, 97, 95};

You may also omit the size of the array, as shown −

int [] marks = new int[] { 99, 98, 92, 97, 95};

You can copy an array variable into another target array variable. In such case, both the target and source point
to the same memory location −

int [] marks = new int[] { 99, 98, 92, 97, 95};

int[] score = marks;


When you create an array, C# compiler implicitly initializes each array element to a default value depending on
the array type. For example, for an int array all elements are initialized to 0.

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index of the element within
square brackets after the name of the array. For example,

double salary = balance[9];

The following example, demonstrates the above-mentioned concepts declaration, assignment, and accessing
arrays −

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

When the above code is compiled and executed, it produces the following 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

Array Types

Arrays can be divided into the following four categories.

 Single-dimensional arrays
 Multidimensional arrays or rectangular arrays
Single Dimension Arrays

Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store number of items of
a predefined type. All items in a single dimension array are stored contiguously starting from 0 to the size of the array
-1.

The following code declares an integer array that can store 3 items. As you can see from the code, first I declare the
array using [] bracket and after that I instantiate the array by calling the new operator.

int[] intArray;

intArray = new int[3];

Array declarations in C# are pretty simple. You put array items in curly braces ({}). If an array is not initialized, its items
are automatically initialized to the default initial value for the array type if the array is not initialized at the time it is
declared.

The following code declares and initializes an array of three items of integer type.

int[] staticIntArray = new int[3] {1, 3, 5};

The following code declares and initializes an array of 5 string items.

string[] strArray = new string[5] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };

You can even directly assign these values without using the new operator.

string[] strArray = { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };

You can initialize a dynamic length array as follows:

string[] strArray = new string[] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };

Multi-Dimensional Arrays

A multi-dimensional array, also known as a rectangular array is an array with more than one dimension. The form of a
multi-dimensional array is a matrix.

Declaring a multi-dimensional array

A multi dimension array is declared as following:

string[,] mutliDimStringArray;

A multi-dimensional array can be fixed-sized or dynamic sized.

Initializing multi-dimensional arrays

The following code snippet is an example of fixed-sized multi-dimensional arrays that defines two multi dimension
arrays with a matrix of 3x2 and 2x2. The first array can store 6 items and second array can store 4 items. Both of
these arrays are initialized during the declaration.

1. int[,] numbers = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };


2. string[,] names = new string[2, 2] { { "Rosy", "Amy" }, { "Peter", "Albert" } };

Now let's see examples of multi-dimensional dynamic arrays where you are not sure of the number of items of the
array. The following code snippet creates two multi-dimensional arrays with no limit.

1. int[,] numbers = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } };


2. string[,] names = new string[,] { { "Rosy", "Amy" }, { "Peter", "Albert" } };
String in C#
In any programming language, to represent a value, we need a data type. The Char data type represents a character
in .NET. In .NET, text is stored as a sequential read-only collection of Char objects. There is no null-terminating
character at the end of a C# string; therefore a C# string can contain any number of embedded null characters ('\0').

The System.String data type is used to represent a string in .NET. A string in C# is an object of type System.String.

The String class in C# represents a string.


The following code creates three strings with a name, number and double values.

1. // String of characters
2. System.String authorName = "Mahesh Chand";
3.
4. // String made of an Integer
5. System.String age = "33";
6.
7. // String made of a double
8. System.String numberString = "33.23";

Here is the complete example that shows how to use stings in C# and .NET.

1. using System;
2. namespace CSharpStrings
3. {
4. class Program
5. {
6. static void Main(string[] args)
7. {
8. // Define .NET Strings
9. // String of characters
10. System.String authorName = "Mahesh Chand";
11.
12. // String made of an Integer
13. System.String age = "33";
14.
15. // String made of a double
16. System.String numberString = "33.23";
17.
18. // Write to Console.
19. Console.WriteLine("Name: {0}", authorName);
20. Console.WriteLine("Age: {0}", age);
21. Console.WriteLine("Number: {0}", numberString);
22. Console.ReadKey();
23. }
24. }
25. }

Parameter passing technique:


Pass by Value

When we pass a parameter to a function by value, the parameter value from the caller is copied to the function parameter.
Consider the below Example:

// C# program to illustrate value parameters


using System;

public class Program {


// Main Method
static public void Main()
{

// The value of the parameter


// is already assigned
string str1 = "Hello";
string str2 = "World";
string res = addstr(str1, str2);
Console.WriteLine(res);
}

public static string addstr(string s1, string s2)


{
return s1 + s2;
}
}
Output:
HelloWorld

Pass by Reference
When we pass a parameter to a function by reference, the reference to the actual value of the caller is copied to the function
parameter. So, at the end there are two references pointing to the same value, one from the caller, and one from the
function.

// C# program to illustrate the


// concept of ref parameter
using System;

class Program {

// Main Method
public static void Main()
{

// Assigning value
string val = "Dog";

// Pass as a reference parameter


CompareValue(ref val);

// Display the given value


Console.WriteLine(val);
}

static void CompareValue(ref string val1)


{
// Compare the value
if (val1 == "Dog")
{
Console.WriteLine("Matched!");
}

// Assigning new value


val1 = "Cat";
}
}
Output:
Matched!
Cat

OUT Parameter

The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used
when a method returns multiple values. The out parameter does not pass the property. It is not necessary to initialize
parameters before it passes to out. The declaring of parameter throughout parameter is useful when a method returns
multiple values.

// C# program to illustrate the


// concept of out parameter
using System;

class Program {

// Main method
static public void Main()
{

// Creating variable
// without assigning value
int num;

// Pass variable num to the method


// using out keyword
AddNum(out num);

// Display the value of num


Console.WriteLine("The sum of"
+ " the value is: {0}",num);

// Method in which out parameter is passed


// and this method returns the value of
// the passed parameter
public static void AddNum(out int num)
{
num = 40;
num += num;
}
}

Variable length parameter


C# provides an elegant solution to resolve preceding problem by using params keyword. Using params we can pass
variable number of parameters to a method.

There are some restrictions using the params keyword:


 You can only use the params keyword for one parameter in your method declaration.
 Params must be always the last parameter in method
Using Code

In the following code, GetConcat() is taking two params, one is separator and another is string array with params.
1. public string GetConcat(params string[] names)
2. {
3. string result = "";
4. if (names.Length > 0)
5. {
6. result += names[0];
7. }
8. for (int i = 1; i < names.Length; i++)
9. {
10. result = ", " + names[i];
11. }
12. return result;
13. }

Call the method:


1. string tempResult = GetConcat("Ajay", "Bijay", "Sanjay");
Here we are passing 4 parameters for names. Run-time compiler creates a temp array and holds all names, after that
pass GetConcat().

Multiple Main() Methods


The C# language standard requires that the Main() method always be the entry point of the program and triggers the
program execution, but the class it is in is not specified by the standard. This article will elaborate a little more on this fact
and will explain the possibility and issues of having multiple Main() methods, if at all possible, technically.

Since we have added another Main() program the compiler is now confused about which one to use and it will
now rely on the developer's decision to assign one specific Main() to the project for execution.

Go to Project -> Properties -> Application Tab -> Startup object.

You will see that both of the Main() method holders (classes) are listed there as shown in the image below.
Set a Startup object and Re-run

As shown in the previous image, select one of the Main() methods and execute the program. You shall see the
two separate messages coming from the two different Main() methods as expected.

You might also like