Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 54

 .

NET Framework
 .NET is a framework to develop software applications. It is designed and
developed by Microsoft and the first beta version released in 2000.
 It is used to develop applications for web, Windows, phone. Moreover, it provides
a broad range of functionalities and support.
 This framework contains a large number of class libraries known as Framework
Class Library (FCL). The software programs written in .NET are executed in the
execution environment, which is called CLR (Common Language Runtime). These
are the core and essential parts of the .NET framework.
 This framework provides various services like memory management, networking,
security, memory management, and type-safety.
 The .Net Framework supports more than 60 programming languages such as C#,
F#, VB.NET, J#, VC++, JScript.NET, APL, COBOL, Perl, Oberon, ML, Pascal, Eiffel,
Smalltalk, Python, Cobra, ADA, etc.
 Following is the .NET framework Stack that shows the modules and components
of the Framework.

 The .NET Framework is composed of four main components:

1. Common Language Runtime (CLR)


2. Framework Class Library (FCL),
3. Core Languages (WinForms, ASP.NET, and ADO.NET), and
4. Other Modules (WCF, WPF, WF, Card Space, LINQ, Entity Framework, Parallel
LINQ, Task Parallel Library, etc.)
 CLR (Common Language Runtime)

 It is a program execution engine that loads and executes the program. It converts
the program into native code. It acts as an interface between the framework and
operating system. It does exception handling, memory management, and
garbage collection. Moreover, it provides security, type-safety, interoperability,
and portablility. A list of CLR components are given below:

 FCL (Framework Class Library)

 It is a standard library that is a collection of thousands of classes and used to


build an application. The BCL (Base Class Library) is the core of the FCL and
provides basic functionalities.
 WinForms

 Windows Forms is a smart client technology for the .NET Framework, a set of
managed libraries that simplify common application tasks such as reading and
writing to the file system.

 ASP.NET

 ASP.NET is a web framework designed and developed by Microsoft. It is used to


develop websites, web applications, and web services. It provides a fantastic
integration of HTML, CSS, and JavaScript. It was first released in January 2002.

 ADO.NET

 ADO.NET is a module of .Net Framework, which is used to establish a connection


between application and data sources. Data sources can be such as SQL Server
and XML. ADO .NET consists of classes that can be used to connect, retrieve,
insert, and delete data.

 WPF (Windows Presentation Foundation)

 Windows Presentation Foundation (WPF) is a graphical subsystem by Microsoft


for rendering user interfaces in Windows-based applications. WPF, previously
known as "Avalon", was initially released as part of .NET Framework 3.0 in 2006.
WPF uses DirectX.

 WCF (Windows Communication Foundation)

 It is a framework for building service-oriented applications. Using WCF, you can


send data as asynchronous messages from one service endpoint to another.

 WF (Workflow Foundation)

 Windows Workflow Foundation (WF) is a Microsoft technology that provides an


API, an in-process workflow engine, and a rehostable designer to implement
long-running processes as workflows within .NET applications.

 LINQ (Language Integrated Query)

 It is a query language, introduced in .NET 3.5 framework. It is used to make the


query for data sources with C# or Visual Basics programming languages.
 Entity Framework

 It is an ORM based open source framework which is used to work with a database
using .NET objects. It eliminates a lot of developers effort to handle the database.
It is Microsoft's recommended technology to deal with the database.

 Parallel LINQ

 Parallel LINQ or PLINQ is a parallel implementation of LINQ to objects. It


combines the simplicity and readability of LINQ and provides the power of
parallel programming.

 It can improve and provide fast speed to execute the LINQ query by using all
available computer capabilities.

 Apart from the above features and libraries, .NET includes other APIs and Model
to improve and enhance the .NET framework.

 NET Common Language Runtime (CLR)

 .NET CLR is a runtime environment that manages and executes the code written
in any .NET programming language.

 CLR is the virtual machine component of the .NET framework. That language's
compiler compiles the source code of applications developed using .NET
compliant languages into CLR's intermediate language called MSIL, i.e., Microsoft
intermediate language code.

 This code is platform-independent. It is comparable to byte code in java.


Metadata is also generated during compilation and MSIL code and stored in a file
known as the Manifest file.

 This metadata is generally about members and types required by CLR to execute
MSIL code.

 A just-in-time compiler component of CLR converts MSIL code into native code
of the machine.

 This code is platform-dependent. CLR manages memory, threads, exceptions,


code execution, code safety, verification, and compilation.
 The main components of CLR are:
