0% found this document useful (0 votes)
120 views23 pages

Unit I NET

The document provides an overview of the ASP.NET Framework, focusing on the Common Language Runtime (CLR) and the Framework Class Library (FCL). It details the key functions of CLR, such as memory management, JIT compilation, and security, as well as the components and benefits of FCL for developing .NET applications. Additionally, it covers C# primitive data types, variable types, and control flow structures like conditional statements and loops.

Uploaded by

bsuresh2002
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)
120 views23 pages

Unit I NET

The document provides an overview of the ASP.NET Framework, focusing on the Common Language Runtime (CLR) and the Framework Class Library (FCL). It details the key functions of CLR, such as memory management, JIT compilation, and security, as well as the components and benefits of FCL for developing .NET applications. Additionally, it covers C# primitive data types, variable types, and control flow structures like conditional statements and loops.

Uploaded by

bsuresh2002
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/ 23

Programming in ASP.

NET UNIT I

Topic : Overview of ASP.NET FRAMEWORK

Common Language Runtime(CLR)

The Common Language Runtime (CLR) is the virtual machine and execution engine of the
Microsoft .NET Framework, managing the execution of .NET applications by providing

1
services like automatic memory management, exception handling, type safety, and security. It
compiles Intermediate Language (IL) code into machine-specific code using a Just-In-Time
(JIT) compiler and ensures interoperability between different .NET programming languages.

Key Functions and Features

 Execution Engine:
The CLR manages the entire lifecycle of a .NET application, from its launch to its
completion.
 Just-In-Time (JIT) Compilation:
When a .NET program is compiled, it is converted into an intermediate language (IL
or MSIL). The CLR's JIT compiler then translates this IL code into native machine code at
runtime, optimizing it for the target platform.
 Memory Management:
The CLR's Garbage Collector automatically manages memory, allocating memory for
objects and reclaiming it when it's no longer in use, preventing memory leaks.
 Exception Handling:
The CLR provides a robust mechanism for handling runtime exceptions, ensuring that
errors are caught and managed gracefully.
 Security:
It enforces various security measures, such as code access security and role-based security,
to protect system resources and prevent unauthorized access.
 Type Safety:
The CLR ensures that programs maintain type safety, which helps prevent common
programming errors and promotes code stability.
 Interoperability:
Through the Common Type System (CTS) and Common Language Specification
(CLS), the CLR enables different .NET languages (like C#, VB.NET, and F#) to interact
and share components seamlessly.
How it Works

1. Compilation: Developers write code in a .NET language (e.g., C#).


2. Intermediate Language (IL): The source code is compiled into an intermediate language,
which is platform-independent.
3. CLR Loading: The CLR loads this IL code.
4. JIT Compilation: The JIT compiler translates the IL code into the native machine code
required by the specific operating system and hardware.

2
5. Execution: The machine code is executed by the computer's CPU.
6. Runtime Services: Throughout execution, the CLR provides essential services such as
memory management and security.

 Performance improvements.

 The ability to easily use components developed in other languages.

 Extensible types provided by a class library.

 Language features such as inheritance, interfaces, and overloading


for object-oriented programming.

 Support for explicit free threading that allows creation of


multithreaded and scalable applications.

 Support for structured exception handling.

 Support for custom attributes.

 Garbage collection.

 Use of delegates instead of function pointers for increased type


safety and security.

FRAMEWORK CLASS LIBRARY: FCL


Definition. The Framework Class Library (FCL) is a comprehensive
collection of reusable classes, interfaces, and value types that provide the
foundation for various functional areas in the . NET framework.1

Framework Class Library (FCL)


The Framework Class Library (FCL) is a collection of reusable classes, interfaces, and
value types that are tightly integrated with the Common Language Runtime (CLR) in the
.NET Framework.

It provides the building blocks for developing .NET applications (desktop, web, mobile,
cloud, etc.) in a language-independent manner.

Key Points about FCL: Part of .NET Framework

o Works with CLR, providing runtime services like memory management,


exception handling, security, and interoperability.
2. Rich collection of namespaces

3
o Includes thousands of classes grouped into namespaces like System,
System.IO, System.Data, System.Net, etc.
3. Object-Oriented
o Provides consistent object-oriented APIs that can be reused across
different .NET languages (C#, VB.NET, F#, etc.).
4. Base Class Library (BCL)
o The core subset of FCL, containing fundamental classes for basic data types,
collections, file I/O, threading, etc.

Components of FCL: System Namespace → Base classes (strings, arrays, exceptions,


math, dates, etc.)

 System.IO → File handling and streams


 System.Collections / System.Collections.Generic → Data structures like lists,
dictionaries, queues
 System.Data → Database connectivity (ADO.NET)
 System.Net → Networking, HTTP, FTP, sockets
 System.Threading → Multithreading and parallelism
 System.Windows.Forms / WPF → Windows desktop UI development
 ASP.NET Libraries → Web applications and services
 XML & JSON APIs → Data exchange and serialization

Benefits of FCL

Code Reusability – prebuilt functions/classes reduce coding effort


Language Interoperability – usable across any .NET-supported language
Rapid Development – ready-made APIs accelerate development
Consistency – standard structure across different types of applications
Scalability – supports small apps to enterprise-level solutions

4
C#, primitive data types are fundamental, built-in types that represent basic
values and are directly supported by the language.

The main categories of primitive data types in C# are:

 Integral Types: Used for whole numbers. These include:


o sbyte: 8-bit signed integer.
o byte: 8-bit unsigned integer.
o short: 16-bit signed integer.
o ushort: 16-bit unsigned integer.
o int: 32-bit signed integer.
o uint: 32-bit unsigned integer.
o long: 64-bit signed integer.
o ulong: 64-bit unsigned integer.
 Floating-Point Types: Used for numbers with decimal points. These include:
o float: Single-precision (32-bit) floating-point number.
o double: Double-precision (64-bit) floating-point number.
 Decimal Type: Used for financial and monetary calculations requiring high precision.
o decimal: 128-bit decimal floating-point number.
 Character Type: Used for single characters.
o char: 16-bit Unicode character.
 Boolean Type: Used for logical values.
o bool: Represents true or false.

5
int num = 5; // Integer (whole number)

Console.WriteLine(num);

float mnum = 5.75F;

Console.WriteLine(mnum);

double dnum = 5.99D; // Floating point number

char my = 'D'; // Character

bool mb = true; // Boolean

string text = "Hello"; // String

Variables are containers for storing data values.

In C#, there are different types of variables (defined with different


keywords)

 int - stores integers (whole numbers), without decimals, such as


123 or -123
 double - stores floating point numbers, with decimals, such as 19.99
or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 string - stores text, such as "Hello World". String values are
surrounded by double quotes
 bool - stores values with two states: true or false

Declaring (Creating) Variables:To create a variable, specify the type and assign it a value:
Syntax

type variableName = value; Example : int num = 5;

6
Variables are containers for storing data values.

In C#, there are different types of variables (defined with different


keywords), for example:

 int - stores integers (whole numbers), without decimals, such as


123 or -123
 double - stores floating point numbers, with decimals, such as 19.99
or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 string - stores text, such as "Hello World". String values are
surrounded by double quotes
 bool - stores values with two states: true or false

To create a variable, specify the type and assign it a value:

Syntax

type variableName = value;


int num =10;

Based on Data Type

(a) Value Type Variables

 Store the actual value directly in memory.


 Stored in the stack.
 Examples:
o Primitive types → int, float, double, char, bool
o Structs → struct Point { ... }
o Enums → enum Colors { Red, Blue }

👉 Example:

int x = 10; // Value stored directly in x


char grade = 'A';

(b) Reference Type Variables

 Store a reference (address) to the value, not the value itself.


 Data is stored in the heap, variable holds the reference in the stack.
 Examples:
o Objects → object obj = new object();
o Class instances → Person p = new Person();

7
o Arrays → int[] numbers = new int[5];
o String → string name = "Suresh";

string name = "Hello"; // name stores reference to the actual


string in heap

(c) Pointer Variables (Unsafe Code Only)

 Store the memory address of another variable.


 Used in unsafe context.
unsafe {

int x = 10;
int* ptr = &x;
}

2. Based on Declaration / Scope :(a) Local Variables

 Declared inside a method, constructor, or block.


 Exist only within that block.
void Show() {

int num = 100; // local variable


}

(b) Instance Variables:Non-static fields inside a class. Each object of the class gets its own
copy.
class Car {

string color; // instance variable


}

(c) Static Variables

 Declared with static keyword inside a class.


 Shared among all objects of the class.
👉 Example:

class Counter {
static int count; // static variable
}

(d) Constant Variables

 Declared with const keyword.


 Value cannot change after initialization.
👉 Example:

8
const double PI = 3.14159;

(e) Read-Only Variables

 Declared with readonly keyword.


 Value can only be assigned at declaration or in constructor.
👉 Example:

readonly int myId;


public Demo(int id) {
myId = id; // allowed only in constructor
}

(f) Volatile Variables

 Declared with volatile keyword.


 Value can be modified by multiple threads at the same time (thread-safe).
👉 Example:

volatile bool isRunning;

(g) Dynamic Variables

 Declared with dynamic keyword.


 Type is resolved at runtime (like Python).
👉 Example:

dynamic value = 1;
value = "Now a string";
Operators in C# : operators, which are special symbols used to perform operations

9
C# Operators and Precedence

10
C# Conditions and If Statements

You already know that C# supports familiar comparison conditions from mathematics,
such as:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

C# has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

The if Statement :Use the statement to specify a block of code to be executed if a


condition is True.
if (condition)
{
// block of code to be executed if the condition is True
}

11
In the example below, we test two values to find out if 20 is greater than 18. If the
condition is True, print some text:

if (20 > 18) {


Console.WriteLine("20 is greater than 18"); }
int x = 20;
int y = 18;
if (x > y) {
Console.WriteLine("x is greater than y"); }

The else Statement:Use the else statement to specify a block of code to be executed if the
condition is False.
SyntaxGet your own C# Server
if (condition)
{
// block of code to be executed if the condition is True
}
else
{
// block of code to be executed if the condition is False
}
Example
int time = 20;
if (time < 18)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
} // Outputs "Good evening."
The else if Statement
Use the else if statement to specify a new condition if the first condition is False.
Syntax
if (condition1)
{
// block of code to be executed if condition1 is True
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is True
}
else
{
// block of code to be executed if the condition1 is false and condition2 is False
}
Example
int time = 22;

12
if (time < 10)
{
Console.WriteLine("Good morning.");
}
else if (time < 20)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
} // Outputs "Good evening."

C# Switch Statements
Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
This is how it works:
 The switch expression is evaluated once
 The value of the expression is compared with the values of each case
 If there is a match, the associated block of code is executed
 The break and default keywords will be described later in this chapter
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;

13
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
}
// Outputs "Thursday" (day 4)

Loops
Loops can execute a block of code as long as a specified condition is
reached.

Loops are handy because they save time, reduce errors, and they make
code more readable.

C# While Loop
The while loop loops through a block of code as long as a specified condition is True:
SyntaxGet your own C# Server
while (condition)
{
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a
variable (i) is less than 5:
Example
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the
condition is true.
Syntax
do
{
// code block to be executed

14
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once,
even if the condition is false, because the code block is executed before the condition is
tested:
Example
int i = 0;
do
{
Console.WriteLine(i);
i++;
}
while (i < 5);
C# For Loop
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 0 to 4:
Example
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been
executed.

Another Example
This example will only print even values between 0 and 10:
Example
for (int i = 0; i <= 10; i = i + 2)
{
Console.WriteLine(i);
}

Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
// Outer loop

15
for (int i = 1; i <= 2; ++i)
{
Console.WriteLine("Outer: " + i); // Executes 2 times

// Inner loop
for (int j = 1; j <= 3; j++)
{
Console.WriteLine(" Inner: " + j); // Executes 6 times (2 * 3)
}
}
C# Foreach Loop

The foreach Loop


There is also a foreach loop, which is used exclusively to loop through elements in
an array (or other data sets):
Syntax
foreach (type variableName in arrayName)
{
// code block to be executed
}
The following example outputs all elements in the cars array, using a foreach loop:
Example
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}

C# Break and Continue

C# Break
You have already seen the break statement used in an earlier chapter of this tutorial. It
was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
This example jumps out of the loop when i is equal to 4:
ExampleGet your own C# Server
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
break;
}
Console.WriteLine(i);
}

C# Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs,
and continues with the next iteration in the loop.
This example skips the value of 4:

16
Example
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
Console.WriteLine(i);
}

C# Type Casting

Type casting is when you assign a value of one data type to another type.

In C#, there are two types of casting:

 Implicit Casting (automatically) - converting a smaller type to a larger type size


char -> int -> long -> float -> double

 Explicit Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char

Implicit Casting

Implicit casting is done automatically when passing a smaller size type to a larger size
type:

ExampleGet your own C# Server


int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt); // Outputs 9
Console.WriteLine(myDouble); // Outputs 9
Explicit Casting:Explicit casting must be done manually by placing the type in
parentheses in front of the value:
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
Console.WriteLine(myDouble); // Outputs 9.78
Console.WriteLine(myInt); // Outputs 9

Type Conversion using built in Methods:It is also possible to convert data types
Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32
(int) and Convert.ToInt64 (long):
int myInt = 10;

17
double myDouble = 5.25;
bool myBool = true;
Console.WriteLine(Convert.ToString(myInt)); // convert int to string
Console.WriteLine(Convert.ToDouble(myInt)); // convert int to double
Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int
Console.WriteLine(Convert.ToString(myBool)); // convert bool to string

Creating and Using Objects in C# step by step.

1. What is an Object in C#?

 An object is an instance of a class.


 A class defines the blueprint, while an object represents a real-world entity
created from that blueprint.

 Class = Car (blueprint)


 Object = myCar (a specific car, like a red BMW)

2. Steps to Create and Use Objects

(a) Define a Class

class Car
{
// Fields (data members)
public string brand;
public int speed;

// Method (function inside class)


public void Drive()
{
Console.WriteLine($"{brand} is driving at {speed} km/h.");
}
}

(b) Create an Object (Using new keyword)

class Program
{
static void Main(string[] args)
{
// Object creation
Car myCar = new Car();

// Assign values to fields


myCar.brand = "BMW";
myCar.speed = 120;

18
// Call method using object
myCar.Drive();
}
}

Output:

BMW is driving at 120 km/h.

3. Ways to Create Objects

(a) Using new keyword

Car car1 = new Car();

(b) Using Object Initializer

Car car2 = new Car { brand = "Audi", speed = 150 };


car2.Drive();

(c) Using Constructor

class Car
{
public string brand;
public int speed;

// Constructor
public Car(string b, int s)
{
brand = b;
speed = s;
}

public void Drive()


{
Console.WriteLine($"{brand} is driving at {speed} km/h.");
}
}

class Program
{
static void Main()
{
Car car3 = new Car("Mercedes", 180); // Using constructor
car3.Drive();
}
}

19
4. Multiple Objects from Same Class
Car car1 = new Car { brand = "Tesla", speed = 200 };
Car car2 = new Car { brand = "Ford", speed = 100 };

car1.Drive();
car2.Drive();

Output:

Tesla is driving at 200 km/h.


Ford is driving at 100 km/h.

5. Using Objects as Parameters


class Garage
{
public void Park(Car c)
{
Console.WriteLine($"{c.brand} parked in garage.");
}
}

class Program
{
static void Main()
{
Car myCar = new Car { brand = "Honda", speed = 90 };
Garage g = new Garage();
g.Park(myCar); // Passing object as parameter
}
}

Arrays in C# : Create an Array

Arrays are used to store group of values in have a common name and common data
type.

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

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

Access the Elements of an Array

You access an array element by referring to the index number.

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

20
Console.WriteLine(cars[0]);

// Outputs Volvo Array Length

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

Console.WriteLine(cars.Length); // Outputs 4

// Arrays accessed using for loop


string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.Length; i++)
{
Console.WriteLine(cars[i]);
}

// Arrays accessed using for each loop

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


foreach (string i in cars)
{
Console.WriteLine(i); }

Strings in C#

 A string is a sequence of characters enclosed in double quotes (").


 In C#, string is an object of the System.String class (reference type).
 Strings are immutable → once created, they cannot be changed (a new string is
created instead).

1. Declaring Strings

string s1 = "Hello";
string s2 = "World"; string s3 = s1 + " " + s2; // Concatenation

2. Common String Operations: (a) Length

string name = "Suresh";


Console.WriteLine(name.Length); // 6

(b) Concatenation

string result = string.Concat("Hello", " ", "World");


Console.WriteLine(result); // Hello World

(c) Interpolation

string first = "C#";


string version = "10";
string msg = $"{first} version {version}";
Console.WriteLine(msg); // C# version 10

21
(d) Access Characters

string word = "Apple";


Console.WriteLine(word[0]); // A

3. Important String Methods

(a) Changing Case

string text = "Hello World";


Console.WriteLine(text.ToUpper()); // HELLO WORLD
Console.WriteLine(text.ToLower()); // hello world

(b) Substring

string text = "Programming";


Console.WriteLine(text.Substring(0, 4)); // Prog

(c) Contains, StartsWith, EndsWith

string msg = "Welcome to C#";


Console.WriteLine(msg.Contains("C#")); // True
Console.WriteLine(msg.StartsWith("Welcome"));// True
Console.WriteLine(msg.EndsWith("Java")); // False

(d) IndexOf / LastIndexOf

string s = "banana";
Console.WriteLine(s.IndexOf("a")); // 1
Console.WriteLine(s.LastIndexOf("a")); // 5

(e) Replace

string s = "I like Java";


Console.WriteLine(s.Replace("Java", "C#")); // I like C#

(f) Trim: string s = " hello ";

Console.WriteLine(s.Trim()); // "hello"

(g) Split and Join : string data = "one,two,three";

string[] parts = data.Split(',');


foreach (string p in parts)
Console.WriteLine(p);

string joined = string.Join("-", parts);


Console.WriteLine(joined); // one-two-three

(h) Equals & Compare :

22
string a = "hello";
string b = "Hello";

Console.WriteLine(a.Equals(b)); // False (case-sensitive)


Console.WriteLine(a.Equals(b, StringComparison.OrdinalIgnoreCase)); // True
Console.WriteLine(string.Compare(a, b)); // -1 (means a < b)

4. StringBuilder (for mutable strings)

Since strings are immutable, use StringBuilder when modifying strings repeatedly.

using System.Text;

StringBuilder sb = new StringBuilder("Hello");


sb.Append(" World");
sb.Replace("World", "C#");
Console.WriteLine(sb.ToString()); // Hello C#

23

You might also like