0% found this document useful (0 votes)
22 views

NET Framework(unit I,unit II)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

NET Framework(unit I,unit II)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

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.

The .NET Framework is composed of four main components:

 Common Language Runtime (CLR)


 Framework Class Library (FCL),
 Core Languages (WinForms, ASP.NET, and ADO.NET), and
 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:
The main components of CLR are:
 Common type system
 Common language speciation
 Garbage Collector
 Just in Time Compiler
 Metadata and Assemblies

1. 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.
It provides two categories of Types.
Value Type: A value type stores the data in memory allocated on the stack or inline in a
structure. This category of Type holds the data directory. If one variable's value is copied to
another, both the variables store data independently. It can be of inbuilt-in types, user-
defined, or enumerations types. Built-in types are primitive data types like numeric,
Boolean, char, and date. Users in the source code create user-defined types. An
enumeration refers to a set of enumerated values represented by labels but stored as a
numeric type.
Reference Type: A Reference type stores a reference to the value of a memory address and
is allocated on the heap. Heap memory is used for dynamic memory allocation. Reference
Type does not hold actual data directly but holds the address of data. Whenever a reference
type object is made, it copies the address and not actual data. Therefore two variables will
refer to the same data. If data of one Reference Type object is changed, the same is
reflected for the other object. Reference types can be self-describing types, pointer types,
or interference types. The self-describing types may be string, array, and class types that
store metadata about themselves.
2. 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.

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.

4. 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.
5. 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.
6. 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
Following are the functions of the CLR.

It converts the program into native code.


Handles Exceptions
Provides type-safety
Memory management
Provides security
Improved performance
Language independent
Platform independent
Garbage collection
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.

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

static void Main(string[] args)

System.Console.WriteLine("Hello World!");

Output:

Hello World!

C# Example: Using System

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

static void Main(string[] args)

Console.WriteLine("Hello World!");

Output:

Hello World!

C# Example: Using namespace

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 class Program

{
public static void Main(string[] args)

Console.WriteLine("Hello World!");

Output:

Hello World!

C# Data Types

There are 3 types of data types in C# language.

Types Data Types

Value Data Type short, int, char, float, double etc

Reference Data Type String, Class, Object and Interface

Pointer Data Type Pointers

Value Data Type

The value data types are integer-based and floating-point based. C# language supports both signed
and unsigned literals.

There are 2 types of value data type in C# language.

1) Predefined Data Types - such as Integer, Boolean, Float, etc.


2) User defined Data Types - such as Structure, Enumerations, etc.

Reference Data Type

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.

There are 2 types of reference data type in C# language.

1) Predefined Types - such as Objects, String.

2) User defined Types - such as Classes, Interface.

Pointer Data Type

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 :

int num = 23; // 23 will assigned to num

Object Obj = num; // Boxing


// C# implementation to demonstrate

// the Boxing

using System;

class GFG {

// Main Method

static public void Main()

// assigned int value

// 2020 to num

int num = 2020;

// boxing

object obj = num;

// value of num to be change

num = 100;

System.Console.WriteLine

("Value - type value of num is : {0}", num);

System.Console.WriteLine

("Object - type value of obj is : {0}", obj);

Output:

Value - type value of num is : 100

Object - type value of obj is : 2020


Unboxing in C#

The process of converting a Reference Type variable into a Value Type variable is known as
Unboxing.

It is an explicit conversion process.

Example :

int num = 23; // value type is int and assigned value 23

Object Obj = num; // Boxing

int i = (int)Obj; // Unboxing

// C# implementation to demonstrate

// the Unboxing

using System;

class GFG {

// Main Method

static public void Main()

// assigned int value

// 23 to num

int num = 23;

// boxing

object obj = num;

// unboxing

int i = (int)obj;

// Display result

Console.WriteLine("Value of ob object is : " + obj);


Console.WriteLine("Value of i is : " + i);

}}

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:

// C# program to demonstrate the working of Binary Arithmetic Operators

using System;

namespace Arithmetic

class GFG

// Main Function

static void Main(string[] args)

int result;

int x = 10, y = 5;

// Addition

result = (x + y);

Console.WriteLine("Addition Operator: " + result);

