Quick Reference Study Notes for C Sharp .NET 4.5 Development (Advanced)

 C Sharp .NET 4.5 Development

C# .NET 4.5 Overview

C# is a type safe object oriented language that enables developers to build variety of secure and robust applications to execute on the .NET framework.

C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and approved by European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO).

C# was developed by Anders Hejlsberg and his team during the development of .Net Framework.

User can create Windows client applications, XML web services, distributed components, client – server applications and database applications.

C# constructs closely follow traditional high-level languages and has numerous strong  programming features that make it powerful and attractive to a number of programmers worldwide.It helps the user to perform all work similar to the C++ application.

C# supports encapsulation, inheritance, polymorphism. Pointers,  interoperability feature, unsafe code for memory access and other powerful features like Automatic Garbage Collection, Multithreading, asynchronous programming, LINQ and Lambda Expressions, Delegates , Indexers ,Support for Integration with Windows.

C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows use of various high-level languages on different computer platforms and architectures.

Although the.NET Framework originally was developed to run on the Windows operating system, but  now there are some alternative versions available that work on other operating systems. Mono is an open-source version of the .NET Framework which includes a C# compiler and runs on several operating systems, including various flavors of Linux and Mac OS


Release History of c# .Net Framework

Over the time many versions has been released in different packs of Visual studio which incorporates different versions  of c# included on .Net framework version inside Visual studio.Below is the list of important version changes and some useful features -   

Visual Studio Pack      

.Net framework           


  Description of features




First version of .net framework and includes basic object oriented features.




  C# was packaged with features  like Generics (with generic collection) Nullable Types, Support of IPv6 addresses in .net remoting, Nullables, Anonymous methods, Private setters (properties), iterators and Covariance and contravariance

were added with new Common Language Runtime version 2.0. .




The major changes incorporated in this pack of visual studio, were the LINQ technique and Addin / Plugin Model in .Net framework 3.5 and c# 3.0 version was included with additional package changes with code package for Implicitly Typed Local Variables,Extension Methods, Lambda Expressions, Type Inference, Object and Collection Initializers, Anonymous Types, Automatically Implemented Properties, Expression Trees.




Some more useful features like Parallel Computing, Code Contracts,Dynamic Language Runtime,Background garbage collection,Generic Covariance and Contravariance with updated Common Language Runtime 4.0 were added in .Net framework 4.0 for Visual studio pack 2010 and package code in c# included support Support for Covariance and Contravariance, Optional parameters and named arguments handling,Support for Dynamic and DLR and Enhanced support for COM interop.




More Advanced features from .Net platform were released with version 4.5 which included support for enhanced regular expressions,default culture for application domain,zip compression,support of array with size more than 2GB, asynchronous file operations, improvement in parallel computing and C# was included in this visual studio pack with release version 5 and included the package components for Async / Await Feature and support for caller information.




This pack included the features Read-only auto-properties,Auto-property initializers:,await in catch and finally blocks,Improved overload resolution:




Improvement over features of Out variables,Tuples and deconstruction,Pattern matching, Local functions,Expanded expression bodied members, Ref locals and returns was incorporated in this pack


Basics of c# programming


Name of a memory location for storing data on which set of operations can be applied and these are reusable in nature.

Syntax of declaring variable in c# :-

<data_type> <variable_list>;

Examples -

  1. int i, j;  

  2. double d;      

  3. float f;      

  4. char ch;   

We can store value in variable at the time of declaration, accordingly its format will be <data_type> <variable_name>=value;

or at any other place at the accessible location using assignment expression without datatype in front of variable name.


To perform different set of operations on variables, many different category of operators like arithmetic, logical, bitwise etc. are available and are shown in chart below:.

Operator Precedence






()  [] -> .  ++ - -

Left to right


+  - !  ~ ++ - -  (type)* and  sizeof

Right to left


*   / %

Left to right


+  -

Left to right


<<  >>

Left to right


<  <= >  >=

Left to right


==  !=

Left to right

Bitwise AND


Left to right

Bitwise XOR


Left to right

Bitwise OR


Left to right

Logical AND


Left to right

Logical OR


Left to right



Right to left


=   += -=   *= /= %=  >>= <<= &=  ^= |=

Right to left



Left to right


It is a reserved word which has a specific meaning and purpose in the c# terminology  and these cannot be used as a variable name, constant name etc.

There is a long list of reserved words, Some of theses are terms used for specifying data type like char, int float etc, decision making words if,else,for, while , switch and many other terms which has specific purpose.