o Common type system Metadata and Assemblies
o Common language speciation
o Garbage Collector
o Just in Time Compiler

 Common type system:

 CTS provides guidelines for declaring, using, and managing data types at
runtime. It offers cross-language communication. For example, VB.NET has an
integer data type, and C# has an int data type for managing integers. After
compilation, Int32 is used by both data types. So, CTS provides the data types
using managed code. A common type system helps in writing language-
independent code.

 Common Language Specification (CLS):

 Common Language Specification (CLS) contains a set of rules to be followed by


all NET-supported languages. The common rules make it easy to implement
language integration and help in cross-language inheritance and debugging.
Each language supported by NET Framework has its own syntax rules. But CLS
ensures interoperability among applications developed using NET languages.

 Garbage Collection:

 Garbage Collector is a component of CLR that works as an automatic memory


manager. It helps manage memory by automatically allocating memory
according to the requirement. It allocates heap memory to objects. When objects
are not in use, it reclaims the memory allocated to them for future use. It also
ensures the safety of objects by not allowing one object to use the content of
another object.

 Just in Time (JIT) Compiler:

 JIT Compiler is an important component of CLR. It converts the MSIL code into
native code (i.e., machine-specific code). The .NET program is compiled either
explicitly or implicitly. The developer or programmer calls a particular compiler to
compile the program in the explicit compilation. In implicit compilation, the
program is compiled twice. The source code is compiled into Microsoft
Intermediate Language (MSIL) during the first compilation process. The MSIL
code is converted into native code in the second compilation process. This
process is called JIT compilation. There are three types of JIT compilers -Pre,
Econo, and Normal. Pre JIT Compiler compiles entire MSIL code into native code
before execution. Econo JIT Compiler compiles only those parts of MSIL code
required during execution and removes those parts that are not required
anymore. Normal JIT Compiler also compiles only those parts of MSIL code
required during execution but places them in cache for future use. It does not
require recompilations of already used parts as they have been placed in cache
memory.

 Metadata:

 A Metadata is a binary information about the program, either stored in a CLR


Portable Executable file (PE) along with MSIL code or in the memory. During the
execution of MSIL, metadata is also loaded into memory for proper interpretation
of classes and related. Information used in code. So, metadata helps implement
code in a language-neutral manner or achieve language interoperability.

 Assemblies:

 An assembly is a fundamental unit of physical code grouping. It consists of the


assembly manifest, metadata, MSIL code, and a set of resources like image files. It
is also considered a basic deployment unit, version control, reuse, security
permissions, etc.

 .NET CLR Functions


o It converts the program into native code.
o Handles Exceptions
o Provides type-safety
o Memory management
o Provides security
o Improved performance
o Language independent
o Platform independent
o Garbage collection
o Provides language features such as inheritance, interfaces, and overloading for object-
oriented programs.

 The code that runs with CLR is called managed code, whereas the code outside
the CLR is called unmanaged code.

 The CLR also provides an Interoperability layer, which allows both the managed
and unmanaged codes to interoperate.

 .NET Framework Class Library

 .NET Framework Class Library is the collection of classes, namespaces, interfaces


and value types that are used for .NET applications.

 It contains thousands of classes that supports the following functions.

o Base and user-defined data types


o Support for exceptions handling
o input/output and stream operations
o Communications with the underlying system
o Access to data
o Ability to create Windows-based GUI applications
o Ability to create web-client and server applications
o Support for creating web services

 .NET Framework Class Library Namespaces


 .NET Framework Base Class Library

 .NET Base Class Library is the sub part of the Framework that provides library
support to Common Language Runtime to work properly. It includes the System
namespace and core types of the .NET framework.

 C# Tutorial
 C# is a programming language of .Net Framework.

 Our C# tutorial includes all topics of C# such as first example, control statements,
objects and classes, inheritance, constructor, destructor, this, static, sealed,
polymorphism, abstraction, abstract class, interface, namespace, encapsulation,
properties, indexer, arrays, strings, regex, exception handling, multithreading, File
IO, Collections etc.

 C# is pronounced as "C-Sharp". It is an object-oriented programming language


provided by Microsoft that runs on .Net Framework.

 By the help of C# programming language, we can develop different types of


secured and robust applications:

 Window applications
 Web applications
 Distributed applications
 Web service applications
 Database applications etc.

 C# is approved as a standard by ECMA and ISO. C# is designed for CLI (Common