// Subtraction

result = (x - y);

Console.WriteLine("Subtraction Operator: " + result);

// Multiplication

result = (x * y);

Console.WriteLine("Multiplication Operator: "+ result);

// Division
result = (x / y);

Console.WriteLine("Division Operator: " + result);

// Modulo

result = (x % y);

Console.WriteLine("Modulo Operator: " + result);

}}}

Relational Operators

// C# program to demonstrate the working of Relational Operators

using System;

namespace Relational {

class GFG {

// Main Function

static void Main(string[] args)

bool result;

int x = 5, y = 10;

// Equal to Operator

result = (x == y);

Console.WriteLine("Equal to Operator: " + result);

// Greater than Operator

result = (x > y);

Console.WriteLine("Greater than Operator: " + result);

// Less than Operator

result = (x < y);

Console.WriteLine("Less than Operator: " + result);

// Greater than Equal to Operator

result = (x >= y);

Console.WriteLine("Greater than or Equal to: "+ result);


// Less than Equal to Operator

result = (x <= y);

Console.WriteLine("Lesser than or Equal to: "+ result);

// Not Equal To Operator

result = (x != y);

Console.WriteLine("Not Equal to Operator: " + result);

}}}

Logical Operators:

// C# program to demonstrate the working of Logical Operators

using System;

namespace Logical {

class GFG {

// Main Function

static void Main(string[] args)

bool a = true,b = false, result;

// AND operator

result = a && b;

Console.WriteLine("AND Operator: " + result);

// OR operator

result = a || b;

Console.WriteLine("OR Operator: " + result);

// NOT operator

result = !a;

Console.WriteLine("NOT Operator: " + result);

}}}

C# if-else

using System;
public class IfExample

public static void Main(string[] args)

int num = 11;

if (num % 2 == 0)

Console.WriteLine("It is even number");

else

Console.WriteLine("It is odd number");

} } }

C# switch

using System;

public class SwitchExample

public static void Main(string[] args)

Console.WriteLine("Enter a number:");

int num = Convert.ToInt32(Console.ReadLine());

switch (num)

case 10: Console.WriteLine("It is 10"); break;

case 20: Console.WriteLine("It is 20"); break;

case 30: Console.WriteLine("It is 30"); break;

default: Console.WriteLine("Not 10, 20 or 30"); break;

}
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

There are 3 types of arrays in C# programming:

 Single Dimensional Array


 Multidimensional Array
 Jagged Array

using System;

public class ArrayExample

public static void Main(string[] args)

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

arr[0] = 10;//initializing array

arr[2] = 20;

arr[4] = 30;

//traversing array

for (int i = 0; i < arr.Length; i++)

Console.WriteLine(arr[i]);

} } }

C# Array Example: Declaration and Initialization at same time

There are 3 ways to initialize array at the time of declaration.

int[] arr = new int[5]{ 10, 20, 30, 40, 50 };

We can omit the size of array.

int[] arr = new int[]{ 10, 20, 30, 40, 50 };

We can omit the new operator also.

int[] arr = { 10, 20, 30, 40, 50 };

C# Array Example: Traversal using for-each loop


We can also traverse the array elements using for-each loop. It returns array element one by one.

using System;

public class ArrayExample

public static void Main(string[] args)

int[] arr = { 10, 20, 30, 40, 50 };//creating and initializing array

//traversing array

foreach (int i in arr)

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:

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

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

Example:

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

Let's see a simple example of multidimensional array which initializes array at the time of
declaration.

using System;

public class MultiArrayExample

public static void Main(string[] args)

int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };//declaration and initialization

//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:

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.

Declaration of Jagged array

Let's see an example to declare jagged array that has two elements.

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

Initialization of Jagged array

Let's see an example to initialize jagged array. The size of elements can be different.

arr[0] = new int[4];

arr[1] = new int[6];

Initialization and filling elements in Jagged array

Let's see an example to initialize and fill elements in jagged array

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

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:

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

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

Let's see a simple example of jagged array in C# which declares, initializes and traverse jagged arrays.

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();

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.

public class JaggedArrayTest

public static void Main()