These are fixed values(referred as literals) that the program may not alter during its execution. Keyword const is used to declare the variable as a constant. Syntax for declaration is :

const <data_type> <constant_name> = value;

The fixed value can be a string , int, float or character constants (includes escape or universal character along with plain characters) based on its data type specified.


Comments are the non-executable statements  which are ignored by c# compiler and generally used for stating purpose ogram of specific blocks or lines of code. There are three ways through which we can add comments in C#—

  1. Single-line (begin with the double forward slash marker, //. )

  2. Multiline (begin comment /* and end comment */ markers) and

  3. XML(start with a triple slash ///)



C# Data Types

Categories of Data types  -

  • Value types  :   Value Data Type contains data  value directly

            Built in values  - bool, byte char decimal double float int

            User defined value types : structures, enumerations

  • Reference types    : The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables.Reference types have null value by default, when they are not initialized.

Built in types - String, dynamic and Object.

User defined types :All arrays, even if their elements are value types, Classes and Interface

  • Pointer types    :  store the memory address of another type.Code block that uses a pointer variable is called the unsafe code or the unmanaged code We can declare pointer to an integer,pointer to a double, pointer to a float, pointer to a character and is represented by the *. Its general format is type *var-name;

Some Useful built-in types in C#.Net

Anonymous type ( var )

  • Anonymous type, as the name suggests, is a type that doesn't have any name. C# allows you to create an object with the new keyword without defining its class. The implicitly typed variable- var is used to hold the reference of anonymous types.

  • type of variable declared is decided by the compiler at compile time.

  • Need to initialize at the time of declaration.

  • Visual Studio shows intellisense since the type of variable assigned is known to compiler.

  • Errors are caught at compile time.

  • Anonymous type is a reference type and all the properties are read-only.

  • An anonymous type will always be local to the method where it is defined.


This was a new type introduced by C# 4.0 (.NET 4.5) that avoids compile time type checking. Instead, it resolves type at run time. A dynamic type can be defined using the dynamic keyword.

  • - The dynamic types do not have intellisense support in visual studio.

  • - A method can have parameters of the dynamic type.

  • - An exception is thrown at runtime if a method or property is not compatible.


C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null value.

-Syntax for declaring a nullable type is as follows −

< data_type> ? <variable_name> = null;

For example, you can store any value from integer range plus null value for nullable int type as -      Int? i=null;

User-defined types


  • store fixed number of values sequentially using special syntax

  • An array can be declared using a type name followed by square brackets [].

int[] intArray; // can store int values

bool[] boolArray; // can store boolean values

string[] stringArray; // can store string values

double[] doubleArray; // can store double values

byte[] byteArray; // can store byte values

Student[] customClassArray; // can store instances of Student class

Array Declaration & Initialization Examples :

  • Format for defining array with size 5 where  values will be added later on

int[] intArray1 = new int[5];

  • Format for  defining array with size 5 and adding values at the same time

int[] intArray2 = new int[5]{1, 2, 3, 4, 5};

  • Format for defining array with 5 elements which indicates the size of an array

int[] intArray3 = {1, 2, 3, 4, 5};

Arrays initialized after declaration (Late Initialization)

string[] strArray; strArray = {"1st Element","2nd Element","3rd Element","4th Element" };

  • You can access one of the array elements directly by its index location for example : intArray[2]

  • An Array can be single dimensional, multi-dimensional and jagged array.

Multi-dimensional - two dimensional series like rows and columns.

Example of Multidimensional array :
            int[,] intArray = new int[3,2]{ {1, 2}, {3, 4}, {5, 6} };

Jagged array -  also known as "array of arrays" because its elements are arrays

Example of Jagged Array :

int[][] arr = new int[2][];  

This jagged array that has two elements. The size of each element array can be different like this -

arr[0] = new int[4];  

arr[1] = new int[6];  

One of the initialization approach of arrays can be like this -

  1. arr[0] = new int[4] { 11, 21, 56, 78 };         

  2. arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 };  

  • C#.Net also provides the Array helper class which includes utility methods for arrays like Sort() , Reverse() etc.


It is a value type data type and helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure.

  • Structures can have methods, fields, indexers, properties, operator methods, and events.

  • Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed.

  • A structure can implement one or more interfaces.

  • Structure members cannot be specified as abstract, virtual, or protected.

Simple Example -

struct Student{
  public string Name;
  public int RollNumber;
  public string Course;

Example of creating object(or variable) of Structure data type :

    Student s1;

    Student s2;

   /* s1 specification */
     s1.Name = "Nuha Ali";

     s1.RollNumber = 6495407;
     s1.Course = "B.Tech";
     /* s2 specification */
     s2.Name = "Zara Ali";
     s2.RollNumber = 6495700;
     s2.Course =  "B.Tech";


enum is a value type data type and is used to declare a list of named integer constants i.e to give a name to each constant so that the constant integer can be referred using its name.

The general syntax of using enum data type is

enum <enum_name> {
  enumeration list


enum WeekDays { Monday = 0, Tuesday =1, Wednesday = 2, Thursday = 3, Friday = 4, Saturday =5, Sunday = 6 }

You can check the enum value of Wednesday like this -

Console.WriteLine(WeekDays.Thursday );

It will print 3 on console screen.

  • The value of enum constants starts from 0. Enum can have value of any valid numeric type.

  • enum cannot be used with string type.

Control Statements

C# provides many decision making statements that help regulate the flow of the C# program based on certain logical conditions. C# includes the decision making and control statements.

if statements -  if statement is used to test the condition and there are various types of if statements in C#.

if statement

   // execute this code block if condition expression evaluates to true

if else statement

// execute this code block if condition expression evaluates to true
// always execute this code block when above if expression is false

if else if ladder

// execute this code block if condition 1 evaluates to true

else if(condition2)


// execute this code block if condition 2 evaluates to true

// always execute this code block when above if, else if expressions all are false.

nested if statement

If statements can also be created inside another if statements

Ternary operator ?:

special type of decision making operator.

First part (before ?) includes conditional expression that returns boolean value true or false. Second part (after ? and before :) contains a statement which will be returned if the conditional expression in the first part evaluatesto true. The third part includes another statement which will be returned if the conditional expression returns false.


Condition Expression ? First Statement : Second Statement

Example :

int x = 20, y = 10;

var result = x > y ? "x is greater than y" : "x is less than or equal to y";

Will result in true condition , so "x is greater than y" will be stored in result variable.

  • It can be used to replace a short if-else statement.

  • A nested ternary operator is allowed. It will be evaluted from right to left.

For loop

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.

for ( init; condition; increment ) {

You can create as many nested loops


while(condition) {

A while loop statement in C# repeatedly executes a target statement as long as a given condition is true.

do {
} while( condition );

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.


The C# break is used to break loop or switch statement. It breaks the current flow of the program at the given condition. In case of inner loop, it breaks only inner loop. Syntax for writing break statement : break;   


To skip some operations from loops. It continues the current flow of the program and skips the remaining code at specified condition in loop. In case of inner loop, it continues only inner loop.

Goto statement

The C# goto statement is also known jump statement. It is used to transfer control to the other part of the program. It unconditionally jumps to the specified label.

        public class class_name

         { public static void Main(string[] args)  




                       if (condition){

                                goto Label_name;






A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main. To use a method, you need to define the method and call the method. The basic format for using method is -

             <Access Specifier> <Return Type> <Method Name>(Parameter List) {
                  //Method Body

  • Access Specifier − determines the visibility of a variable or a method from another class.

  • Return type − The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void.

  • Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class.

  • Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.

  • Method body − This contains the set of instructions needed to complete the required activity.
         public int Sum(int num1, int num2) {
               return num1+num2;
         To use at accessible location in same scope, we will simply write the calling statement as -
                  result= Sum(a, b); //where a and b  integer values.

  • A method can call itself. This is known as recursion

Passing Parameters to a Method

Pass By Value :


<method_name>(int x,int y)

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

Pass By Reference :

Class class_name{

   <method_name>(ref int x, ref int y){


Class main_class_name

static void Main(string[] args) {

         class_name obj;

         /* calling a function to swap the values */
        obj.<method_name>(ref a, ref b);


This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.

Output Parameters :

Example of using out parameters -

public void getValues(int a, int b, out int x, out int y ) {
         x = a+b;
         y = a*b;

To return more than one value from method, out keyword is used for function parameters which stores the modified values from the method.


Casting and Type Conversions

Type conversion is converting one type of data to another type.However, you might sometimes need to copy a value into a variable or method parameter of another type. For example, you might have an integer variable that you need to pass to a method whose parameter is typed as double. Or you might need to assign a class variable to a variable of an interface type. These kinds of operations are called type conversions. In C#, you can perform the following kinds of conversions:

  • Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.

  • Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.

     Example :  double x = 1234.7;
                       int a;
                       a = (int)x; // Cast double to int

  • Conversions with helper classes: To convert between non-compatible types, you can use the System.BitConverter class, the System.Convert class, and the Parse methods of the built-in numeric types, such as Int32.Parse.Convert class methods such as ToBoolean(), ToByteToChar(), ToDateTime(),ToDecimal(), ToDouble(), ToInt16(), ToInt32(),ToInt64(), ToSingle(), ToUInt32(),ToUInt64(). Another benefit of Convert classes is ability to handle  nulls while conversion.

Boxing and Unboxing

There are 2 categories  of Conversions-

When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing.

Boxing example  : int i = 123;

                            object o = i;

                            int i = 123;
                            object o = (object)i; // explicit boxing

Unboxing :
                             int i = 123; // a value type
                             object o = i; // boxing
                             int j = (int)o; // unboxing

Attempting to unbox null causes a NullReferenceException. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.

Classes and Objects

Class is a blueprint for a data type and it enables you to create your own custom types by grouping together variables of other types, methods and events.In object oriented programming, a class defines certain properties, fields, events, method etc.

Object is an instance of a class and all the members of the class can be accessed through object.

General format of class (along with constructors) :

<access specifier> class  class_name {
  // member variables
  <access specifier> <data type> variable1;
  <access specifier> <data type> variable2;

  <access specifier> <data type> variableN;

  class_name(){       …... }    // constructor  

  class_name (<data type> variableN){   …..} // parameterized contructor
  ~class_name(){  ….. }   // destructor
  // member methods
  <access specifier> <return type> method1(parameter_list) {
     // method body
  <access specifier> <return type> method2(parameter_list) {
     // method body
  <access specifier> <return type> methodN(parameter_list) {
     // method body

Access specifiers specify the access rules for the members as well as the class itself. If not mentioned, then the default access specifier for a class type is internal. Default access for the members is private.

To access the class members, you use the dot (.) operator.

  • General syntax  for creating object     : class_name object_name;

  • A class can have parameterized or parameter less constructors. The constructor will be called when you create an instance of a class. Constructors can be defined by using an access modifier and class name: <access modifiers> <class name>(){ }

  • Property encapsulates a private field. It provides getters (get{}) to retrieve the value of the underlying field and setters (set{}) to set the value of the underlying field.if you don't want to apply some logic in get or set, you can apply an auto-implemented property like this - public int MyAutoImplementedProperty { get; set; }

  • Namespace is a container for a set of related classes and namespaces. Namespace is also used to give unique names to classes within the namespace name. Namespace and classes are represented using a dot (.).

namespace mynamespace { class MyClass { } }


It is a process in which one object acquires all the properties and behaviors of its parent object automatically

C# does not support multiple inheritance(multiple parents). However, you can use interfaces to implement multiple inheritance.

Basic syntax :

<access-specifier> class <base_class> {
class <derived_class> : <base_class> {


Generics allow you to define a class with placeholders for the type of its fields, methods, parameters, etc. Generics replace these placeholders with some specific data type at compile time. Below is a simple generic class example format.

class MyGenericClass<T> {

   private T genericMemberVariable;

   public MyGenericClass(T value) { genericMemberVariable = value; }

   public T genericMethod(T genericParameter) {


           return genericMemberVariable;


  public T genericProperty { get; set; }


This class can be instantiated as-

   MyGenericClass<int> gebObj= new MyGenericClass<int>(10);

   int val = gebObj.genericMethod(200);


These are specialized classes that hold many values or objects in a specific series'. There are two types of collections available in C#: non-generic collections and generic collections.

Non-generic collections -

ArrayList - comes with additional capabilities than array where you can add and remove items specified position. It also allows dynamic memory allocation, adding, searching and sorting items in the list.

Hashtable- Hashtable stores key and value pairs.The key is used to access the items in the collection.

BitArray - It represents an array of the binary representation using the values 1 and 0. Items from the BitArray can be accessed using an integer index, which starts from zero.

SortedList - It uses a key as well as an index to access the items in a list.

A sorted list is a combination of an array and a hash table.

Stack - Stack stores the values in LIFO style (Last In First Out). It provides a Push() method to add a value and Pop() & Peek() methods to retrieve values

Queue- stores the values in First In First Out style. It keeps the order in which the values were added. It provides an Enqueue() method to add values and a Dequeue() method to retrieve values from the collection.

The limitation of non-generic collections is that while retrieving items, you need to cast into the appropriate data type, otherwise the program will throw a runtime exception.

C# also includes generic form of SortedList, Stack  and queue collection (i.e the generic SortedList<TKey,TValue> , Stack<T> and Queue<T> collections)

Other Generic Collection classes are -

List<T> : contains elements of specified type. It grows automatically as you add elements in it.

Dictionary<TKey,TValue> : contains key-value pairs.

Hashset<T>:  contains non-duplicate elements and eliminates duplicate elements.

File Handling

The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file etc.

Some of the useful file handling classes are :




Helps in manipulating files.


Used for performing operations on files.


Helps in manipulating a directory structure.


Used for performing operations on directories.


Performs operations on path information.


Used for reading characters from a byte stream. It involves reading from text files.


Is used for writing characters to a stream.It involves writing into text files.


Used to read from and write to any location in a file.


It involves reading from binary files.


It involves writing into binary files.


Important Methods of Static File Class

AppendAllText - open appends the specified string to the file ( creates new file if not exists)

AppendText- Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist.

Copy- Copies an existing file to a new file. Overwriting a file of the same name is not allowed.,

Create - Creates or overwrites a file in the specified path,

CreateText -Creates or opens a file for writing UTF-8 encoded text.

Exists - Determines whether the specified file exists.,

ReadAllBytes - Opens a binary file, reads the contents of the file into a byte array, and then closes the file.),

ReadAllText - Opens a text file, reads all lines of the file, and then closes the file.),

WriteAllBytes - Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.,

WriteAllText - Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

Replace -Replace the file contents.


The DirectoryInfo class is derived from the FileSystemInfo class. It has various methods for creating, moving, and browsing through directories and subdirectories. This class cannot be inherited.

It has properties like Attributes, CreationTime, Exists, Extension, FullName, LastAccessTime and Name and involves operational methods  -Create(), CreateSubdirectory(string path), Delete(), GetDirectories() and GetFiles()


This class from the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream.FileStream obj parameters in sequence are  <file_name>, <FileMode Enumerator>,<FileAccess Enumerator> and<FileShare Enumerator>

The FileMode enumeration defines various methods for opening files. The members of the FileMode enumerator are −

  • Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist.

  • Create − It creates a new file.

  • CreateNew − It specifies to the operating system, that it should create a new file.

  • Open − It opens an existing file.

  • OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file.

  • Truncate − It opens an existing file and truncates its size to zero bytes.

FileAccess enumerators have members: Read, ReadWrite and Write.

FileShare enumerators have the following members −

  • Inheritable − It allows a file handle to pass inheritance to the child processes

  • None − It declines sharing of the current file

  • Read − It allows opening the file for readin.

  • ReadWrite − It allows opening the file for reading and writing

  • Write − It allows opening the file for writing


This class provides the same functionality as the static File class but you have more control on read/write operations on files by writing code manually for reading or writing bytes from a file.

Important Properties of FileInfo:

Directory - Gets an instance of the parent directory.

DirectoryName - Gets a string representing the directory's full path.

Name  - Gets the name of the file.

FullName  -Gets the full path of the directory or file.

Extension - Gets the string representing the file extension.

Exists - indicates whether a file exists.

IsReadOnly  - Gets or sets a value that determines if the current file is read only.

LastAccessTime  - Gets the time the current file was last accessed.

LastWriteTime  - Gets the time of the last written activity of the file.

Length- Gets the size, in bytes, of the current file.

Important Methods of FileInfo:

AppendText -  Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.

CopyTo    - Copies an existing file to a new file, disallowing the overwriting of an existing file.

Create   -  Creates a file.

CreateText  -   Creates a StreamWriter that writes a new text file.

Delete -  Deletes the specified file.

Open - File can be Opened in a controlled manner based on the parameters passed. Various open file formats are

  • Open(FileMode mode) : Opens a file in the specified mode.

  • Open(FileMode mode, FileAccess access) : Opens a file in the specified mode with read, write, or read/write access.

  • Open(FileMode mode, FileAccess access, FileShare share) : Opens a file in the specified mode with read, write, or read/write access and the specified sharing option.

OpenRead - Creates a read-only FileStream

Replace - Replaces the contents of a specified file with the file described by the current FileInfo object, deleting the original file, and creating a backup of the replaced file.

*NOTE : "This study material is collected from multiple sources to make a quick refresh course available to students."

This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Cookie Policy. More info. I Agree