Language Infrastructure). CLI is a specification that describes executable code and
runtime environment.

 C# programming language is influenced by C++, Java, Eiffel, Modula-3, Pascal


etc. languages.

 History of C# language is interesting to know. Here we are going to discuss


brief history of C# language.

 C# is pronounced as "C-Sharp". It is an object-oriented programming language


provided by Microsoft that runs on .Net Framework.

 Anders Hejlsberg is known as the founder of C# language.

 It is based on C++ and Java, but it has many additional extensions used to
perform component oriented programming approach.

 C# has evolved much since their first release in the year 2002. It was introduced
with .NET Framework 1.0 and the current version of C# is 5.0.

 C# Features

1) Simple
 C# is a simple language in the sense that it provides structured approach (to
break the problem into parts), rich set of library functions, data types etc.

2) Modern Programming Language


 C# programming is based upon the current trend and it is very powerful and
simple for building scalable, interoperable and robust applications.
3) Object Oriented
 C# is object oriented programming language. OOPs makes development and
maintenance easier where as in Procedure-oriented programming language it is
not easy to manage if code grows as project size grow.

4) Type Safe
 C# type safe code can only access the memory location that it has permission to
execute. Therefore it improves a security of the program.

5) Interoperability
 Interoperability process enables the C# programs to do almost anything that a
native C++ application can do.

6) Scalable and Updateable


 C# is automatic scalable and updateable programming language. For updating
our application we delete the old files and update them with new ones.

7) Component Oriented
 C# is component oriented programming language. It is the predominant software
development methodology used to develop more robust and highly scalable
applications.

8) Structured Programming Language


 C# is a structured programming language in the sense that we can break the
program into parts using functions. So, it is easy to understand and modify.

9) Rich Library
 C# provides a lot of inbuilt functions that makes the development fast.

10) Fast Speed


 The compilation and execution time of C# language is fast.

 C# Variable

 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.
 C# Data Types

 A data type specifies the type of data that a variable can store such as integer,
floating, character etc.

 C# Keywords

 A keyword is a reserved word. You cannot use it as a variable name, constant


name etc.
 In C# keywords cannot be used as identifiers. However, if we want to use the
keywords as identifiers, we may prefix the keyword with @ character.

 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.
 There are following types of operators to perform different types of operations in
C# language.

 Arithmetic Operators Ternary Operators


 Relational Operators Misc Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Unary Operators
Control Statement
 C# IF Statement

The C# if statement tests the condition. It is executed if condition is true.

 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.

 C# If-else Example: with input from user


we are getting input from the user using Console.ReadLine() method. It returns
string. For numeric value, you need to convert it into int
using Convert.ToInt32() method.

 C# IF-else-if ladder Statement


The C# if-else-if ladder statement executes one condition from multiple
statements.
 C# switch

The C# switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement in C#.

 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.

 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.

 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.
 C# Break Statement

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.

 C# Continue Statement

The C# continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it
continues only inner loop.

 C# 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.

It can be used to transfer control from deeply nested loop or switch case label.

 C# Function

 Function is a block of code that has a signature. Function is used to execute


statements specified in the code block. A function consists of the following
components:

Function name: It is a unique name that is used to make Function call.

Return type: It is used to specify the data type of function return value.

Body: It is a block that contains executable statements.

Access specifier: It is used to specify function accessibility in the application.

Parameters: It is a list of arguments that we can pass to the function during call.

 C# Function Syntax
<access-specifier><return-type>FunctionName(<parameters>)
{
}

 Access-specifier, parameters and return statement are optional.

1. C# Call By Value

 value-type parameters are that pass a copy of original value to the function
rather than reference. It does not modify the original value. A change made in
passed value does not alter the actual value. In the following example, we have
pass value during function call.

using System;
namespace CallByValue
{
class Program
{
// User defined function
public void Show(int val)
{
val *= val; // Manipulating valu
e
Console.WriteLine("Value inside the show function "+val);
}

static void Main(string[] args)


{
int val = 50;
Program program = new Program(); // Creating Object
Console.WriteLine("Value before calling the function "+val);
program.Show(val);
// Calling Function by passing value
Console.WriteLine("Value after calling the function " + val);
}
}
}
Output:

Value before calling the function 50


Value inside the show function 2500
Value after calling the function 50

2. C# Call By Reference

 C# provides a ref keyword to pass argument as reference-type. It passes


reference of arguments to the function rather than copy of original value. The
changes in passed values are permanent and modify the original variable value.

