NET Framework(unit I,unit II)
NET Framework(unit I,unit II)
.NET Framework
Following is the .NET framework Stack that shows the modules and
components of the Framework.
3. 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.
1. Managed code:
Any language that is written in the .NET framework is managed code. Managed code use
CLR, which looks after your applications by managing memory, handling security, allowing
cross-language debugging, etc. The process of managed code is shown in the figure:
2. Unmanaged code:
The code developed outside the .NET framework is known as unmanaged code. Applications
that do not run under the control of the CLR are said to be unmanaged. Certain languages
such as C++ can be used to write such applications, such as low-level access functions of the
operating system. Background compatibility with VB, ASP, and COM are examples of
unmanaged code. This code is executed with the help of wrapper classes. The unmanaged
code process is shown below:
Suppose you have written a C# program and save it in a file which is known as the
Source Code.
Language specific compiler compiles the source code into the MSIL(Microsoft
Intermediate Language) which is also known as the CIL(Common Intermediate
Language) or IL(Intermediate Language) along with its metadata. Metadata includes
all the types, actual implementation of each function of the program. MSIL is
machine-independent code.
Now CLR comes into existence. CLR provides the services and runtime environment
to the MSIL code. Internally CLR includes the JIT(Just-In-Time) compiler which
converts the MSIL code to machine code which further executed by CPU. CLR also
uses the .NET Framework class libraries. Metadata provides information about the
programming language, environment, version, and class libraries to the CLR by which
CLR handles the MSIL code. As CLR is common so it allows an instance of a class that
written in a different language to call a method of the class which written in another
language.
Below diagram illustrate how CLR is associated with the operating
system/hardware along with the class libraries. Here, the runtime is actually CLR.
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.
Integrated Development Environment (IDE):
An integrated development environment (IDE) is a software suite that consolidates basic
tools required to write and test software.
Developers use numerous tools throughout software code creation, building and testing.
Development tools often include text editors, code libraries, compilers and test platforms.
Common features of integrated development environments
An IDE typically contains a code editor, a compiler or interpreter, and a debugger, accessed
through a single graphical user interface (GUI). The user writes and edits source code in the
code editor. The compiler translates the source code into a readable language that is
executable for a computer. And the debugger tests the software to solve any issues or bugs.
An IDE can also contain features such as programmable editors, object and data modeling,
unit testing, a source code library and build automation tools.
Types of IDEs and available tools
Types of IDEs range from web-based and cloud-based to mobile, language-specific or multi-
language.
Web-based IDEs suit web-based application development in HTML, JavaScript or similar
programming languages. Microsoft's Visual Studio Code is an example of a web-based IDE
with features such as a code editor, syntax highlighting, code completion and debugging.
Increasingly, IDEs are offered on a platform as a service (PaaS) delivery model. The benefits
of these cloud-based IDEs include accessibility to software development tools from
anywhere in the world, from any compatible device; minimal to nonexistent download and
installation requirements; and ease of collaboration among geographically dispersed
developers. Cloud9 is an IDE from AWS that supports up to 40 languages including C, C++,
Python, Ruby and JavaScript. Cloud9 gives users code completion, an image editor and a
debugger, as well as other features such as support for deployment to Microsoft Azure and
Heroku (which is a cloud-based PaaS IDE).
An IDE for mobile development normally works with code that runs on iOS or Android
devices. Xamarin is an example of a cross-platform mobile IDE, which means it can create
code for multiple mobile platform types. For example, a developer can write a feature in C
and Xamarin translates it into Swift for iOS and Java for Android. Additionally, Xamarin offers
UI tests and it can distribute beta tests to users.
IDEs such as C-Free -- which supports a code editor, debugger and an environment to run C
and C++ code -- are language specific. Other IDEs support multiple languages, such as
previously mentioned Cloud9 and Visual Studio Code. More popular IDE tools include
Netbeans, Eclipse and IntelliJ IDE.
C#
C# is pronounced as "C-Sharp". It is an object-oriented programming language provided by Microsoft
that runs on .Net Framework.
C# Simple Example
class Program
System.Console.WriteLine("Hello World!");
Output:
Hello World!
If we write using System before the class, it means we don't need to specify System namespace for
accessing any class of this namespace.
using System;
class Program
Console.WriteLine("Hello World!");
Output:
Hello World!
We can create classes inside the namespace. It is used to group related classes. It is used to
categorize classes so that it can be easy to maintain.
using System;
namespace ConsoleApplication1
{
public static void Main(string[] args)
Console.WriteLine("Hello World!");
Output:
Hello World!
C# Data Types
The value data types are integer-based and floating-point based. C# language supports both signed
and unsigned literals.
The reference data types do not contain the actual data stored in a variable, but they contain a
reference to the variables.
If the data is changed by one of the variables, the other variable automatically reflects this change in
value.
The pointer in C# language is a variable, it is also known as locator or indicator that points to an
address of a value.
Boxing in C#
The process of converting a Value Type variable (char, int etc.) to a Reference Type variable (object)
is called Boxing. Boxing is an implicit conversion process in which object type (super type) is used.
Value Type variables are always stored in Stack memory, while Reference Type variables are stored
in Heap memory.
Example :
// the Boxing
using System;
class GFG {
// Main Method
// 2020 to num
// boxing
num = 100;
System.Console.WriteLine
System.Console.WriteLine
Output:
The process of converting a Reference Type variable into a Value Type variable is known as
Unboxing.
Example :
// C# implementation to demonstrate
// the Unboxing
using System;
class GFG {
// Main Method
// 23 to num
// boxing
// unboxing
int i = (int)obj;
// Display result
}}
Output:
Value of ob object is : 23
Value of i is : 23
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:
using System;
namespace Arithmetic
class GFG
// Main Function
int result;
int x = 10, y = 5;
// Addition
result = (x + y);
// Subtraction
result = (x - y);
// Multiplication
result = (x * y);
// Division
result = (x / y);
// Modulo
result = (x % y);
}}}
Relational Operators
using System;
namespace Relational {
class GFG {
// Main Function
bool result;
int x = 5, y = 10;
// Equal to Operator
result = (x == y);
result = (x != y);
}}}
Logical Operators:
using System;
namespace Logical {
class GFG {
// Main Function
// AND operator
result = a && b;
// OR operator
result = a || b;
// NOT operator
result = !a;
}}}
C# if-else
using System;
public class IfExample
if (num % 2 == 0)
else
} } }
C# switch
using System;
Console.WriteLine("Enter a number:");
switch (num)
}
C# Arrays
Like other programming languages, array in C# is a group of similar types of elements that have
contiguous memory location. In C#, array is an object of base type System. Array. In C#, array index
starts from 0. We can store only fixed set of elements in C# array.
C# Array Types
using System;
arr[2] = 20;
arr[4] = 30;
//traversing array
Console.WriteLine(arr[i]);
} } }
using System;
int[] arr = { 10, 20, 30, 40, 50 };//creating and initializing array
//traversing array
Console.WriteLine(i);
C# Multidimensional Arrays
The multidimensional array is also known as rectangular arrays in C#. It can be two dimensional or
three dimensional. The data is stored in tabular form (row * column) which is also known as matrix.
To create multidimensional array, we need to use comma inside the square brackets. For example:
Example:
using System;
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]+" ");
Let's see a simple example of multidimensional array which initializes array at the time of
declaration.
using System;
//traversal
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
Console.Write(arr[i,j]+" ");
Output:
123
456
789
C# Jagged Arrays
In C#, jagged array is also known as "array of arrays" because its elements are arrays. The element
size of jagged array can be different.
Let's see an example to declare jagged array that has two elements.
Let's see an example to initialize jagged array. The size of elements can be different.
Here, size of elements in jagged array is optional. So, you can write above code as given below:
Let's see a simple example of jagged array in C# which declares, initializes and traverse jagged arrays.
arr[0] = new int[] { 11, 21, 56, 78 };// Initialize the array
System.Console.Write(arr[i][j]+" ");
System.Console.WriteLine();
Output:
11 21 56 78
42 61 37 41 59 63
Let's see a simple example of jagged array which initializes the jagged arrays upon declaration.
new int[] { 2, 5 }
};
System.Console.Write(arr[i][j]+" ");
System.Console.WriteLine();
}
}
Output:
11 21 56 78
2 5 6 7 98 5
25
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.
C# namespace example
Let's see another example of namespace in C# where one namespace program accesses another
namespace program.
using System;
namespace First {
namespace Second
{
public static void Main()
h1.sayHello();
h2.sayHello();
Output:
Let's see another example of namespace where we are using "using" keyword so that we don't have
to use complete name for accessing a namespace program.
using System;
using First;
using Second;
namespace First {
namespace Second
}
public class TestNamespace
h1.sayHello();
w1.sayWelcome();
Output:
Hello Namespace
Welcome Namespace
In C#, it is possible to inherit fields and methods from one class to another. We group the
"inheritance concept" into two categories:
Derived Class (child) - the class that inherits from another class
class Shape {
width = w;
height = h;
// Derived class
class RectangleTester {
Rect.setWidth(5);
Rect.setHeight(7);
Console.ReadKey();
Data abstraction is the process of hiding certain details and showing only essential information to
the user.
Abstraction can be achieved with either abstract classes or interfaces (which you will learn more
about in the next chapter).
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is
provided by the derived class (inherited from).
namespace ConsoleApp4
// non-abstract method
obj.display();
Console.ReadLine();
Interfaces
An interface is a completely "abstract class", which can only contain abstract methods and
properties (with empty bodies):
namespace InterfaceApplication {
// interface members
void showTransaction();
double getAmount();
amount = 0.0;
tCode = c;
date = d;
amount = a;
return amount;
class Tester {
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();
Callee is a function called by another and the caller is a function that calls another function (the
callee). The values that are passed in the function call are called the actual parameters.
The values received by the function (when it is called ) are called the formal parameters.
Pass by value
Pass by value means that a copy of the actual parameter’s value is made in memory, i.e. the caller
and callee have two independent variables with the same value. If the callee modifies the parameter
value, the effect is not visible to the caller.
Overview:
Callee does not have any access to the underlying element in the calling code.
Changes made to the passed variable do not affect the actual value.
Pass by Reference
Pass by reference (also called pass by address) means to pass the reference of an argument in the
calling function to the corresponding formal parameter of the called function so that a copy of the
address of the actual parameter is made in memory, i.e. the caller and the callee use the same
variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the
caller’s variable.
Overview:
Callee gives a direct reference to the programming element in the calling code.
using System;
namespace ConsoleApp2
class Program
int value;
pass(out value);
Console.WriteLine(value);
Console.ReadLine();
a = 5;
a = a + 10;
Console.WriteLine(a);
Sealed class
Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using
the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be
extended. No class can be derived from a sealed class.
using System;
// Sealed class
// Calling Function
return a + b;
}}
class Program {
// Main Method
Property in C# is a class member that exposes the class' private fields. Internally,
C# properties are special methods called accessors. A C# property has two
accessors, a get property accessor or a getter and a set property accessor or a
setter. A get accessor returns a property value, and a set accessor assigns a new
value. The value keyword represents the value of a property.
using System;
int amount;
set
if(value<100)
Console.WriteLine("no");
return;
amount=value;
get
return amount;
ab.abc1=90;
}
}
C# | Indexers
An indexer allows an instance of a class or struct to be indexed as an array. If the user will
define an indexer for a class, then the class will behave like a virtual array. Array access
operator i.e ([ ]) is used to access the instance of the class which uses an indexer. A user can
retrieve or set the indexed value without pointing an instance or a type member. Indexers
are almost similar to the Properties. The main difference between Indexers and Properties is
that the accessors of the Indexers will take parameters.
Method Overloading
Method Overloading is a type of polymorphism. It has several names like “Compile Time
Polymorphism” or “Static Polymorphism,” and sometimes it is called “Early Binding”.
Method Overloading means creating multiple methods in a class with the same names but different
signatures (Parameters). It permits a class, struct, or interface to declare multiple methods with the
same name with unique signatures.
The compiler automatically calls the required method to check the number of parameters and their
type passed into that method.
using System;
namespace DemoCsharp
class Program
Console.ReadLine();
Method Overriding
Method Overriding is a type of polymorphism. It has several names like “Run Time Polymorphism” or
“Dynamic Polymorphism,” and sometimes it is called “Late Binding”.
Method Overriding means having two methods with the same name and same signatures
[parameters]; one should be in the base class, and another method should be in a derived class
[child class]. You can override the functionality of a base class method to create the same name
method with the same signature in a derived class. You can achieve method overriding using
inheritance. Virtual and Override keywords are used to achieve method overriding.
using System;
namespace DemoCsharp
class BaseClass
{
public virtual int Add(int num1, int num2)
num1 = Convert.ToInt32(Console.ReadLine());
num2 = Convert.ToInt32(Console.ReadLine());
class Program
BaseClass baseClassObj;
Console.ReadLine();
}
}
Pointers:
C# supports pointers in a limited extent. A C# pointer is nothing but a variable that holds the
memory address of another type. But in C# pointer can only be declared to hold the memory
address of value types and arrays.
int x = 100;
int *ptr = & x;.
Console.WriteLine((int)ptr) // Displays the memory address
Console.WriteLine(*ptr) // Displays the value at the memory
address.
Unsafe Codes
The C# statements can be executed either as in a safe or in an unsafe context. The statements
marked as unsafe by using the keyword unsafe runs outside the control of Garbage Collector.
Remember that in C# any code involving pointers requires an unsafe context.
We can use the unsafe keyword in two different ways. It can be used as a modifier to a method,
property, and constructor etc.
using System;
class MyClass
{
public unsafe void Method()
{
int x = 10;
int y = 20;
int* ptr1 = &x;
int* ptr2 = &y;
Console.WriteLine((int)ptr1);
Console.WriteLine((int)ptr2);
Console.WriteLine(*ptr1);
Console.WriteLine(*ptr2);
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.Method();
}
}
The keyword unsafe can also be used to mark a group of statements as unsafe as shown below.
using System;
class MyClass
{
public void Method()
{
unsafe
{
int x = 10;
int y = 20;
int* ptr1 = &x;
int* ptr2 = &y;
Console.WriteLine((int)ptr1);
Console.WriteLine((int)ptr2);
Console.WriteLine(*ptr1);
Console.WriteLine(*ptr2);
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.Method();
}
}
C# - Unsafe Code
C# allows using pointer variables in a function of code block when it is marked by the unsafe
modifier. The unsafe code or the unmanaged code is a code block that uses a pointer
variable.
Unmanaged code is code that executes outside the context of the CLR. The best example of
this is our traditional Win32 DLLs like kernel32.dll and user32.dll.
In unmanaged code, a programmer is responsible for:
Calling the memory allocation function
Making sure that the casting is done right
Making sure that the memory is released when the work is done
Unsafe is a C# programming language keyword to denote a section of code that is not
managed by the Common Language Runtime (CLR) of the .NET Framework, or unmanaged
code. Unsafe is used in the declaration of a type or member or to specify a block code.
When used to specify a method, the context of the entire method is unsafe.
To maintain type safety and security, C# does not support pointer arithmetic, by default.
However, using the unsafe keyword, you can define an unsafe context in which pointers can
be used.
How to write your code in Unsafe mode in C#:
Go to View in Visual Studio
Then go to Solution Explorer
Double click on "Properties"
Select Build. You can see the checkbox for "Allow unsafe code". Tick it.
Once you tick this checkbox, your error under the Main method will be gone and your code
will be automatically compilable without any issue.
The ‘Fixed’ Keyword
The garbage collector in .NET might relocate variables, leading to invalid pointer references.
The fixed keyword pins a variable, preventing the garbage collector from moving it:
class Program
{
static int square(int n)
{
return n * n;
}
static unsafe void square1(int* pn)
{
*pn= *pn * *pn;
}
static unsafe void printA(int* ar, int len)
{
for (int i=0; i<len; i++)
{
//Console.WriteLine("hi");
Console.WriteLine(ar[i]);
Console.ReadKey();
}
}
public static void Main(string[] args)
{
int m;
m = 9;
int[] arr = new int[] { 1, 2, 3 };
unsafe
{
square1(&m);
}
Console.WriteLine(m);
Console.ReadLine();
unsafe
{
fixed (int* ar = arr)
{
printA(ar, arr.Length);
}
}
}
}
}
Delegate is one of the base types in .NET. Delegate is a class used to create and invoke delegates at
runtime.
A delegate in C# is similar to a function pointer in C or C++. It's a new type of object in C#. A delegate
is a very special type of object, as mentioned earlier. The entire object we used to define contained
data, but a delegate contains the details of a method.
C# programmers often need to pass a method as a parameter of other methods when dealing with
events. For this purpose, we create and use delegates in C#. A delegate is a class that encapsulates a
method signature. Although it can be used in any context, it often serves as the basis for the event-
handling model in C# and .NET. One good way of understanding delegates is by thinking of a
delegate as something that gives a name to a method signature.
Example
This makes it possible to programmatically change method calls and plug new code into existing
classes. You can assign your own delegated method if you know the delegate's signature.
There are two types of delegates in C#, singlecast delegates and multiplecast delegates.
Singlecast delegate: Singlecast delegate points to a single method at a time. The delegate is assigned
to a single method at a time. They are derived from System.Delegate class.
Multicast Delegate: When a delegate is wrapped with more than one method, that is known as a
multicast delegate.
using System;
namespace ConsoleApplication5
{
class Program
{
public delegate void delmethod();
public class P
{
public static void display()
{
Console.WriteLine("Hello!");
}
del1();
del2();
del3();
Console.ReadLine();
}
}
}
using System;
namespace delegate_Example4
{
class Program
{
public delegate void delmethod(int x, int y);
Events and delegates work together. An event is a reference to a delegate, i.e., when an event is
raised, a delegate is called. In C# terms, events are a special form of delegates.
Events play an important part in user interfaces and programming notifications. Events and
delegates work hand-in-hand to communicate between codes from one class to another. Events are
used when something happens in one class or part of the code and another part needs a
notification.
A C# event is a class member that is activated whenever the event it was designed for occurs. It
starts with a class that declares an event. Any class, including the same class that the event is
declared in, may register one of its methods for the event. This occurs through a delegate, which
specifies the signature of the registered method for the event. The event keyword is a delegate
modifier. It must always be used in connection with a delegate.
namespace delegate_custom
{
class Program
{
public delegate void MyDelegate(int a);
public class XX
{
public event MyDelegate MyEvent;
obj.RaiseEvent();
Console.ReadLine();
}
}
}
namespace delegate_custom_multicast
{
class Program
{
public delegate void MyDelegate(int a, int b);
public class XX
{
public event MyDelegate MyEvent;
C# collections are made to more effectively organize, store, and modify comparable data. Adding,
deleting, discovering, and inserting data into the collection are all examples of data manipulation.
These classes support stacks, queues, lists, and hash tables. Most collection classes implement the
same interfaces.
There are several applications for collection classes, such as dynamic memory allocation for
elements and index-based access to lists of objects. These classes construct collections of objects of
the Object class, the building blocks of all other C# data types.
Generic Collections
Non-Generic Collections
Generic Collections
A Generic collection provides the type safety without derivation from a basic collection type and the
implementation of type-specific members. The Generic Collection classes are found in the
namespace "System.Collections.Generics." Internally, Generic Collections store elements in arrays of
their respective types.
List:
In Generic List, we have to specify a data type to its contents, and all elements will have the same
datatype.
Code:
using System;
using System.Collections.Generic;
namespace genericList{
class Program
GenericList.Add(30);
GenericList.Add(60);
GenericList.Add(90);
GenericList.Add(120);
Console.WriteLine(x);
Dictionary:
Dictionaries usually store data in key-value pairs, and we have to specify both data types
beforehand.
Code:
using System;
using System.Collections.Generic;
namespace genericDictionary
class Program
GenericDictionary.Add(1, "Soda");
GenericDictionary.Add(2, "Burger");
GenericDictionary.Add(3, "Fries");
Stack:
Values are kept in Stack using LIFO (Last In First Out). It offers the Push() and Pop() & Peek() methods
to add and retrieve values, respectively. In generic Stack, we have to specify the datatypes of its
content beforehand.
Code:
using System;
using System.Collections.Generic;
namespace genericStack
class Program
steak.Push("Rare");
steak.Push("Medium Rare");
steak.Push("Medium");
steak.Push("Well done");
Console.WriteLine(s);
}
}
Queue:
Values are kept in a queue in a FIFO fashion (First In, First Out). The sequence in which the values
were inserted is preserved. It offers the Enqueue() and Dequeue() methods to add and remove
values from the collection. In the generic queue, we have to specify the datatypes of its content
beforehand.
Code:
using System;
using System.Collections.Generic;
namespace genericQueue
class Program
GenericQueue.Enqueue("Mark");
GenericQueue.Enqueue("Bill");
GenericQueue.Enqueue("Xavier");
GenericQueue.Enqueue("Michael");
Console.WriteLine(s);
Non-Generic Collections
Non-generic collections are specialized data storage and retrieval classes that handle stacks, queues,
lists, and hash tables. The "System.Collections" namespace contains the Non-generic Collection
classes. Non-generic collections store elements in object arrays internally, allowing them to hold any
data type.
Non-Generic collections are often classified into five types.
ArrayList:
The array's size might change during use since it is dynamic, which implies it is not static. It offers
functions that are comparable to those in the generic List class.
Code:
using System;
using System.Collections;
namespace nonGenericArrayList
class Program
int x = 11;
DateTime d = DateTime.Parse("3-dec-1998");
NonGenericArrayList.Add(str);
NonGenericArrayList.Add(x);
NonGenericArrayList.Add(d);
Console.WriteLine(o);
}
HashTable:
A hash table data structure is made up of key-value pairs. The hash values of the
keys are compared to find the values. It offers functions that are comparable to those
in the generic dictionary class.
Code:
using System;
using System.Collections;
namespace nonGenericHashTable
{
class Program
{
static void Main(string[] args)
{
Hashtable NonGenericHashTable = new Hashtable();
NonGenericHashTable.Add(1, "Soda");
NonGenericHashTable.Add(2, "Burger");
NonGenericHashTable.Add(3, "Fries");
NonGenericHashTable.Add(4, "Onion Rings");
foreach (DictionaryEntry h in NonGenericHashTable)
{
Console.WriteLine (h.Key + " " + h.Value);
}
}
}
}
Stack:
It's a FIFO (first-in, first-out) list. Hence it works similarly to the Stack class in generic
collections.
Code:
using System;
using System.Collections;
namespace nonGenericStack
class Program
{
static void Main(string[] args)
steak.Push("Rare");
steak.Push("Medium Rare");
steak.Push("Medium");
steak.Push("Well done");
Console.WriteLine(o);