Unit II - Introduction To C#
Unit II - Introduction To C#
Introduction
C# is an object-oriented programming language developed by Microsoft by Anders Hejlsberg
and his team.
Main features of C#
1. Simple
Most of the confusing and complicated things are removed in C#, such as there is no
usage of scope resolution operator "::" or "->" operators. Unsafe operations such as direct
memory manipulation are not allowed. There is no need to handle memory explicitly. It
supports automatic memory management and garbage collection. Next important change
is that, "= =" is used for comparison operation and "=" is used for assignment operation.
assignment operation (=) cannot be used in "if" or “while” statement. If you use, It will
give compile time error.
2. Object oriented
C# supports all features of object oriented language such as class, object, Data
Encapsulation, inheritance, polymorphism, interfaces.
3. Type safe
Pointers are not directly supported by .NET. C# - Types are safe. Type-safe code
accesses only the memory locations it is authorized to access.
Example:
string empName = 10; //cause an error
int a = "Hello World"; // cause an error
double db = d; //cause an error
All of the above code will give compile time error.
While accessing the array, C# checks the range and warned if it goes out-of-bounds.
4. Interoperability
C# includes native support for the COM and windows based applications.We can easily
access the Components (dll) from VB. NET and other managed code languages using C#
and vice versa.
5. Scalable and updateable
We can upgrade code of an existing running application by using the new version of dll.
There is no registering of dynamic linking library.
Application of C#
1. Web application
2. Windows application
3. Web services
4. Windows services
5. Mobile application
6. Developing component library
Let us directly jump on our simple example that will display “Welcome at C# Tutorial” on
the console.
namespace ConsoleApplication1
class Program
System.Console.ReadLine();
C# program starts with namespaces. Namespaces are the logical grouping of related types.
Console class is available in System namespace. It is not compulsory to use name space, but
at this situation you have to append the related namespace with every types.
Example:
As you can see, the code is lengthy; therefore it would be nice if you write required
namespaces at the beginning of program.
In C# code must be contained within a class, so when you create a new console application in
Visual Studio, the template will be created automatically that have a class and main function
is written.
For writing text on console window, there are two static methods of Console class Write()
and WriteLine().
Console.ReadLine() reads user input. ReadLine() is also an static method and return type is
strings. If you execute the console application without writing the Console.ReadLine(), then
console window will disappear in seconds and you will not able to see the output. It forces
the application to wait for some input from keyboard before the application exits.
Variables in C#
A variable is a name of memory location. It is used to store data. Its value can be changed
and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
type variable_list;
int i, j;
double d;
float f;
char ch;
Here, i, j, d, f, ch are variables and int, double, float, char are data types.
We can also provide values while declaring the variables as given below:
float f=40.2;
char ch='B';
C# Data Types
A data type specifies the type of data that a variable can store such as integer, floating,
character etc.
The value data types are integer-based and floating-point based. C# language supports both
signed and unsigned literals.
The memory size of data types may change according to 32 or 64 bit operating system.
Let's see the value data types. It size is given according to 32 bit OS.
Memory
Data Types Range
Size
unsigned
2 byte 0 to 65,535
short
The reference data types do not contain the actual data stored in a variable, but they contain a
reference to the variables.
If the data is changed by one of the variables, the other variable automatically reflects this
change in value.
The pointer in C# language is a variable, it is also known as locator or indicator that points to
an address of a value.
Declaring a pointer
Boxing and unboxing is an important concept in .NET framework. Boxing and unboxing
enables you to convert value type into reference type and vice versa.
Example
System.Console.WriteLine(intVar.ToString());
Unboxing: Converting a reference type into value type is called unboxing. It is an explicit
operation.
Example
using System.Collections;
System.Console.WriteLine(intVar.ToString());
C# operators
An operator is simply a symbol that is used to perform operations. There can be many types
of operations like arithmetic, logical, bitwise etc.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Unary Operators
Ternary Operators
Misc Operators
Precedence of Operators in C#
The precedence of operator specifies that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right to
left.
The "data" variable will contain 35 because * (multiplicative operator) is evaluated before +
(additive operator).The precedence and associativity of C# operators is given below:
C# Literals
The fixed values are called as Literal. Literal is a value that is used by the variables. Values
can be either an integer, float or string, etc.
int x = 100;
Integer Literals
Floating-point Literals
Character Literals
String Literals
Null Literals
Boolean Literals
Integer Literals:
A literal of integer type is known as the integer literal. It can be octal, decimal, binary, or
hexadecimal constant. No prefix is required for the decimal numbers. A suffix can also be
used with the integer literals like U or u are used for unsigned numbers while l or L are used
for long numbers. By default, every literal is of int type. For Integral data types (byte, short,
int, long), we can specify literals in the ways:
1. Decimal literals (Base 10): In this form, the allowed digits are 0-9.
int x = 101;
2. Octal literals (Base 8): In this form, the allowed digits are 0-7.
// The octal number should be prefix with 0.
int x = 0146;
3. Hexa-decimal literals (Base 16): In this form, the allowed digits are 0-9 and
characters are a-f. We can use both uppercase and lowercase characters. As we know
that c# is a case-sensitive programming language but here c# is not case-sensitive.
// The hexa-decimal number should be prefix with 0X or 0x.
int x = 0X123Face;
4. Binary literals (Base 2): In this form, the allowed digits are only 1’s and 0’s.
// The binary number should be prefix with 0b.
int x = 0b101
Floating-point Literals:
The literal which has an integer part, a decimal point, a fractional part, and an exponent part
is known as the floating-point literal. These can be represented either in decimal form or
exponential form.
Examples:
Character Literals: For character data types we can specify literals in 3 ways:
Single quote: We can specify literal to char data type as single character within single
quote. Example : char ch = 'a';
Unicode Representation: We can specify char literals in Unicode representation
‘\uxxxx’. Here xxxx represents 4 hexadecimal numbers.
char ch = '\u0061'; // Here /u0061 represent a.
Escape Sequence: Every escape character can be specified as char literals.
char ch = '\n';
\\ \ character
\’ ‘ character
\? ? character
\” ” character
\b Backspace
\a Alert or Bell
\n New Line
\f Form Feed
\r Carriage Return
\v Vertical Tab
String Literals:
Literals which are enclosed in double quotes(“”) or starts with @”” are known as the String
literals.
Examples:
String s1 = "Hello C# Geeks!";
String s2 = @"Hello C# Geeks!";
Boolean Literals:
Only two values are allowed for Boolean literals i.e. true and false.
Example:
bool b = true;
bool c = false;
C# Expressions
An expression in C# is a combination of operands (variables, literals, method calls) and
operators that can be evaluated to a single value. To be precise, an expression must have at
least one operand but may not have any operator.
Let's look at the example below:
double temperature;
temperature = 42.05;
Here, 42.05 is an expression. Also, temperature = 42.05 is an expression too.
int a, b, c, sum;
sum = a + b + c;
Here, a + b + c is an expression.
if (age>=18 && age<58)
Console.WriteLine("Eligible to work");
Here, (age>=18 && age<58) is an expression that returns a boolean value. "Eligible to work"
is also an expression.
Enumeration
An enumeration is a set of named integer constants. By default the type of each element in
the enum is integer. It is declared using the enum keyword. By default, the value of the first
enumeration element is 0 and automatically incremented by 1 for successive element.
For creating an enumeration, the general form is
enum name { enumeration list };
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
Here Sunday has the value 0, Monday 1 and so on.
Let us take an example on enumeration. In this example, We have created two enum Days
and EditMenu.
Example
using System;
namespace ConsoleApplication1
{
enum EditMenu
{
Create=10,
Delete=20,
Add=30,
Update=40
};
class Program
{ enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
static void Main(string[] args)
{
int favDay = (int)Days.Sunday;
Console.WriteLine("My favorite day is {0} = {1}", Days.Sunday,favDay);
Console.ReadLine();
}
}
}
Output:
My favorite day is Sunday = 0
The value of enum ADD is =30
Iterating through an enum
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
C# Control Statements
C# if-else
In C# programming, the if statement is used to test the condition. There are various types of if
statements in C#.
if statement
if-else statement
nested if statement
if-else-if ladder
C# IF Statement
The C# if statement tests the condition. It is executed if condition is true.
Syntax:
if(condition){
//code to be executed
}
C# If Example
using System;
public class IfExample {
public static void Main(string[] args) {
int num = 10;
if (num % 2 == 0)
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 13
KAVITHA RAJALAKSHMI D INTRODUCTION TO C#
{
Console.WriteLine("It is even number");
}
}
}
Output:
It is even number
C# IF-else Statement
The C# if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
C# If-else Example
using System;
Output: Output:
Enter a number:11 Enter a number:12
It is odd number It is even number
}else if(condition2){
//code to be executed if condition2 is true
}
...
else{
//code to be executed if all the conditions are false
C# If else-if Example
using System;
public class IfExample{
public static void Main(string[] args) {
Output: Output:
Enter a number to check grade:66 Enter a number to check grade:-2
C Grade wrong number
C# switch
The C# switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement in C#.
Syntax:
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
C# Switch Example
using System;
Output: Output:
Enter a number: Enter a number:
10 55
It is 10 Not 10, 20 or 30
C# For Loop
The C# for loop is used to iterate a part of the program several times. If the number of
iteration is fixed, it is recommended to use for loop than while or do-while loops.
The C# for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.
Syntax:
for(initialization; condition; incr/decr){
//code to be executed
}
Output:
1
2
3
4
5
6
7
8
9
10
Output:
11
12
13
21
22
23
31
32
33
C# While Loop
In C#, while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop than for loop.
Syntax:
while(condition){
//code to be executed
}
C# Do-While Loop
The C# do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended
to use do-while loop.
The C# do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);
Syntax:
do{
//code to be executed
}while(true);
C# Arrays
Like other programming languages, array in C# is a group of similar types of elements that
have contiguous memory location. In C#, array is an object of base type System.Array. In
C#, array index starts from 0. We can store only fixed set of elements in C# array.
Advantages of C# Array
Fixed size
C# Array Types
There are 3 types of arrays in C# programming:
C# Multidimensional Arrays
The multidimensional array is also known as rectangular arrays in C#. It can be two
dimensional or three dimensional. The data is stored in tabular form (row * column) which is
also known as matrix.
To create multidimensional array, we need to use comma inside the square brackets. For
example:
int[,] arr=new int[3,3];//declaration of 2D array
int[,,] arr=new int[3,3,3];//declaration of 3D array
C# Jagged Arrays
In C#, jagged array is also known as "array of arrays" because its elements are arrays. The
element size of jagged array can be different.
Here, size of elements in jagged array is optional. So, you can write above code as given
below:
arr[0] = new int[] { 11, 21, 56, 78 };
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
C# Strings
In C#, string is an object of System.String class that represent sequence of characters. We can
perform many operations on strings such as concatenation, comparision, getting substring,
search, trim, replacement etc.
string vs String
In C#, string is keyword which is an alias for System.String class. That is why string and
String are equivalent. We are free to use any naming convention.
string s1 = "hello";//creating string using string keyword
C# String Example
C# String methods
Structure in C#
A structure is a value type, means it stores on stack. So there is no overhead to maintain the
stack and heap both. Structure does not require a separate reference variable. Its syntax is
similar to a class.
Struct is more efficient than class. All reference types are cleaned by garbage collector.
Structures cannot inherit other structures or classes. A structure in C# can contain fields.
These fields can be marked as private, public, internal. Please keep in mind that we can't
initialize a field inside a structure. However we can use parameterized constructor to initialize
the structure fields. A structure can contain constructors (Parameterized), fields, methods,
properties, indexers, operators, events, and nested types.
Structures are declared using the keyword struct.
Example
public struct Employee
{
public int EmpID;
public string Name;
public string Address;
}
Example
In the above code the structure variables obj1 and obj2 are still separate even though we have
done obj1=obj2. Both are value types so they are not refer to each other.
If we replace the structure with class then output will be different. Because, in this case the
obj1 and obj2 will be reference type. Obj1 will be refer to obj2.
obj1.x = 10, obj2.x = 20
obj1.x = 30, obj2.x = 30
Note that in the second line both value is 30.
Example
using System;
namespace ConsoleApplication1
{
struct propertyStruct
{
private int intVar ;
public int initValue
{
get
{
return intVar;
}
set
{
if (value>0)
intVar = value;
}
}
public void DisplayValue()
{
Console.WriteLine("Value is: {0}", initValue);
}
}
class Program
{
static void Main(string[] args)
{
propertyStruct obj = new propertyStruct();
obj.initValue = 25;
obj.DisplayValue();
Console.ReadLine();
}
}
}
C# Object
In C#, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality.
Object is a runtime entity, it is created at runtime.
Object is an instance of a class. All the members of the class can be accessed through object.
In this example, Student is the type and s1 is the reference variable that refers to the instance
of Student class. The new keyword allocates memory at runtime.
C# Class
In C#, class is a group of similar objects. It is a template from which objects are created. It
can have fields, methods, constructors etc.
C# Inheritance
In C#, inheritance is a process in which one object acquires all the properties and behaviors
of its parent object automatically. In such way, you can reuse, extend or modify the attributes
and behaviors which is defined in other class.
In C#, the class which inherits the members of another class is called derived class and the
class whose members are inherited is called base class. The derived class is the specialized
class for the base class.
Advantage of C# Inheritance
Code reusability: Now you can reuse the members of your parent class. So, there is no need
to define the member again. So less code is required in the class.
}
}
In the above example, Employee is the base class and Programmer is the derived class.
}
class TestInheritance2{
public static void Main(string[] args)
{
Dog d1 = new Dog();
d1.eat();
d1.bark();
}
}
C# Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many
forms. It is a greek word. In object-oriented programming, we use 3 main concepts:
inheritance, encapsulation and polymorphism.
There are two types of polymorphism in C#: compile time polymorphism and runtime
polymorphism.
C# Interface
Interface in C# is a blueprint of a class. It is like abstract class because all the methods which
are declared inside the interface are abstract methods. It cannot have method body and cannot
be instantiated.
It is used to achieve multiple inheritance which can't be achieved by class. It is used to
achieve fully abstraction because it cannot have method body.
Its implementation must be provided by class or struct. The class or struct which implements
the interface, must provide the implementation of all the methods declared inside the
interface.
C# interface example
Let's see the example of interface in C# which has draw() method. Its implementation is
provided by two classes: Rectangle and Circle.
C# Delegates
In C#, delegate is a reference to the method. It works like function pointer in C and C++. But
it is objected-oriented, secured and type-safe than function pointer.
For static method, delegate encapsulates method only. But for instance method, it
encapsulates method and instance both.
The best use of delegate is to use as event.
Internally a delegate declaration defines a class which is the derived class of
System.Delegate.
C# Delegate Example
Let's see a simple example of delegate in C# which calls add() and mul() methods.
Events
An event is an automatic notification to users that some action has occurred. Or you can say
that events are user actions such as key press, clicks, etc. When user performs some event,
your application should respond by executing function.
Steps for working with events:
1. Create a delegate that will work as event handler.
2. Declare an event with the help of delegate.
3. Register the method with the event.
4. Perform some action for executing the event.
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 38
KAVITHA RAJALAKSHMI D INTRODUCTION TO C#
using System;
namespace ConsoleApplication1
{
// Declare a delegate for an event.
delegate void MyEventHandler();
class SimpleEvent{
public event MyEventHandler MyEvent;
// This method will fire the event.
public void OnEvent(){
if (MyEvent != null)
MyEvent();
}
}
class Program{
static void Handler(){
Console.WriteLine("Hello My Event");
}
static void Main(string[] args)
{
SimpleEvent eventObject = new SimpleEvent();
// Add Handler() to the event list.
eventObject.MyEvent += Handler;
// Below line will fire the event.
eventObject.OnEvent();
Console.ReadLine();
}
}
}
In the above program we have craeted a delegate type for the event handler, as shown here:
try
{
.........
}
catch (<exceptionType> e)
{
...........
}
finally
{
..........
}
Example
In the given example, intArr is an int array of five elements. The for loop tries to execute
eight time and also tries to insert element in intArr from 0 to 8, which causes an
IndexOutOfRangeException to occur when an index value of 5 is tried.