using System;
namespace CallByReference
{
class Program
{
// User defined function
public void Show(ref int val)
{
val *= val; // Manipulating value
Console.WriteLine("Value inside the show function "+val);
// No return statement
}

static void Main(string[] args)


{
int val = 50;
Program program = new Program(); // Creating Object
Console.WriteLine("Value before calling the function "+val);
program.Show(ref val); // Calling Function by passing referenc
e
Console.WriteLine("Value after calling the function " + val);
}
}
}

Output:

Value before calling the function 50


Value inside the show function 2500
Value after calling the function 2500

3. C# Out Parameter

C# provides out keyword to pass arguments as out-type. It is like reference-type, except


that it does not require variable to initialize before passing. We must use out keyword
to pass argument as out-type. It is useful when we want a function to return multiple
values.

using System;
namespace OutParameter
{
class Program
{
// User defined function
public void Show(out int val) // Out parameter
{
int square = 5;
val = square;
val *= val; // Manipulating value
}

static void Main(string[] args)


{
int val = 50;
Program program = new Program(); // Creating Object
Console.WriteLine("Value before passing out variable " + val);
program.Show(out val); // Passing out argument
Console.WriteLine("Value after recieving the out variable " + val);
}
}
}

Output:

Value before passing out variable 50


Value after receiving the out variable 25

 C# Arrays

 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
 Code Optimization (less code)
 Random Access
 Easy to traverse data
 Easy to manipulate data
 Easy to sort data etc.

 C# Array Types
1. Single Dimensional Array
2. Multidimensional Array
3. Jagged Array
4.
1.C# Single Dimensional Array

 To create single dimensional array, you need to use square brackets [] after the
type.

int[] arr = new int[5];//creating array

 You cannot place square brackets after the identifier.

int arr[] = new int[5];//compile time error

Solution: int[] arr = new int[5];

 C# Passing Array to Function

 to reuse the array logic, we can create function. To pass array to function in C#,
we need to provide only array name.

functionname(arrayname); //passing array


 Example: print array elements
using System;
public class ArrayExample
{
static void printArray(int[] arr)
{
Console.WriteLine("Printing array elements:");
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
public static void Main(string[] args)
{
int[] arr1 = { 25, 10, 20, 15, 40, 50 };
int[] arr2 = { 12, 23, 44, 11, 54 };
printArray(arr1);//passing array to function
printArray(arr2);
}
}
Printing array elements:
25
10
20
15
40
50
Printing array elements:
12
23
44
11
54
2.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.

int[,] arr=new int[3,3]; //declaration of 2D array


int[,,] arr=new int[3,3,3]; //declaration of 3D array

using System;
public class MultiArrayExample
{
public static void Main(string[] args)
{
int[,] arr=new int[3,3]; //declaration of 2D array
arr[0,1]=10; //initialization
arr[1,2]=20;
arr[2,0]=30;

//traversal
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
Console.Write(arr[i,j]+" ");
}
Console.WriteLine(); //new line at each row
}
}
}

Output:

0 10 0
0 0 20
30 0 0

 Declaration and initialization at same time

int[,] arr = new int[3,3]= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };


int[,] arr = new int[,]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

 C# Jagged Arrays

 jagged array is also known as "array of arrays" because its elements are arrays.
The element size of jagged array can be different.

 Declaration of Jagged array


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

 Initialization of Jagged array


1. arr[0] = new int[4];
2. arr[1] = new int[6];

 Initialization and filling elements in Jagged array


1. arr[0] = new int[4] { 11, 21, 56, 78 };
2. arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 };

 Here, size of elements in jagged array is optional. So, you can write above code
as given below:

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


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

public class JaggedArrayTest


{
public static void Main()
{
int[][] arr = new int[2][];// Declare the array

arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array
arr[1] = new int[] { 42, 61, 37, 41, 59, 63 };
// Traverse array elements
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr[i].Length; j++)
{
System.Console.Write(arr[i][j]+" ");
}
System.Console.WriteLine();
}
} 11 21 56 78
} 42 61 37 41 59 63

 C# Params

 params is a keyword which is used to specify a parameter that takes


variable number of arguments. It is useful when we don't know the number
of arguments prior. Only one params keyword is allowed and no additional
parameter is permitted after params keyword in a function declaration.

