NET Framework
NET Framework
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.
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:
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
ADO.NET
WF (Workflow Foundation)
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
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 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 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.
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.
Garbage Collection:
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:
Assemblies:
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 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.
Window applications
Web applications
Distributed applications
Web service applications
Database applications etc.
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.
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.
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.
9) Rich Library
C# provides a lot of inbuilt functions that makes the development 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.
A data type specifies the type of data that a variable can store such as integer,
floating, character etc.
C# Keywords
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.
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.
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
Return type: It is used to specify the data type of function return value.
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>)
{
}
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);
}
2. C# Call By Reference
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
}
Output:
3. C# Out Parameter
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
}
Output:
C# Arrays
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.
to reuse the array logic, we can create function. To pass array to function in C#,
we need to provide only array name.
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
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.
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 };// 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
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);
}
}
}
}
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 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
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)
Default constructor
Parameterized constructor
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:
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
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.
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
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();
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 constants has default values which starts from 0 and incremented to one
by one. But we can change the default value.
C# Properties
The Properties have accessors that are used to set, get or compute their 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);
}
}
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.
Output:
Salary: 40000
Bonus: 10000
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
Having two or more methods with same name but different in parameters, is
known as method overloading in C#.
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.
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();
}
}
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.
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:
You can't use static and virtual modifiers in abstract method declaration.
C# Abstract class
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.
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 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 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 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.
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
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# try/catch
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
Output:
C# User-Defined Exceptions
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
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
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);
}
}
}
}