C# Unit II
C# Unit II
// namespace declaration
namespace HelloWorldApp {
// Class declaration
class Geeks {
// Main Method
static void Main(string[] args) {
// statement
// printing Hello World!
Console.WriteLine("Hello World!");
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.
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.
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;
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.
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
-32768 to
short System.Int16 signed integer 16 32767 0
unsigned
byte System.byte integer 8 0 to 255 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.
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
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
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
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 :
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);
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
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());
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.
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"};
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.
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.
using System;
namespace example_enum
{
class Program
{
public enum DayofWeek
{
Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
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 –
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 −
&& 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# −
= 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
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,
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,
balance[0] = 4500.0;
You can assign values to the array at the time of declaration, as shown −
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 −
The following example, demonstrates the above-mentioned concepts declaration, assignment, and accessing
arrays −
using System;
namespace ArrayApplication {
class MyArray {
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
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;
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.
You can even directly assign these values without using the new operator.
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.
string[,] mutliDimStringArray;
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.
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.
The System.String data type is used to represent a string in .NET. A string in C# is an object of type System.String.
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. }
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:
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.
class Program {
// Main Method
public static void Main()
{
// Assigning value
string val = "Dog";
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.
class Program {
// Main method
static public void Main()
{
// Creating variable
// without assigning value
int num;
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. }
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.
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.