using System;
namespace AccessSpecifiers
{
class Program
{
// User defined function
public void Show(params int[] val) // Params Paramater
{
for (int i=0; i<val.Length; i++)
{
Console.WriteLine(val[i]);
}
}
// Main function, execution entry point of the program
static void Main(string[] args)
{
Program program = new Program(); // Creating Object
program.Show(2,4,6,8,10,12,14); // Passing arguments of variable length
}
}
}

Output:

2
4
6
8
10
12
14
 C# Command Line Arguments

 Arguments that are passed by command line known as command line arguments.
We can send arguments to the Main method while executing the code. The
string args variable contains all the values passed from the command line.

using System;
namespace CSharpProgram
{
class Program
{
// Main function, execution entry point of the program
static void Main(string[] args) // string type parameters
{
// Command line arguments
Console.WriteLine("Argument length: "+args.Length);
Console.WriteLine("Supplied Arguments are:");
foreach (Object obj in args)
{
Console.WriteLine(obj);
}
}
}
}

Output: Argument length: 5


Supplied Arguments are:
Hi
there,
how
are
you?

 C# Object

 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.

Student s1 = new Student();//creating an object of Student

 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

 class is a group of similar objects. It is a template from which objects are created.
It can have fields, methods, constructors etc.

 example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.
using System;
public class Student
{
int id; //data member (also instance variable)
String name; //data member(also instance variable)

public static void Main(string[] args)


{
Student s1 = new Student();//creating an object of Student
s1.id = 101;
s1.name = "Sonoo Jaiswal";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
}
} Output: 101
Sonoo Jaiswal
 C# Constructor

 constructor is a special method which is invoked automatically at the time of


object creation. It is used to initialize the data members of new object generally.
The constructor in C# has the same name as class or struct.

 There can be two types of constructors in C#.

 Default constructor
 Parameterized constructor

1.C# Default Constructor

A constructor which has no argument is known as default constructor. It is invoked at


the time of creating object.

using System;
public class Employee
{
public Employee()
{
Console.WriteLine("Default Constructor Invoked");
}
public static void Main(string[] args)
{
Employee e1 = new Employee();
Employee e2 = new Employee();
}
}

Output:

Default Constructor Invoked


Default Constructor Invoked

2.C# Parameterized Constructor

A constructor which has parameters is called parameterized constructor. It is used to


provide different values to distinct objects.

using System;
public class Employee
{
public int id;
public String name;
public float salary;
public Employee(int i, String n,float s)
{
id = i;
name = n;
salary = s;
}
public void display()
{
Console.WriteLine(id + " " + name+" "+salary);
}
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee(101, "Sonoo", 890000f);
Employee e2 = new Employee(102, "Mahesh", 490000f);
e1.display();
e2.display();
}
}
101 Sonoo 890000
102 Mahesh 490000

 C# Destructor

A destructor works opposite to constructor, It destructs the objects of classes. It can be


defined only once in a class. Like constructors, it is invoked automatically.

Note: C# destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.

 C# this
 In c# programming, this is a keyword that refers to the current instance of the
class. There can be 3 main usage of this keyword in C#.

 It can be used to refer current class instance variable. It is used if field names
(instance variables) and parameter names are same, that is why both can be
distinguish easily.
 It can be used to pass current object as a parameter to another method.
 It can be used to declare indexers.

 C# static

 static is a keyword or modifier that belongs to the type not instance. So instance
is not required to access the static members. In C#, static can be field, method,
constructor, class, properties, operator and event.

 C# static class
 The C# static class is like the normal class but it cannot be instantiated. It can
have only static members. The advantage of static class is that it provides you
guarantee that instance of static class cannot be created.

 C# static class contains only static members.


 C# static class cannot be instantiated.
 C# static class is sealed.
 C# static class cannot contain instance constructors.

Example

using System;
public static class MyMath
{
public static float PI=3.14f;
public static int cube(int n){return n*n*n;}
}
class TestMyMath
{
public static void Main(string[] args)
{
Console.WriteLine("Value of PI is: "+MyMath.PI);
Console.WriteLine("Cube of 3 is: " + MyMath.cube(3));
}
} Output: Value of PI is: 3.14
Cube of 3 is: 27

 C# static constructor

 C# static constructor is used to initialize static fields. It can also be used to


perform any action that is to be performed only once. It is invoked automatically
before first instance is created or any static member is referenced.

 C# static constructor cannot have any modifier or parameter.


 C# static constructor is invoked implicitly. It can't be called explicitly.
 Let's see the example of static constructor which initializes the static field
rateOfInterest in Account class.