int[][] arr = new int[3][]{

new int[] { 11, 21, 56, 78 },

new int[] { 2, 5, 6, 7, 98, 5 },

new int[] { 2, 5 }

};

// 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();

}
}

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 {

public class Hello

public void sayHello() { Console.WriteLine("Hello First Namespace"); }

namespace Second

public class Hello

public void sayHello() { Console.WriteLine("Hello Second Namespace"); }

public class TestNamespace

{
public static void Main()

First.Hello h1 = new First.Hello();

Second.Hello h2 = new Second.Hello();

h1.sayHello();

h2.sayHello();

Output:

Hello First Namespace

Hello Second Namespace

C# namespace example: by using keyword

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 {

public class Hello

public void sayHello() { Console.WriteLine("Hello Namespace"); }

namespace Second

public class Welcome

public void sayWelcome() { Console.WriteLine("Welcome Namespace"); }

}
public class TestNamespace

public static void Main()

Hello h1 = new Hello();

Welcome w1 = new Welcome();

h1.sayHello();

w1.sayWelcome();

Output:

Hello Namespace

Welcome Namespace

Inheritance (Derived and Base Class)

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

Base Class (parent) - the class being inherited from

To inherit from a class, use the : symbol.

class Shape {

public void setWidth(int w) {

width = w;

public void setHeight(int h) {

height = h;

protected int width;

protected int height;

// Derived class

class Rectangle: Shape {


public int getArea() {

return (width * height);

class RectangleTester {

static void Main(string[] args) {

Rectangle Rect = new Rectangle();

Rect.setWidth(5);

Rect.setHeight(7);

// Print the area of the object.

Console.WriteLine("Total area: {0}", Rect.getArea());

Console.ReadKey();

Abstract Classes and Methods

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

The abstract keyword is used for classes and methods:

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

An abstract class can have both abstract and regular methods:

namespace ConsoleApp4

abstract class Language

// non-abstract method

public void display()


{

Console.WriteLine("Non abstract method");

// inheriting from abstract class

class Program : Language

static void Main(string[] args)

// object of Program class

Program obj = new Program();

// access method of an abstract class

obj.display();

Console.ReadLine();

Interfaces

Another way to achieve abstraction in C#, is with interfaces.

An interface is a completely "abstract class", which can only contain abstract methods and
properties (with empty bodies):

namespace InterfaceApplication {

public interface ITransactions {

// interface members

void showTransaction();

double getAmount();

public class Transaction : ITransactions {

private string tCode;

private string date;

private double amount;


public Transaction() {

tCode = " ";

date = " ";

amount = 0.0;

public Transaction(string c, string d, double a) {

tCode = c;

date = d;

amount = a;

public double getAmount() {

return amount;

public void showTransaction() {

Console.WriteLine("Transaction: {0}", tCode);

Console.WriteLine("Date: {0}", date);

Console.WriteLine("Amount: {0}", getAmount());

class Tester {

static void Main(string[] args) {

Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);

Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);

t1.showTransaction();

t2.showTransaction();

Console.ReadKey();

Pass by value and pass by reference:


When a function is called, the arguments in a function can be passed by value or passed by
reference.

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:

Passes an argument by value.

Callee does not have any access to the underlying element in the calling code.

A copy of the data is sent to the callee.

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:

Passes an argument by reference.

Callee gives a direct reference to the programming element in the calling code.

The memory address of the stored data is passed.

Changes to the value have an effect on the original data.

using System;

namespace ConsoleApp2

class Program

static void Main(string[] args)

int value;

pass(out value);
Console.WriteLine(value);

Console.ReadLine();

public static void pass(out int a)

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

sealed class SealedClass {

// Calling Function

public int Add(int a, int b)

return a + b;

}}

class Program {

// Main Method

static void Main(string[] args)

// Creating an object of Sealed Class

SealedClass slc = new SealedClass();

// Performing Addition operation

int total = slc.Add(6, 4);

Console.WriteLine("Total = " + total.ToString());


}

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;

public class abc

int amount;

public int abc1

set

if(value<100)

Console.WriteLine("no");

return;

amount=value;

get

return amount;

public class HelloWorld

public static void Main(string[] args)

abc ab=new abc();

ab.abc1=90;

Console.WriteLine ("Try programiz.pro");

}
}

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.

// C# program to illustrate the Indexer


using System;
// class declaration
class IndexerCreation
{
private string[] val = new string[3];
public string this[int index]
{
get
{
return val[index];
}
set
{
val[index] = value;
}
}}
class main {
// Main Method
public static void Main() {
IndexerCreation ic = new IndexerCreation();
ic[0] = "C";
ic[1] = "CPP";
ic[2] = "CSHARP";
Console.Write("Printing values stored in objects used as arrays\n");
Console.WriteLine("First value = {0}", ic[0]);
Console.WriteLine("Second value = {0}", ic[1]);
Console.WriteLine("Third value = {0}", ic[2]);
}}
Polymorphism means “Many Forms”. In polymorphism, poly means “Many,” and morph means
“Forms.” polymorphism is one of the main pillars in Object Oriented Programming. It allows you to
create multiple methods with the same name but different signatures in the same class. The same
name methods can also be in derived classes.

There are two types of polymorphism,

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

public int Add(int num1, int num2)

return (num1 + num2);

public int Add(int num1, int num2, int num3)

return (num1 + num2 + num3);


}

public float Add(float num1, float num2)

return (num1 + num2);

public string Add(string value1, string value2)

return (value1 + " " + value2);

static void Main(string[] args)

Program objProgram = new Program();

Console.WriteLine("Add with two int parameter :" + objProgram.Add(3, 2));

Console.WriteLine("Add with three int parameter :" + objProgram.Add(3, 2, 8));

Console.WriteLine("Add with two float parameter :" + objProgram.Add(3 f, 22 f));

Console.WriteLine("Add with two string parameter :" + objProgram.Add("hello", "world"));

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)

return (num1 + num2);

class ChildClass: BaseClass

public override int Add(int num1, int num2)

if (num1 <= 0 || num2 <= 0)

Console.WriteLine("Values could not be less than zero or equals to zero");

Console.WriteLine("Enter First value : ");

num1 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter First value : ");

num2 = Convert.ToInt32(Console.ReadLine());

return (num1 + num2);

class Program

static void Main(string[] args)

BaseClass baseClassObj;

baseClassObj = new BaseClass();

Console.WriteLine("Base class method Add :" + baseClassObj.Add(-3, 8));

baseClassObj = new ChildClass();

Console.WriteLine("Child class method Add :" + baseClassObj.Add(-2, 2));

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:

int var = 10;


fixed (int* ptr = &var)
{
// Perform operations with ptr
}

Pointers can point to arrays’ elements:

int[] numbers = {10, 20, 30};


fixed (int* ptr = numbers)
{
*ptr = *ptr + 10; // First element becomes 20

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);
}
}

}
}
}

What is a Delegate in C#?

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.

Why do we need delegates in C#?

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

public delegate int DelegateMethod(int x, int y);


Any method that matches the delegate's signature, which consists of the return type and
parameters, can be assigned to the delegate.

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.

What are the types of delegates in C#?

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.

What is a Singlecast delegate in C#?

A sample code demonstrates how to create and use a singlecast delegate.

using System;

namespace ConsoleApplication5
{
class Program
{
public delegate void delmethod();

public class P
{
public static void display()
{
Console.WriteLine("Hello!");
}

public static void show()


{
Console.WriteLine("Hi!");
}

public void print()


{
Console.WriteLine("Print");
}
}

static void Main(string[] args)


{
// here we have assigned static method show() of
class P to delegate delmethod()
delmethod del1 = P.show;
// here we have assigned static method display() of
class P to delegate delmethod() using new operator
// you can use both ways to assign the delegate
delmethod del2 = new delmethod(P.display);
P obj = new P();

// here first we have create instance of class P and


assigned the method print() to the delegate i.e. delegate with
class
delmethod del3 = obj.print;

del1();
del2();
del3();
Console.ReadLine();
}
}
}

What is a Multicast delegate in C#?

A sample code demonstrates how to create and use a multicast delegate.

using System;

namespace delegate_Example4
{
class Program
{
public delegate void delmethod(int x, int y);

public class TestMultipleDelegate


{
public void plus_Method1(int x, int y)
{
Console.Write("You are in plus_Method");
Console.WriteLine(x + y);
}

public void subtract_Method2(int x, int y)


{
Console.Write("You are in subtract_Method");
Console.WriteLine(x - y);
}
}

static void Main(string[] args)


{
TestMultipleDelegate obj = new
TestMultipleDelegate();
delmethod del = new delmethod(obj.plus_Method1);

// Here we have multicast


del += new delmethod(obj.subtract_Method2);
// plus_Method1 and subtract_Method2 are called
del(50, 10);
Console.WriteLine();
// Here again we have multicast
del -= new delmethod(obj.plus_Method1);
// Only subtract_Method2 is called
del(20, 10);
Console.ReadLine();
}
}
}

How are Delegates Related to Events in C#?

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.

Program for creating a custom Singlecast delegate and event.


using System;

namespace delegate_custom
{
class Program
{
public delegate void MyDelegate(int a);

public class XX
{
public event MyDelegate MyEvent;

public void RaiseEvent()


{
MyEvent(20);
Console.WriteLine("Event Raised");
}
public void Display(int x)
{
Console.WriteLine("Display Method {0}", x);
}
}

static void Main(string[] args)


{
XX obj = new XX();
obj.MyEvent += new MyDelegate(obj.Display);

obj.RaiseEvent();
Console.ReadLine();
}
}
}

Program for creating custom multiplecast delegates and events.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace delegate_custom_multicast
{
class Program
{
public delegate void MyDelegate(int a, int b);

public class XX
{
public event MyDelegate MyEvent;

public void RaiseEvent(int a, int b)


{
MyEvent(a, b);
Console.WriteLine("Event Raised");
}

public void Add(int x, int y)


{
Console.WriteLine("Add Method {0}", x + y);
}

public void Subtract(int x, int y)


{
Console.WriteLine("Subtract Method {0}", x - y);
}
}

static void Main(string[] args)


{
XX obj = new XX();
obj.MyEvent += new MyDelegate(obj.Add);
obj.MyEvent += new MyDelegate(obj.Subtract);
obj.RaiseEvent(20, 10);
Console.ReadLine();
}
}
}

What Are Collections in C#?

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.

What Are the Types of Collections in C#?

Collections are majorly classified into two 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.

Generic collections are often classified into five 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

static void Main(string[] args){


List<int> GenericList = new List<int>();

GenericList.Add(30);

GenericList.Add(60);

GenericList.Add(90);

GenericList.Add(120);

foreach (int x in GenericList)

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

static void Main(string[] args)

Dictionary<int, string> GenericDictionary = new Dictionary<int, string>();

GenericDictionary.Add(1, "Soda");

GenericDictionary.Add(2, "Burger");

GenericDictionary.Add(3, "Fries");

GenericDictionary.Add(4, "Onion Rings");


foreach (KeyValuePair<int, string> kvp in GenericDictionary)

Console.WriteLine(kvp.Key + " " + kvp.Value);

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

static void Main(string[] args)

Stack<string> steak = new Stack<string>();

steak.Push("Rare");

steak.Push("Medium Rare");

steak.Push("Medium");

steak.Push("Well done");

foreach (string s in steak)

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

static void Main(string[] args)

Queue<string> GenericQueue = new Queue<string>();

GenericQueue.Enqueue("Mark");

GenericQueue.Enqueue("Bill");

GenericQueue.Enqueue("Xavier");

GenericQueue.Enqueue("Michael");

foreach (string s in GenericQueue)

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

static void Main(string[] args)

ArrayList NonGenericArrayList = new ArrayList();

string str = "Like, Share, Subscribe";

int x = 11;

DateTime d = DateTime.Parse("3-dec-1998");

NonGenericArrayList.Add(str);

NonGenericArrayList.Add(x);

NonGenericArrayList.Add(d);

foreach (object o in NonGenericArrayList)

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)

Stack steak = new Stack();

steak.Push("Rare");

steak.Push("Medium Rare");

steak.Push("Medium");

steak.Push("Well done");

foreach (object o in steak)

Console.WriteLine(o);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy