0% found this document useful (0 votes)
4 views80 pages

Net Unit1 Notes

The .NET Framework is a Microsoft software development framework that provides a runtime environment and libraries for building applications on Windows. It supports multiple programming languages and application types, with key components including the Common Language Runtime (CLR) for code execution and the Framework Class Library (FCL) for reusable classes and methods. The framework features platform independence, language independence, automatic resource management, and easy database connectivity.

Uploaded by

NPR ASC
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)
4 views80 pages

Net Unit1 Notes

The .NET Framework is a Microsoft software development framework that provides a runtime environment and libraries for building applications on Windows. It supports multiple programming languages and application types, with key components including the Common Language Runtime (CLR) for code execution and the Framework Class Library (FCL) for reusable classes and methods. The framework features platform independence, language independence, automatic resource management, and easy database connectivity.

Uploaded by

NPR ASC
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

OVERVIEW OF .

NET FRAMEWORK

INTRODUCTION

The .NET Framework is a software development framework developed by Microsoft that


provides a runtime environment and a set of libraries and tools for building and running
applications on Windows operating systems. The .NET framework is primarily used on
Windows, while .NET Core (which evolved into just .NET starting from version 5) is cross-
platform. The framework supports multiple programming languages, such as C#, F#, and
[Link], and supports a range of application types, including desktop, web, mobile, cloud, and
gaming applications.

Main Components of .NET Framework

 Common Language Runtime(CLR):

o The CLR is the heart of the .NET Framework, acting as a virtual machine that
runs the code and manages various services such as memory management,
security, and thread management. Code that is compiled and executed within the
CLR is called "Managed Code," while code that the CLR does not manage is
known as "Unmanaged Code."

 .NET Framework Class Library (FCL):

o The FCL provides a large set of reusable classes and methods for application
development.

o This includes libraries for input/output operations, networking, data access, UI


controls, and more.

.NET is a software framework that is designed and developed by Microsoft. The first version of
the .Net framework was 1.0 which came in the year 2002. In easy words, it is a virtual machine
for compiling and executing programs written in different languages like C#, [Link], etc.

It is used to develop Form-based applications, Web-based applications, and Web services. There
is a variety of programming languages available on the .Net platform, [Link] and C# being the
most common ones. It is used to build applications for Windows, phones, web, etc. It provides a
lot of functionalities and also supports industry standards.

.NET Framework supports more than 60 programming languages of which 11 programming


languages are designed and developed by Microsoft. The remaining Non-Microsoft Languages
are supported by .NET Framework but not designed and developed by Microsoft.

Features of .NET

1. Platform independent

Platform independent means it supports cross platform that works on multiple platforms.
Whenever we make .NET program, we use windows operating system. In windows operating
system we have different versions such as (window 10, window 8, window 9 etc ). Suppose, if
we develop programming code in window 11 and the same code try to run on different version
like in window 10 operating system it will work perfectly fine. So, we can say that it is
interoperable between multiple windows operating system.

2. Language Independent

As Programmer can choose any language from a various programming language available on the
.NET platform. So, if I have the code of one language. I can just work with other language as
well. We can say code written in one language can be used in other language. Suppose program
is

develop in [Link] user can easily reuse that code in C#.NET as well. That means user can
reuse the code from one language to another. So, as we don’t need to write code again and again
so it improves efficiency and performance will be faster with the help of different languages.

3. Automatic management of resources

It automatically manages the resources(file, memory, database etc). In .NET we have garbage
collector that periodically checks for unused objects (memory space) in our code, and
automatically free up that space if it is no longer needed in the program.

4. Consistent programming model


.NET is the pure object oriented programming language. .NET is a framework inside we are
having multiple languages like [Link], C#.NET(C [Link]) etc and all these languages
having object oriented features. So, we can say that it is having consistent object oriented
programming model across all languages. We know that object oriented contain features like i)
abstraction ii) encapsulation iii) polymorphism iv)inheritance.

5. Easy database connectivity

[Link] is used to develop applications to interact with Databases suchas Oracle or Microsoft
SQL Server. So, .NET can connect easily with database using [Link] technology.

COMMON LANGUAGE RUNTIME (CLR)

The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that
manages the execution of .NET applications. It is responsible for loading and executing the code
written in various .NET programming languages, including C#, [Link], F#, and others.

When a C# program is compiled, the resulting executable code is in an intermediate language


called Common Intermediate Language (CIL) or Microsoft Intermediate Language (MSIL). This
code is not machine-specific, and it can run on any platform that has the CLR installed. When the
CIL code is executed, the CLR compiles it into machine code that can be executed by the
processor.

Working of CLR

1. Compilation and Execution:

When we write a C# program, it gets compiled into Intermediate Language (IL) code, which is
platform-independent.
The CLR then uses a Just-In-Time (JIT) compiler to convert the IL code into machine-specific
code while the program runs.

2. Services Provided by CLR:

CLR handles automatic memory management through Garbage Collection, preventing memory
leaks.

It ensures that data types are used correctly and safely.

The CLR checks the IL code for security risks before running it.

3. Cross-Language Integration:

CLR allows code from different .NET languages (C#, [Link], F#) to work together seamlessly
through the Common Type System (CTS).

Key Components of CLR

As the word specify, Common means CLR provides a common runtime or execution
environment as there are more than 60 .NET programming languages.

Common Language Specification (CLS): It defines common rules so that code written in
different languages can interoperate.

Managed Code: The MSIL code which is managed by the CLR is known as the Managed Code.
For managed code CLR provides three .NET facilities:

Unmanaged Code: Before .NET development, programming languages [Link] Components


& Win32 API do not generate the MSIL code. So these are not managed by CLR rather managed
by Operating System.

JIT Compiler: It converts IL code into machine code specific to the system at runtime,
optimizing execution.
Garbage Collector: It automatically manages memory by freeing unused objects, reducing the
need for manual memory management.

Common Type System (CTS): This ensures that different data types across languages are
understood by CLR and can work together. There are 2 Types of CTS that every .NET
programming language have:

Value Types: Value Types will store the value directly into the memory location. These types
work with stack mechanisms only. CLR allows memory for these at Compile Time.

Reference Types: Reference Types will contain a memory address of value because the reference
types won’t store the variable value directly in memory. These types work with Heap
mechanism. CLR allot memory for these at Runtime.

Role of CLR in the Execution of a C# Program

Suppose we 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.
FRAMEWORK CLASS LIBRARY

The Framework Class Library or FCL provides the system functionality in the .NET Framework
as it has various classes, data types, interfaces, etc. to perform multiple functions and build
different types of applications such as desktop applications, web applications, mobile
applications, etc. The Framework Class Library is integrated with the Common Language
Runtime (CLR) of the .NET framework and is used by all the .NET languages such as C#, F#,
Visual Basic .NET, etc.

Categories in the Framework Class Library

The functionality of the Framework Class Library can be broadly divided into three categories i.e
utility features written in .NET, wrappers around the OS functionality and frameworks. These
categories are not rigidly defined and there are many classes that may fit into more than one
category.
Details about the Categories in the Framework Class Library are given as follows:

 Utility Features: The utility features in the FCL includes various collection classes such
as list, stack, queue, dictionary, etc. and also classes for more varied manipulations such
as Regex class for regular expressions.

 Wrappers Around OS functionality: Some of the features in the FCL are wrappers
around the underlying Windows OS functionality. These include the classes for using the
file system, the classes to handle the network features, the classes to handle I/O for
console applications, etc.

 Frameworks: There are various frameworks available in the FCL to develop certain
applications. For example, [Link] is used to develop web applications, Windows
Presentation Foundation (WPF) is used to render user interfaces in Windows applications,
and so on.

Namespaces in the Framework Class Library

Namespaces in the Framework Class Library are a group of related classes and interfaces that
can be used by all the .NET framework languages. Some of the namespaces in the FCL along
with their description is given as follows:

Namespace Description

The Accessibility namespace is a part of the managed wrapper for


Accessibility
the COM accessibility interface.

The [Link] namespace provides support for Windows


[Link]
Workflow Foundation applications.

[Link] The [Link] namespace has support for compilation and


Namespace Description

code generation for the C# source code.

The [Link] namespace has support for compilation and


[Link]
code generation for the JScript source code.

[Link] The [Link] namespace has support for compilation


c and code generation for the VisualBasic source code.

The System namespace has base classes for definition of interfaces,


System data types, events, event handlers, attributes, processing exceptions
etc.

A data type specifies the size and type of variable values.

It is important to use the correct data type for the corresponding variable; to avoid errors, to save
time and memory, but it will also make your code more maintainable and readable. The most
common data types are:

Data Type Size Description

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,03


9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal


double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal dig

bool 1 byte Stores true or false values

char 2 bytes Stores a single character/letter, surrounded by single quotes

string 2 bytes per Stores a sequence of characters, surrounded by double quotes


character

Numbers

Number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -456), without
decimals. Valid types are int and long. Which type you should use, depends on the numeric
value.

Floating point types represents numbers with a fractional part, containing one or more decimals.
Valid types are float and double.

Even though there are many numeric types in C#, the most used for numbers are int (for whole
numbers) and double (for floating point numbers). However, we will describe them all as you
continue to read.

Integer Types

Int

The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in
our tutorial, the int data type is the preferred data type when we create variables with a numeric
value.
Example

int myNum = 100000;

[Link](myNum);

Long

The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note that
you should end the value with an "L":

Example

long myNum = 15000000000L;

[Link](myNum);

Floating Point Types

You should use a floating point type whenever you need a number with a decimal, such as 9.99
or 3.14515.

The float and double data types can store fractional numbers. Note that you should end the value
with an "F" for floats and "D" for doubles:

Float myNum = 5.75F;

[Link](myNum)

Double Example

double myNum = 19.99D;

[Link](myNum);

OPERATORS IN C#

In C#, Operators are special types of symbols which perform operations on variables or values. It
is a fundamental part of language which plays an important role in performing different
mathematical operations. It takes one or more operands and performs operations to produce a
result.

Types of Operators

C# has some set of operators that can be classified into various categories based on their
functionality. Categorized into the following types:

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Assignment Operators

5. Increment and Decrement Operators

6. Bitwise Operators

7. Ternary Operator

8. Null Coalescing Operator

1. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations on numeric values.

 Addition ( + )

 Subtraction ( - )

 Multiplication ( * )

 Division ( / )

 Modulus ( % )

Example:

using System;
class Geeks

static void Main(string[] args)

int x = 8, y = 4;

// Using different arithmetic operators

[Link]("Addition: " + (x + y));

[Link]("Subtraction: " + (x - y));

[Link]("Multiplication: " + (x * y));

[Link]("Division: " + (x / y));

[Link]("Modulo: " + (x % y));

Output

Addition: 12

Subtraction: 4

Multiplication: 32

Division: 2

Modulo: 0

2. Relational Operators
Relational operators are used to compare values. And we get the answer in either true or false
( boolean). Let's learn about different relation operators.

 Equal to ( == )

 Not equal to ( != )

 Less than ( < )

 Less than or equal to ( <= )

 greater than ( > )

 Greater than or equal to ( >= )

Example:

using System;

class Geeks

static void Main(string[] args)

int x = 10, y = 20;

// Compare using different relational operators

[Link](x == y);

[Link](x != y);

[Link](x > y);

[Link](x < y);

[Link](x >= y);


[Link](x <= y);

Output

False

True

False

True

False

True

3. Logical Operators

Used when multiple conditions and there we can combine these to compare complex conditions.

 Logical AND (&&) : returns true when both conditions are true.

 Logical OR ( || ) : returns true if at least one condition is true.

 Logical NOT ( ! ): returns true when a condition is false and vice-versa.

Example:

using System;

class Geeks

static void Main(string[] args)

{
bool a = true, b = false;

// conditional operators

if (a && b)

[Link]("a and b are true");

if (a || b)

[Link]("Either a or b is true");

if (!a)

[Link]("a is not true");

if (!b)

[Link]("b is not true");

Output

Either a or b is true

b is not true

4. Assignment Operators

Assignment operators are used to assign values to variables. The assignment operator is
combined with others to create shorthand compound statements. Common compound operators
include:
 += (Add and assign.)

 -= (Subtract and assign.)

 *= (Multiply and assign.)

 /= (Divide and assign.)

 %= (Modulo and assign.)

Example:

using System;

class Geeks

static void Main(string[] args)

int a = 10;

// Using different assignment operators

a += 5;

[Link]("Add Assignment: " + a);

a -= 3;

[Link]("Subtract Assignment: " + a);

a *= 2;

[Link]("Multiply Assignment: " + a);


a /= 4;

[Link]("Division Assignment: " + a);

a %= 5;

[Link]("Modulo Assignment: " + a);

Output

Add Assignment: 15

Subtract Assignment: 12

Multiply Assignment: 24

Division Assignment: 6

Modulo Assignment: 1

5. Increment/Decrement Operators

Increment and decrement operators are used to increase or decrease the value of a variable by 1.

++ (Increments by 1)

 Post-Increment: Uses value first, then increments.

 Pre-Increment: Increments first, then uses value.

-- (Decrements by 1)

 Post-Decrement: Uses value first, then decrements.

 Pre-Decrement: Decrements first, then uses the value.


Example:

using System;

public class Geeks

static public void Main()

int a = 5;

// pre-increment

[Link]("++a returns: " + ++a);

// post-increment

[Link]("a++ returns: " + a++);

[Link]("Final value of a: " + a);

[Link]();

// pre-decrement

[Link]("--a returns: " + --a);

// post-decrement
[Link]("a-- returns: " + a--);

[Link]("Final value of a: " + a);

Output

++a returns: 6

a++ returns: 6

Final value of a: 7

--a returns: 6

a-- returns: 6

Final value of a: 5

6. Bitwise Operators

Bitwise operators are used to perform bit-level operations on integer values. It takes less time
because it directly works on the bits.

Example:

using System;

class Geeks

static void Main(string[] args)


{

// Binary representation: 1010

int x = 10;

// Binary representation: 0010

int y = 2;

// Bitwise AND

[Link](x & y);

// Bitwise OR

[Link](x | y);

// Bitwise XOR

[Link](x ^ y);

// Bitwise NOT

[Link](~x);

// Shifting bit by one on the left

[Link](x << 1);

// Shifting bit by one on the right


[Link](x >> 1);

Output

-6

10

7. Ternary Operator

The ternary operator is a shorthand for an if-else statement. It evaluates a condition and returns
one of two values depending on whether the condition is true or false.

Syntax

condition ? if true : if false

Example:

using System;

public class Geeks

static public void Main()

{
int a = 10, b = 5;

// similar to if else

string result = (a > b) ? "a" : "b";

[Link](result + " is greater");

Output

a is greater

8. Null-Coalescing Operator

null-coalescing operator is used when we want to put a default value if the value of the variable
is null.

Example:

using System;

public class Geeks

static public void Main()

string name = null;

// Name have null value takes default value instead of null

string result = name ? ? "Default Name";


[Link](result);

Output

Default Name

CONDITIONAL STATEMENTS

Decision Making in programming is similar to decision making in real life. In


programming too, a certain block of code needs to be executed when some condition is
fulfilled.

A programming language uses control statements to control the flow of execution of


program based on certain conditions. These are used to cause the flow of execution to
advance and branch based on changes to the state of a program.

Conditional Statements of C#

There are few conditional statements of C# is mentioned below:

 if

 if-else

 if-else-if

 Nested if

 Switch

 Nested Switch

1. If Statement
The if statement checks the given condition. If the condition evaluates to be true then the
block of code/statements will execute otherwise not.

Syntax

if ( condition ) {
//code to be executed
}

Note: If the curly brackets { } are not used with if statements then the statement just next to
it is only considered associated with the if statement.

Flowchart:

Example: Using if statement

using System;

public class Geeks

{
public static void Main(string[] args)

string name = "Geek";

// Using if statement

if (name == "Geek") {

[Link]("GeeksForGeeks");

Output

GeeksForGeeks

2. If-else Statement

The if statement evaluates the code if the condition is true but what if the condition is not
true, here comes the else statement. It tells the code what to do when the if condition is
false.

Syntax

if(condition)
{
// code if condition is true
}
else
{
// code if condition is false
}

Flowchart:

Example: Using if-else statement

public class Geeks

public static

using System;

public class Geeks

{
public static void Main(string[] args)

string name = "Geek";

// Using if-else statement

if (name == "Geeks") {

[Link]("GeeksForGeeks");

else {

[Link]("Geeks");

Output

Geeks

3. If-else-if ladder Statement

The if-else-if ladder is used when you need to test multiple conditions one after another.

The program evaluates each condition in order.

As soon as one condition is true, its block executes and the ladder ends.

If none of the conditions are true, the else block (if provided) executes.

Syntax
if(condition1)

// code to be executed if condition1 is true

else if(condition2)

// code to be executed if condition2 is true

else if(condition3)

// code to be executed if condition3 is true

...

else

// code to be executed if all the conditions are false

Flowchart:
xample: Using if-else-if ladder

using System;

class Geeks

public static void Main(String[] args)


{

int i = 20;

// Using If-else-if ladder

if (i == 10)

[Link]("i is 10");

else if (i == 15)

[Link]("i is 15");

else if (i == 20)

[Link]("i is 20");

else

[Link]("i is not present");

Output

i is 20

4. Nested - If Statement

If statement inside an if statement is known as nested if. if statement in this case is the target of
another if or else statement. When more than one condition needs to be true and one of the
condition is the sub-condition of parent condition, nested if can be used.

Syntax
if (condition1)

// code to be executed

// if condition2 is true

if (condition2)

// code to be executed

// if condition2 is true

Flowchart:

Example: Using Nested-if statement


using System;

class Geeks

public static void Main(String[] args)

int i = 10;

if (i == 10) {

// nested - if statement will only be executed if statement above it is true

if (i < 12)

[Link]("i is smaller than 12 too");

else

[Link]("i is greater than 11");

Output

i is smaller than 12 too


5. Switch Statement

Switch statement is an alternative to long if-else-if ladders. The expression is checked for
different cases and the one match is execute. Break Statement is used to move out of the switch.
If the break is not used, the control will flow to all cases below it until break is found or switch
comes to an end. There is default case (optional) at the end of switch, if none of the case matches
then default case is executed.

Syntax

switch (expression)

case value1: // statement sequence

break;

case value2: // statement sequence

break;

case valueN: // statement sequence

break;

default: // default statement sequence

Flowchart:
Example: Using Switch case

using System;

public class Geeks

public static void Main(String[] args)

{
int number = 30;

// Using Switch case

switch(number)

case 10:

[Link]("case 10");

break;

case 20:

[Link]("case 20");

break;

case 30:

[Link]("case 30");

break;

default:

[Link]("None matches");

break;

Output 30

6. Nested Switch
Nested Switch case are allowed in C# . In this case, switch is present inside other switch case.
Inner switch is present in one of the cases in parent switch.

Example:

using System;

public class Geeks

public static void Main(String[] args)

int outter = 2;

int inner = 3;

// Using Nested Switch Case

switch(outter){

case 1:

[Link]("Outter Case 1");

break;

case 2:
[Link]("Outter Case 2");

switch(inner)

case 1:

[Link]("Inner Case 1");

break;

case 2:

[Link]("Inner Case 2");

break;

case 3:

[Link]("Inner Case 3");

break;

default:

[Link]("Default Inner Run");

break;

break;

default:

[Link]("Default Outter Run");

break;

}
Output

Outter Case 2

Inner Case 3

LOOPING STATEMENTS

Looping in a programming language is a way to execute a statement or a set of statements


multiple times, depending on the result of the condition to be evaluated to execute
statements. The result condition should be true to execute statements within loops.

Types of Loops in C#

Loops are mainly divided into two categories:

Entry Controlled Loops

Exit Controlled Loops

1. Entry Controlled Loops

The loops in which the condition to be checked before entering the loop body are known as
Entry Controlled Loops.

Example: while, for

1.1 while Loop : The test condition is given at the beginning of the loop and all statements
are executed till the given Boolean condition is satisfied. When the condition becomes false,
the control will be out of the while loop.
Syntax:

while (boolean condition)

loop statements...

Flowchart:

Example:
using System;

class Geeks

public static void Main()

int x = 1;

// Exit when x becomes greater than 4

while (x <= 4)

[Link]("GeeksforGeeks");

// Increment the value of x for next iteration

x++;

Output

GeeksforGeeks

GeeksforGeeks
GeeksforGeeks

GeeksforGeeks

1.2 for loop : The for loop is a control flow statement that allows you to execute a block of
code repeatedly for a fixed number of iterations. It’s commonly used when the number of
repetitions is known beforehand.

Syntax:

for (loop variable initialization ; testing condition; increment / decrement)

// statements to be executed

Flowchart:
Note:

Initialization part is evaluated only once when the for loop starts.

Example:
using System;

class Geeks

public static void Main()

// for loop begins when x=1 and runs till x <= 4

for (int x = 1; x <= 4; x++)

[Link]("GeeksforGeeks");

Output

GeeksforGeeks

GeeksforGeeks

GeeksforGeeks

GeeksforGeeks

2. Exit Controlled Loops

The loops in which the condition is checked after the loop body is known as Exit Controlled
Loops.

Note: In Exit Controlled Loops, loop body will be evaluated for at-least one time as the
testing condition is present at the end of loop body.
Example: do-while Loop

2.1 do-while loop : The do while loop is similar to while loop with the only difference that it
checks the condition after executing the statements, i.e it will execute the loop body one
time for sure because it checks the condition after executing the statements.

Syntax :

do

statements..

} while (condition);

Flowchart:
xample:

using System;

class Geeks

public static void Main()

int x = 21;
do

// The line will be printed even if the condition is false

[Link]("GeeksforGeeks");

x++;

while (x < 20);

Output

GeeksforGeeks

Class and Objects in C#In C#, classes and objects are the core building blocks of object-
oriented programming. A class provides a way to model real-world entities by grouping
data and behavior together, while objects represent the actual entities created from these
classes. This approach makes programs more organized, reusable and easier to maintain.

Classes

A class in C# is a user-defined type that encapsulates data and behavior. It can contain
fields, properties, methods, events and constructors. A class itself does not occupy memory
until objects are created from it.

Syntax:
class ClassName{

// Fields

// Properties

// Methods

Declaration of Class

A class declaration contains only a keyword class, followed by an identifier(name) of the


class.

However, some optional attributes can be used with class declaration according to the
application requirement. Class declarations can include these components, in order:

Modifiers: Define the accessibility of a class. By default, a class is internal.

Keyword class: Used to declare a class.

Class Identifier: The name of the class, conventionally starting with a capital letter.

Base Class (Optional): Specifies a parent class to inherit from, using the : symbol.

Interfaces (Optional): A comma-separated list of interfaces implemented by the class, also


preceded by : A class can implement multiple interfaces.

Body: Enclosed within { }, containing members like fields, properties, methods,


constructors and events.
Example:

using System;

// declaring public class

public class Geeks

// field variables

public int a, b;

// member function or method

public void Display(){

[Link]("Class in C#");

Objects

Object in C# is something you create from a class, which represents a real-world entity and
lets you use the data and actions defined in that class.

In C# an object consists of :
State: It is represented by attributes of an object and reflects the properties of an object.

Behaviour: It is represented by the methods of an object and also reflects the response of an
object with other objects.

Identity: It gives a unique name to an object and enables one object to interact with other
[Link] Objects (Also called instantiating a class)

Note:

Classes define the blueprint of state, behavior and identity. Objects are the real instances
that actually hold the state, show behavior and carry identity.

Declaration of Object

When an object is created, the class is instantiated. All objects share the class’s behavior,
but each has its own unique state. A class can have multiple instances.

Example:

public class Dog{

// Instance Variables

String name;

String breed;

int age;

String color;
// Constructor Declaration of Class same name as class

public Dog(String name, String breed, int age, String color){

[Link] = name;

[Link] = breed;

[Link] = age;

[Link] = color;

public String GetName()

return name;

public String GetBreed()

return breed;

public int GetAge()

return age;

}
public String GetColor()

return color;

public override String ToString()

return "my name is: " + name +

"\nmy breed is: " + breed +

"\nmy age is: " + age;

public static void Main(String[] args)

// Creating object

Dog tuffy = new Dog("tuffy", "papillon", 5, "white");

[Link]([Link]());

Arrays in C#
Last Updated : 09 Sep, 2025

An array is a linear data structure that stores a fixed-size sequence of elements of the same
data type in contiguous memory locations. It allows accessing elements using an index,
starting from 0.

The array has can contain primitive data types as well as objects of a class depending on
the definition of an array.

Whenever use primitives data types, the actual values have to be stored in contiguous
memory locations.

In the case of objects of a class, the actual objects are stored in the heap segment.

Example: Declaring and initializing an array

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

The following figure shows how array stores values sequentially:

download

Array in C#

Syntax

<Data Type>[ ] <Name_Array>

Here,
<Data Type> : It define the element type of the array.

[ ] : It define the size of the array.

<Name_Array> : It is the Name of array.

Note : Only Declaration of an array doesn’t allocate memory to the array. For that array
must be initialized.

Array Initialization

Aarray is a reference type so the new keyword used to create an instance of the array. We
can assign initialize individual array elements, with the help of the index.

Syntax:

type [ ] < Name_Array > = new < datatype > [size];

Here, type specifies the type of data being allocated, size specifies the number of elements in
the array and Name_Array is the name of an array variable. And new will allocate memory
to an array according to its size.

Examples: To Show Different ways for the Array Declaration and Initialization

Syntax

Use Cases
Example

<data_type>[] <arr_name> = new <data_type>[size];

Defining array with size, but not assigns values

int[] arr1 = new int[5];

<data_type>[] <arr_name> = new <data_type>[size]{ array_elements};

Defining array with size and assigning the values at the same time

int[] arr2 = new int[5]{1, 2, 3, 4, 5};

<data_type>[] <arr_name> = { array_elements};

The value of the array is directly initialized without taking its size

int[] intArray3 = {1, 2, 3, 4, 5};

Arrays can be initialized after the declaration. It is not necessary to declare and initialize at
the same time using the new keyword.
Example:

// Declaration of the array

string[] str1, str2;

// Initialization of array

str1 = new string[5]{ “Element 1”, “Element 2”, “Element 3”, “Element 4”, “Element 5” };

str2 = new string[5]{ “Element 1”, “Element 2”, “Element 3”, “Element 4”, “Element 5” };

Note :

Initialization without giving size is not valid in C#. It will give a compile-time error.

Example: Wrong Declaration for initializing an array

// Compile-time error: must give size of an array

int[] intArray = new int[];

// Error : wrong initialization of an array

string[] str1;

str1 = {“Element 1”, “Element 2”, “Element 3”, “Element 4” };


Accessing Array Elements

We can access an array value through indexing, placed index of the element within square
brackets with the array name.

Example: Accessing Array elements using different loops

using System;

class Geeks

// Main Method

public static void Main()

// declares an Array of integers.

int[] intArray;

// allocating memory for 5 integers.

intArray = new int[5];

// initialize the first elements of the array


intArray[0] = 10;

// initialize the second elements of the array

intArray[1] = 20;

// so on...

intArray[2] = 30;

intArray[3] = 40;

intArray[4] = 50;

// accessing the elements using for loop

[Link]("For loop :");

for (int i = 0; i < [Link]; i++)

[Link](" " + intArray[i]);

[Link]("");

[Link]("For-each loop :");

// using for-each loop

foreach(int i in intArray)

[Link](" " + i);

[Link]("");
[Link]("while loop :");

// using while loop

int j = 0;

while (j < [Link]) {

[Link](" " + intArray[j]);

j++;

[Link]("");

[Link]("Do-while loop :");

// using do-while loop

int k = 0;

do

[Link](" " + intArray[k]);

k++;

} while (k < [Link]);

Output
For loop : 10 20 30 40 50

For-each loop : 10 20 30 40 50

while loop : 10 20 30 40 50

Do-while loop : 10 20 30 40 50

Types of Arrays in C#

There are three types of Arrays C# supports as mentioned below:

One Dimensional Array

Multi Dimensional Array

Jagged Array

1. One Dimensional Array

In this array contains only one row for storing the values. All values of this array are stored
contiguously starting from 0 to the array size.

For example, declaring a single-dimensional array of 5 integers :

int[] arrayint = new int[5];

The above array contains the elements from arrayint[0] to arrayint[4]. Here, the new
operator has to create the array and also initialize its element by their default values. Above
example, all elements are initialized by zero, Because it is the int type.

Example:
using System;

class Geeks

public static void Main()

// declares a 1D Array of string.

string[] weekDays;

// allocating memory for days.

weekDays = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

// Displaying Elements of array

foreach(string day in weekDays)

[Link](day + " ");

Output
Sun Mon Tue Wed Thu Fri Sat

2. Multidimensional Arrays

The multi-dimensional array contains more than one row to store the values. It is also
known as a Rectangular Array in C# because it’s each row length is same. It can be a 2D-
array or 3D-array or more. To storing and accessing the values of the array, one required
the nested loop.

Syntax:

// creates a two-dimensional array of four rows and two columns.

int[,] intarray = new int[4, 2];

//creates an array of three dimensions, 4, 2 and 3

int[,,] intarray1 = new int[4, 2, 3];

Example: Demonstration of multi- dimensional array

using System;

class Geeks
{

public static void Main()

// The same array with dimensions specified 2, 2 and 3.

int[,, ] arr = new int[2, 2, 3] { { { 1, 2, 3 },

{ 4, 5, 6 } },

{ { 7, 8, 9 },

{ 10, 11, 12 } } };

// Checking elements at particular index

[Link]("arr[1][0][1] : " + arr[1, 0, 1]);

[Link]("arr[1][1][2] : " + arr[1, 1, 2]);

Output

arr[1][0][1] : 8

arr[1][1][2] : 12

3. Jagged Arrays

An array whose elements are arrays is known as Jagged arrays it means “array of arrays“.
The jagged array elements may be of different dimensions and sizes.
Example: Showing how to declare, initialize and access the jagged arrays

using System;

class Geeks

public static void Main()

// Declaring Jagged Array

int[][] arr = { new int[] { 1, 3, 5, 7, 9 },

new int[] { 2, 4, 6, 8 } };

[Link]("Arrays :");

// Display the array elements:

for (int i = 0; i < [Link]; i++)

[Link]("Elements[" + i + "] Array: ");

// Printing the elements of array


for (int j = 0; j < arr[i].Length; j++) {

[Link](arr[i][j] + " ");

[Link]();

Output

Arrays :

Elements[0] Array: 1 3 5 7 9

Elements[1] Array: 2 4 6 8

Points To Remember:

GetLength(int): returns the number of elements in the first dimension of the Array.

When using jagged arrays be safe as if the index does not exist then it will throw exception
which is IndexOutOfRange.

Strings in C#

Last Updated : 05 Sep, 2025


In C#, a string is a sequence of Unicode characters (U+0000 to U+FFFF) used to represent
text. It is an object of the [Link] class. The keyword string and the class name
String are both aliases for [Link], so they can be used interchangeably.

Example:

// creating the string using string keyword

string s1 = “GeeksforGeeks”;

// creating the string using String class

String s2 = “GFG”;

// creating the string using String class

[Link] s3 = “Pro Geek”;

[Link] (defined in the .NET base class library) is a collection of char objects. A
string can hold up to ~2 billion characters (2GB). Strings are immutable, meaning their
value cannot be changed after creation.

using System;
class Geeks

static void Main(string[] args)

// declare a string Name using "[Link]" class

[Link] Name;

// initialization of String

Name = "Geek";

String id;

// initialization of String

id = "33";

// declare a string mrk using string keyword

string mrk;

// initialization of String

mrk = "97";

// Declaration and initialization of the string in a single line

string rank = "1";


[Link]("Name: {0}", Name);

[Link]("Id: {0}", id);

[Link]("Marks: {0}", mrk);

[Link]("Rank: {0}", rank);

Output

Name: Geek

Id: 33

Marks: 97

Rank: 1

Key Characteristics of Strings

Immutable: Once created, the content of a string cannot be altered. Any modification
results in the creation of a new string.

Reference Type: Strings are reference types, but they behave like value types in some
scenarios, such as comparison.

Unicode Support: Strings can contain any Unicode character, allowing support for multiple
languages.

Null and Embedded Nulls: Strings can be null and may also contain embedded null
characters (\0).

Operator Overloading: Strings support operator overloading, such as + for concatenation


and == for comparison.
String Class Properties

Chars: It is used to get the Char object at a specified position in the current String object.

Length: It is used to get the number of characters in the current String object. To know
more about the string class properties please go to String Properties in C#.

Reading String from User-Input

A string can be read out from the user input. ReadLine() method of console class is used to
read a string from user input.

Example:

using System;

class Geeks

static void Main(string[] args)

[Link]("Enter the String");

String read_user = [Link]();


// Displaying the user input

[Link]("User Entered: " + read_user);

Input:

Hello Geeks !

Output:

User Entered: Hello Geeks !

Different Ways to Create Strings

Method

Syntax / Example

Create a string from a literal

string str = "GeeksforGeeks";

Create a string using concatenation

string str = str1 + "data";


Create a string using a constructor

// Create a string from a character array

char[] chars = { 'G', 'E', 'E', 'K', 'S' };

string str = new string(chars);

Create a string using a property or a method

// start and end are the index for str index

string substr = [Link](start, end);

Create a string using formatting

string str = [Link]("{0} {1} Cars color " + "are {2}", [Link](), cname, clr);

Example:

using System;

public class GFG


{

static public void Main ()

// Creating String using string literal

String str = "Geeks";

[Link]("Method 1: " + str);

// Creating String using concatenation

String str2 = str + "ofGeeks";

[Link]("Method 2: " + str2);

// Creating a string using a constructor

char[] chars = { 'G', 'E', 'E', 'K', 'S' };

string str3 = new string(chars);

[Link]("Method 3: " + str3);

// Creating a string using a property or a method

String s = "Geeks For Geeks";

// Index of

int start = [Link](" ") + 1;

int end = [Link](" ", start) - start;

string str4 = [Link](start, end);


[Link]("Method 4: " + str4);

// Creating a string using formatting

int i=1;

int j=2;

int sum= i + j;

String str5 = [Link]("Addition of {0} with {1} is {2}"

, i , j , sum );

[Link]("Method 5: " + str5);

Output

Method 1: Geeks

Method 2: GeeksofGeeks

Method 3: GEEKS

Method 4: For

Method 5: Addition of 1 with 2 is 3

C# String Operations

There are multiple String Operations which we can perform in String in C#. Let us
demonstrate the operations using the example as mentioned below:

Example 1: For performing string operation of interpolation


using System;

public class GFG

// Main Method

static public void Main ()

string name = "GeeksforGeeks";

// Interpolation is performed

string res = $"{name} is the Organisation Name.";

// Printing the String

[Link](res);

[Link]("Length: " + [Link]);

Output
GeeksforGeeks is the Organisation Name.

Length: 39

Example 2: for performing trim, replace and concatenate operation

using System;

public class GFG

static public void Main ()

string first = " GeEks ";

string second = " forGeeks ";

// trim the String

first=[Link]();

second=[Link]();

// Checking element at index 2 first

[Link]("Element at index 2: " + first[2]);


// replacing the element in String

first=[Link]("E","e");

[Link](first+second);

Output

Element at index 2: E

GeeksforGeeks

In the above, two example we have explored many methods we are not full aware of so,
there is a list of Methods associated with Strings in C# attached below.

Methods of C# String

Method

Description

Return Type

Example

IndexOf

Finds the index of the first occurrence of a specified character or substring.

Integer
[Link]("World");

StartsWith

Checks if a string starts with a specified substring.

Boolean

[Link]("Hello");

EndsWith

Checks if a string ends with a specified substring.

Boolean

[Link]("World!");

ToUpper

Converts a string to uppercase.

String

[Link]();

ToLower

Converts a string to lowercase.


String

[Link]();

Split

Splits a string into an array based on a specified delimiter.

String Array

[Link](',');

Join

Combines an array of strings into a single string with a specified delimiter.

String

[Link](" - ", fruitArray);

Contains

Checks if a string contains a specified substring.

Boolean

[Link]("World");

PadLeft
Pads a string with spaces or a specified character to a certain length.

String

[Link](20, '*');

PadRight

Pads a string on the right with spaces or a specified character to a certain length.

String

[Link](20, '*');

Remove

Removes characters from a string starting at a specified index.

String

[Link](5, 7);

Insert

Inserts a string at a specified index.

String

[Link](5, " Beautiful");

Trim
Removes leading and trailing whitespaces.

String

[Link]();

Replace

Replaces occurrences of a substring with another substring.

String

[Link]("fun", "awesome");

String Array

We can also create the array of string and assigns values to it. The string arrays can be
created as follows:

String [] array_variable = new String[Length_of_array]

Example:

using System;
class Geeks

static void Main(string[] args)

String[] str_arr = new String[3];

// Initialising the array of strings

str_arr[0] = "Geeks";

str_arr[1] = "For";

str_arr[2] = "Geeks";

// printing String array

for(int i = 0; i < 3; i++) {

[Link]("value at Index position " + i + " is " + str_arr[i]);

Output

value at Index position 0 is Geeks

value at Index position 1 is For

value at Index position 2 is Geeks

You might also like