using System;
public class Account
{
public int id;
public String name;
public static float rateOfInterest;
public Account(int id, String name)
{
this.id = id;
this.name = name;
}
static Account()
{
rateOfInterest = 9.5f;
}
public void display()
{
Console.WriteLine(id + " " + name+" "+rateOfInterest);
}
}
class TestEmployee
{
public static void Main(string[] args)
{
Account a1 = new Account(101, "Sonoo");
Account a2 = new Account(102, "Mahesh");
a1.display();
a2.display();

} Output: 101 Sonoo 9.5

} 102 Mahesh 9.5


 C# Structs

 classes and structs are blueprints that are used to create instance of a class.
Structs are used for lightweight objects such as Color, Rectangle, Point etc.

 Unlike class, structs in C# are value type than reference type. It is useful if you
have data that is not intended to be modified after creation of struct.

 C# Enum

 Enum in C# is also known as enumeration. It is used to store a set of named


constants such as season, days, month, size etc. The enum constants are also
known as enumerators. Enum in C# can be declared within or outside class and
structs.

 Enum constants has default values which starts from 0 and incremented to one
by one. But we can change the default value.

o enum has fixed set of constants


o enum improves type safety
o enum can be traversed

 C# Properties

 C# Properites doesn't have storage location. C# Properites are extension of fields


and accessed like fields.

 The Properties have accessors that are used to set, get or compute their values.

1. C# Properties can be read-only or write-only.


2. We can have logic while setting values in the C# Properties.
3. We make fields of the class private, so that fields can't be accessed from outside the class
directly. Now we are forced to use C# properties for setting or getting values.

using System;
public class Employee
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
class TestEmployee
{
public static void Main(string[] args)
{
Employee e1 = new Employee();
e1.Name = "Sonoo Jaiswal";
Console.WriteLine("Employee Name: " + e1.Name);

}
}

Output: Employee Name: Sonoo Jaiswal

 C# Inheritance

 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.

 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.

 C# Single Level Inheritance Example: Inheriting Fields


using System;
public class Employee
{
public float salary = 40000;
}
public class Programmer: Employee
{
public float bonus = 10000;
}
class TestInheritance
{
public static void Main(string[] args)
{
Programmer p1 = new Programmer();
Console.WriteLine("Salary: " + p1.salary);
Console.WriteLine("Bonus: " + p1.bonus);
}
}

Output:

Salary: 40000
Bonus: 10000

C# Aggregation (HAS-A Relationship)

aggregation is a process in which one class defines another class as any entity reference.

using System;
public class Address
{
public string addressLine, city, state;
public Address(string addressLine, string city, string state)
{
this.addressLine = addressLine;
this.city = city;
this.state = state;
}
}
public class Employee
{
public int id;
public string name;
public Address address;//Employee HAS-A Address
public Employee(int id, string name, Address address)
{
this.id = id;
this.name = name;
this.address = address;
}
public void display()
{
Console.WriteLine(id + " " + name + " " +
address.addressLine + " " + address.city + " " + address.state);
}
}
public class TestAggregation
{
public static void Main(string[] args)
{
Address a1=new Address("G-13, Sec-3","Noida","UP");
Employee e1 = new Employee(1,"Sonoo",a1);
e1.display();
} }
 C# Member Overloading

 If we create two or more members having same name but different in number or
type of parameter, it is known as member overloading. In C#, we can overload:

 methods,
 constructors, and
 indexed properties

It is because these members have parameters only.


 C# Method Overloading

 Having two or more methods with same name but different in parameters, is
known as method overloading in C#.

 The advantage of method overloading is that it increases the readability of the


program because you don't need to use different names for same action.

 You can perform method overloading in C# by two ways:

1. By changing number of arguments


2. By changing data type of the arguments

Example: By changing no. of arguments

Let's see the simple example of method overloading where we are changing number of
arguments of add() method.

using System;
public class Cal
{
public static int add(int a,int b)
{
return a + b;
}
public static int add(int a, int b, int c)
{
return a + b + c;
}
}
public class TestMemberOverloading
{
public static void Main()
{
Console.WriteLine(Cal.add(12, 23));
Console.WriteLine(Cal.add(12, 23, 25));
}
} output: 35
60

 C# Method Overriding
 If derived class defines same method as defined in its base class, it is known as
method overriding in C#. It is used to achieve runtime polymorphism. It enables
you to provide specific implementation of the method which is already provided
by its base class.

 To perform method overriding in C#, you need to use virtual keyword with base
class method and override keyword with derived class method.

 Let's see a simple example of method overriding in C#. In this example, we are
overriding the eat() method by the help of override keyword.

using System;
public class Animal
{
public virtual void eat(){
Console.WriteLine("Eating...");
}
}
public class Dog: Animal
{
public override void eat(){
Console.WriteLine("Eating bread...");
}
}
public class TestOverriding
{
public static void Main()
{
Dog d = new Dog();
d.eat();
} } output: Eating bread
 C# Base

 base keyword is used to access fields, constructors and methods of base class.

 You can use base keyword within instance method, constructor or instance
property accessor only. You can't use it inside the static method.

 C# base keyword: accessing base class field

 We can use the base keyword to access the fields of the base class within derived
class. It is useful if base and derived classes have the same fields. If derived class
doesn't define same field, there is no need to use base keyword. Base class field
can be directly accessed by the derived class.

using System;
public class Animal{
public string color = "white";
}
public class Dog: Animal
{
string color = "black";
public void showColor()
{
Console.WriteLine(base.color);
Console.WriteLine(color);
}
}
public class TestBase
{
public static void Main()
{
Dog d = new Dog();
d.showColor();
}
}
Output: white

black

 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. Compile time polymorphism is achieved by method overloading and
operator overloading in C#. It is also known as static binding or early binding. Runtime
polymorphism in achieved by method overriding which is also known as dynamic
binding or late binding.

using System;
public class Animal
{
public virtual void eat(){
Console.WriteLine("eating...");
}
}
public class Dog: Animal
{
public override void eat(){
Console.WriteLine("eating bread...");
}

}
public class TestPolymorphism
{
public static void Main()
{
Animal a= new Dog();
a.eat();
}
}

output: eating bread...


 C# Sealed

 C# sealed keyword applies restrictions on the class and method. If you create a
sealed class, it cannot be derived. If you create a sealed method, it cannot be
overridden.

 Note: Structs are implicitly sealed therefore they can't be inherited.


 C# Sealed class

C# sealed class cannot be derived by any class. Let's see an example of sealed class in
C#.

using System;
sealed public class Animal
{
public void eat()
{
Console.WriteLine("eating...");
}
}
public class Dog: Animal
{
public void bark()
{
Console.WriteLine("barking..."); }
}
public class TestSealed
{
public static void Main()
{
Dog d = new Dog();
d.eat();
d.bark();
}
}

Output:

Compile Time Error: 'Dog': cannot derive from sealed type 'Animal'

 C# Abstract

 Abstract classes are the way to achieve abstraction in C#. Abstraction in C# is the
process to hide the internal details and showing functionality only. Abstraction
can be achieved by two ways:
1. Abstract class
2. Interface

 Abstract class and interface both can have abstract methods which are necessary
for abstraction.

 Abstract Method

 A method which is declared abstract and has no body is called abstract method.
It can be declared inside the abstract class only. Its implementation must be
provided by derived classes. For example:

public abstract void draw();

 An abstract method in C# is internally a virtual method so it can be overridden by the derived


class.

 You can't use static and virtual modifiers in abstract method declaration.

 C# Abstract class

 abstract class is a class which is declared abstract.

 It can have abstract and non-abstract methods.

 It cannot be instantiated. Its implementation must be provided by derived


classes. Here, derived class is forced to provide the implementation of all the
abstract methods.

 Let's see an example of abstract class in C# which has one abstract method
draw(). Its implementation is provided by derived classes: Rectangle and Circle.
Both classes have different implementation.

 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# Namespaces

 Namespaces in C# are used to organize too many classes so that it can be easy to
handle the application.

 In a simple C# program, we use System.Console where System is the namespace


and Console is the class. To access the class of a namespace, we need to use
namespacename.classname. We can use using keyword so that we don't have to
use complete name all the time.

 In C#, global namespace is the root namespace. The global::System will always
refer to the namespace "System" of .Net Framework.

 Let's see a simple example of namespace which contains one class "Program".

using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Namespace!");
}
}
}

Output:
Hello Namespace!

 C# Access Modifiers / Specifiers

 C# Access modifiers or specifiers are the keywords that are used to specify
accessibility or scope of variables and functions in the C# application.

 C# Encapsulation

 Encapsulation is the concept of wrapping data into a single unit. It collects data
members and member functions into a single unit called class. The purpose of
encapsulation is to prevent alteration of data from outside. This data can only be
accessed by getter functions of the class.

 A fully encapsulated class has getter and setter functions that are used to read
and write data. This class does not allow data access directly.

Example
namespace AccessSpecifiers
{
class Student
{
// Creating setter and getter for each property
public string ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
}
 C# Strings

 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

 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


String s2 = "welcome"; //creating string using String class

Example
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "hello";
char[] ch = { 'c', 's', 'h', 'a', 'r', 'p' };
string s2 = new string(ch);
Console.WriteLine(s1);
Console.WriteLine(s2);
}
} output: hello
csharp
 C# Exception Handling

 Exception Handling in C# is a process to handle runtime errors. We perform


exception handling so that normal flow of the application can be maintained
even after runtime errors.

 In C#, exception is an event or object which is thrown at runtime. All exceptions


the derived from System.Exception class. It is a runtime error which can be
handled. If we don't handle the exception, it prints exception message and
terminates the program.

 Advantage

 It maintains the normal flow of the application. In such case, rest of the code is
executed event after exception.

 C# Exception Classes

 All the exception classes in C# are derived from System.Exception class. Let's see
the list of C# common exception classes.

 C# Exception Handling Keywords


 try
 catch
 finally, and
 throw

 C# try/catch

 exception handling is performed by try/catch statement. The try block in C# is


used to place the code that may throw exception. The catch block must be
preceded by try block.

 C# example without try/catch


using System;
public class ExExample
{
public static void Main(string[] args)
{
int a = 10;
int b = 0;
int x = a/b;
Console.WriteLine("Rest of the code");
}
} Output: Unhandled Exception: System.DivideByZeroException: Attempted to divide by
zero.

 C# try/catch example
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e) { Console.WriteLine(e); }
Console.WriteLine("Rest of the code");
}
} output: System.DivideByZeroException: Attempted to divide by zero.
Rest of the code
 C# finally

 C# finally block is used to execute important code which is to be executed


whether exception is handled or not. It must be preceded by catch or try block.

 C# finally example if exception is handled


using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e) { Console.WriteLine(e); }
finally { Console.WriteLine("Finally block is executed"); }
Console.WriteLine("Rest of the code");
}
}

Output:

System.DivideByZeroException: Attempted to divide by zero.


Finally block is executed
Rest of the code

 C# finally example if exception is not handled


using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (NullReferenceException e) { Console.WriteLine(e); }
finally { Console.WriteLine("Finally block is executed"); }
Console.WriteLine("Rest of the code");
}
} output: Unhandled Exception: System.DivideBy

 C# User-Defined Exceptions

 C# allows us to create user-defined or custom exception. It is used to make the


meaningful exception. To do this, we need to inherit Exception class.

using System;
public class InvalidAgeException : Exception
{
public InvalidAgeException(String message)
: base(message)
{

}
}
public class TestUserDefinedException
{
static void validate(int age)
{
if (age < 18)
{
throw new InvalidAgeException("Sorry, Age must be greater than 18");
}
}
public static void Main(string[] args)
{
try
{
validate(12);
}
catch (InvalidAgeException e) { Console.WriteLine(e); }
Console.WriteLine("Rest of the code");
}
}
Output:
InvalidAgeException: Sorry, Age must be greater than 18
Rest of the code

 C# Checked

 The checked keyword is used to explicitly check overflow and conversion of


integral type values at compile time.

 C# Checked Example without using checked


using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
Output: -2147483647
 See, the above program produces the wrong result and does not throw any
overflow exception.

 C# Checked Example using checked

This program throws an exception and stops program execution.

using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
checked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}
Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.

 C# Unchecked

 The Unchecked keyword ignores the integral type arithmetic exceptions. It does
not check explicitly and produce result that may be truncated or wrong.

using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
unchecked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}
Output: -2147483647

 C# SystemException class

 The SystemException is a predefined exception class in C#. It is used to handle


system related exceptions. It works as base class for system exception
namespace. It has various child classes like: ValidationException,
ArgumentException, ArithmeticException, DataException, StackOverflowException
etc.

 It consists of rich constructors, properties and methods that we have tabled


below.

 C# SystemException Signature
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class SystemException : Exception
 C# SystemException Example

 This class can be used to handle exception of subclasses. Here, in the following
program, program throws an IndexOutOfRangeException that is subclass of
SystemException class.

using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
try
{
int[] arr = new int[5];
arr[10] = 25;
}
catch (SystemException e)
{
Console.WriteLine(e);
}
}
}
}

Output: System.IndexOutOfRangeException: Index was outside the bounds of the array

You might also like