0% found this document useful (0 votes)
19 views35 pages

C# Unit I 2024 25 Revised

.NET Framework is a software development platform by Microsoft that supports multiple programming languages and object-oriented programming concepts. It includes components like CLR, CTS, BCL, FCL, and MSIL, which facilitate application development and execution across various platforms. .NET Core, a modern, open-source, and cross-platform framework, allows for building high-performance applications and supports features like modularity and cloud integration.

Uploaded by

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

C# Unit I 2024 25 Revised

.NET Framework is a software development platform by Microsoft that supports multiple programming languages and object-oriented programming concepts. It includes components like CLR, CTS, BCL, FCL, and MSIL, which facilitate application development and execution across various platforms. .NET Core, a modern, open-source, and cross-platform framework, allows for building high-performance applications and supports features like modularity and cloud integration.

Uploaded by

Harsh Nampurkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link].

(ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

UNIT-I Introduction to C#
*Introduction- The .NET Framework is a software development platform that was introduced
by Microsoft on 13th February 2002

.NET stands for Network Enabled Technology.

* Definition- Framework-Framework in a programming is a tool that provides readymade


components used to speed up S/W development.
-.NET Framework is a virtual machine for compiling and executing programs written in
different languages like C#, [Link], J#, F#,C++ etc.
-It is also used to create a form based, console-based, mobile and web-based application or
services that are available in Microsoft environment.
-Furthermore, the .NET framework is a pure object oriented, that is it support all OOP’s
Concepts.
- .NET framework supports more than 60 programming languages.

* .NET Framework Architecture-


The first three components from bottom are considered as the basic architecture of .NET
framework and after this more components were added by Microsoft in the .NET Framework,

Fig- .NET Framework Architecture-


Components of .NET Framework
1) CLR (Common Language Runtime)-
- CLR is heart and soul of .NET framework.
- Used to Execute programs which are written in different languages like C#, [Link], J#,
F#,C++ etc.

*CLR provides a number of services that includes:


1. Loading and executing of programs
2. Memory isolation for application
3. Memory management using automatic garbage collection
4. Providing metadata(basic information about data)

SANGOLA COLLEGE SANGOLA 1|Page


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

5. Verification of type safety


6. Security
7. Interoperability with other system
8. Compilation of IL into native executable code
9. Managing exception and errors
CTS (Common Type System)
CTS is built in CLR which provides Multiple Language Support.
It specifies a standard that represent what type of data and value can be defined and managed in
computer memory at runtime.
A CTS ensures that programming data defined in various languages should be interact with each
other to share information. For example, in C# we define data type as int, while in [Link] we
define integer as a data type hence it does not require any type conversion.
2) BCL (Base Class Library)

The base class library has a rich collection of libraries features and functions that help to
implement many programming languages in the .NET Framework, such as C #, F #, Visual C
++, and more. Furthermore, BCL divides into two parts:
1. User defined class library
 Assemblies –it is a File which is automatically generated by compiler upon
successful compilation.
 It is the collection of small parts of deployment an application's part.
 It contains either the .DLL (Dynamic Link Library) or .exe (Executable) file.
2. Predefined class library
 Namespace - It is the collection of predefined classes and methods that present
in .NET.
 In other languages such as, C we used header files, in java we used package
similarly we used "using system" in .NET, where using is a keyword and system is
a namespace.
FCL (Framework Class Library)-
 The Framework Class Library or FCL is a superset of BCL which 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.
3) CLS (Common Language Specification)-

CLS is a subset of CTS. It defines a set of rules and restrictions that every language must
follow which runs under the .NET framework. The languages which follow these set of rules
are said to be CLS Compliant.

In simple words, CLS enables cross-language integration or Interoperability.


Ex. if we talk about C# and [Link] then, in C# every statement must have to end with a
semicolon. It is also called a statement Terminator, but in [Link] each statement should not
end with a semicolon (;).

SANGOLA COLLEGE SANGOLA 2|Page


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

4)MSIL/CIL(MicrosoftIntermediateLanguage/Common Intermediate Language) –

The Microsoft Intermediate Language (MSIL), also known as the Common Intermediate
Language (CIL) is a set of instructions that are platform independent and are generated by the
language-specific compiler from the source code.

The MSIL is platform independent and consequently, it can be executed on any of the Common
Language Infrastructure supported environments such as the Windows .NET runtime.

The execution process that includes the creation of the MSIL and the conversion of the MSIL
into machine code by the JIT compiler is given as follows:

5) Garbage Collector
Garbage Collector is responsible for automatic memory management of objects.

Also, the responsibility of the garbage collector is removing the object from memory that has
no use.

Advantages of Garbage Collector


 Allows us to develop an application without having worry to free memory.

 Allocate main memory for object efficiently on the managed Heap.

 Provide security to main memory space by making sure that an


object cannot use the content of another object.

SANGOLA COLLEGE SANGOLA 3|Page


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

* .NET Core
 .NET Core, developed by Microsoft, is managed under the .NET Foundation, a non-
profit open source organization.

 .NET Core is written in C# and C++ and licensed under MIT (Massachusetts Institute
of Technology) license. The first version, .NET Core 1.0, was released in 2016 with
limited functionality.

 .NET Core is a free, open-source, modular, cross-platform framework for building


modern and high-performance applications.

 It is a reimplementation of the .NET Framework to be more lightweight, modular, and


flexible.

 .NET Core includes a runtime, a set of libraries, and a development environment that
supports multiple programming languages such as C#, Visual Basic, and F#.

 It is designed to run on various platforms, including Windows, macOS, and Linux.

 It can be used to build a wide range of applications, including web applications, desktop
applications, Mobile applications, Cloud applications, Gaming applications, Internet of
Things and micro services etc.

*Characteristics of .NET Core

Key characteristics of .NET Core include open source, cross-platform, modern, flexible,
lightweight, fast, friendly, shareable, and built for future software development.
1) Free and Open Source.
 The .NET Core platform is free and open source.
 .NET Core source code project is available on GitHub.
 Any developer can get involved in .NET Core development. Thousands of active
developers participating in .NET Core development are improving features, adding new
features, and fixing bugs and issues.
 .NET Core is free and licensed under MIT and Apache licenses.
2) Cross-Platform.
 .NET Core supports and runs on Windows, macOS, and Linux operating systems.
 .NET Core is consistent across architecture, including x64, x86, and ARM.
 The same assemblies and libraries can be imported and used on multiple platforms.
 The assemblies and libraries are built using one of the .NET languages, C#, [Link], or
F#.
3) Sharable.
 .NET Core uses one consistent API model written in .NET Standard that is common to
all .NET applications.
 The same API or library can be used with multiple platforms in multiple languages.

SANGOLA COLLEGE SANGOLA 4|Page


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

4) Modern.
 Unlike some older frameworks, .NET Core is designed to solve today's modern needs,
including being mobile friendly, build once run everywhere, scalable, and high
performance.
 .NET Core is designed to build applications that target all kinds of devices, including
IoTs and gaming consoles.
 .NET Core supports modern language constructs with the help of C# version 8, like
object-oriented and modular programming, generics, collections, lambdas, Language
Integrated Query (LINQ), and asynchronous programming, which makes developers
productive.

5) Fast.
 .NET Core 3.0 is fast. Compared to the .NET Framework.
 .NET Core is much quicker than other server-side frameworks such as Java Servlet and
[Link].

According to a report published by TechEmpowers, .NET Core is much faster than any other framework.
TechEmpower benchmark compares Web application frameworks for tasks such as database access for a single
query, multiple queries, fortunes, data updates, plaintext, and JSON serialization.
6) Lightweight.
 .NET Core is lightweight.
 .NET Core can be included in your app or installed on a server side-by-side user,
machine-wide, or. In addition, the .NET Core can be deployed in Docker containers.
7) .NET Core is Friendly.
 .NET Core is compatible with .NET Framework, Xamarin, and Mono, via .NET
Standard.
 .NET Core also supports working with various popular Web frameworks and libraries
such as React, Angular, and JavaScript.
 TypeScript is one of the key components of the .NET Core and Visual Studio ecosystem.
*C# Basics-
Introduction-
 C# is a Pure Object Oriented Programming Language under .NET Framework developed
by Microsoft.
 C# is designed and developed by Anders Hejlsberg & his team members at Microsoft.

C# Variables-
Definition - A Variable is an identifier that denotes a storage location used to store data value.
OR
Variables are containers used to store data values.
A variable may take different values at different time during the execution of program.

SANGOLA COLLEGE SANGOLA 5|Page


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

Variable naming conventions-


1. Variable name may consist of alphabet, digit and underscore
2. They must not begin with digit.
3. Uppercase and Lowercase are different/distinct i.e. the variable SUM is not same as Sum
or sum.
4. It should not be Keyword.
5. White spaces is not allowed.
Variable Declaration Syntax-
<data type> <variable list>;
Here, data type must be a valid C# data type including char, int, float, double, or any user-defined
data type, and variable list may consist of one or more identifier names separated by commas.
Some valid variable definitions are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
Initializing Variables
Variables are initialized (assigned a value) with an equal sign followed by a constant expression.
The general form of initialization is −
<variable_name> = value;
Variables can be initialized in their declaration. The initializer consists of an equal sign followed
by a constant expression as −
<data_type> <variable_name> = value;
Some examples are −
int d = 3, f = 5; /* initializing d and f. */
byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */
Accepting Values from User
The Console class in the System namespace provides a function ReadLine() for accepting input
from the user and store it into a variable.
For example,
String name=[Link]();
int num;
num = Convert.ToInt32([Link]());
OR
num=[Link] ([Link]());

Note-The function Convert.ToInt32()/ [Link] converts the data entered by the user to int
data type, because [Link]() accepts the data in string format.

C# Data Types-
Data type specify the size and type of values that can be stored.

Every variable in C# is associated with a data type.

SANGOLA COLLEGE SANGOLA 6|Page


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

C# having rich set of data types.

Characters Arrays, Delegates

Value Types:
In C#, Value Types are stored on the Stack and having Fixed Length.
When a value of variable is assigned to another variable, the value is actually copied. It means
that two identical copies of the value are available in memory.

Reference Types:
In C#, Reference Types are stored on the Heap and having variable (Not Fixed) Length.
When a value of reference variable is assigned to another reference variable, the reference
(address) is actually copied. It means that both variables are refers to same memory location.

*Nullable types-
In C#, the compiler does not allow you to assign a null value to a variable. So, C# 2.0 provides a
special feature to assign a null value to a variable that is known as the Nullable type.

The Nullable type allows you to assign a null value to a variable.

The concept of Nullable type is useful when we deal with databases that contain elements that may
not be assigned a value.
C# provides two different ways to create Nullable types.
1. By creating [Link] instance,
2. By using ? operator
1. By creating [Link] instance
Syntax:
Nullable<data_type> variable_name = null;
Example
internal class Program
{
static void Main(string[] args)
{
Nullable<int> a= 10;
[Link]("Value in a="+a);
a = null;
[Link]("Value in a=" + a);

SANGOLA COLLEGE SANGOLA 7|Page


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

[Link]();

}
}
2. By using ? operator
Syntax:
datatype? variable_name = null;
Example
static void Main(string[] args)
{
int? a = 10;
[Link]("Value in a="+a);
a = null;
[Link]("Value in a=" + a);
[Link]();
}

Note- A Nullable Type is incompatible with a General Data Type. This means we cannot
operate between a nullable type and a general datatype.

For example
int? x = 4;
int y = 3;
int z = x * y;
[Link]([Link]());
[Link]();

Here x is nullable while y is not nullable. So The above Program will generate the following
compile time Error:
Error 1 Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you
missing a cast?)

*Null Coalescing Operator-

The ?? operator is also known as the null-coalescing operator.

null-coalescing Operator returns the left side operand if the operand is not null else if left side
operand is NULL then it returns the right side operand.

Example-
static void Main(string[] args)
{
int? left = null;//NULL
int right = 20;

int? result = left ?? right;


[Link]("Result="+result);
[Link]();

SANGOLA COLLEGE SANGOLA 8|Page


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

}
Output-
Result=20
Example:2-
static void Main(string[] args)
{
int? left = 10;//NOT NULL
int right = 20;

int? result = left ?? right;


[Link]("Result="+result);
[Link]();

}
Output-
Result=10

Advantages/Usage of the Null-Coalescing Operator (??) operator.


 It is used to define a default value for a nullable item (for both value types and
reference types).
 It prevents the runtime InvalidOperationException exception.
 It helps us to remove many redundant "if-else" conditions.
 It works for both reference types and value types.
 The code becomes well-organized and readable.

*Elvis Operator (?.) (Null Conditional Operator )-

The null conditional operator (?.), often referred to as the "Elvis operator", allows you to
perform member access or method calls on an object only if that object is not null.

If the object is null, the operation returns null instead of throwing a null reference exception.

This operator is a game-changer for developers, as it significantly reduces the amount of code
needed to safely access members of potentially null objects.
Example-
class Employee
{
private string empname;

public Employee(string nm) { empname = nm; }

public string GetName()


{ return empname;
}

internal class Program


{
static void Main(string[] args)
{
Employee emp = new Employee("ABC");

SANGOLA COLLEGE SANGOLA 9|Page


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

[Link](emp?.GetName());

Employee emp2 = null;


[Link](emp2?. GetName());
[Link]();

}
}

*Boxing and UnBoxing-


Boxing is the process of converting a value type on stack in to the object type on heap.
Boxing is implicit.

A boxing conversion makes a copy of the value. So, changing the value of one variable will not
impact others.
Example: Boxing
int i = 10;
object ob = i; //performs boxing
In the above example, the integer variable that is "i" is assigned to the object "ob". Thus the
object data type is a reference type and base class of all the other classes in C# ultimately, an
integer can be assigned to an object type. And this process of converting from the integer to the
object data type is called boxing.
Unboxing is the reverse of boxing. It is the process of converting a reference type to value
type.
Unboxing extract the value from the reference type and assign it to a value type.
Unboxing is explicit. It means we have to cast explicitly.
Example: Unboxing
int i = 10;
object ob = i; //performs boxing
object ob = 10;
int i = (int)ob; //performs unboxing

Boxing Unboxing

It convert value type into an object type. It convert an object type into value type.

Boxing is an implicit conversion process. Unboxing is the explicit conversion process.

Here, the value stored on the stack copied to Here, the object stored on the heap memory
the object stored on the heap memory. copied to the value stored on the stack .

C# Keywords-
Keywords are predefined sets of reserved words that have special meaning in a program.

SANGOLA COLLEGE SANGOLA 10 | P a g e


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

The meaning of keywords cannot be changed, neither can they be directly used as identifiers in a
program.

C# has a total of 79 keywords. All these keywords are in lowercase. Here is a complete list of all
C# keywords.
abstract as base bool
break byte case catch
char checked class const
continue decimal default delegate
do double else enum
event explicit extern false
finally fixed float for
foreach goto if implicit
in in (generic modifier) int interface
internal is lock long
namespace new null object
operator out out (generic modifier) override
params private protected public
readonly ref return sbyte
sealed short sizeof stackalloc
static string struct switch
this throw true try
typeof uint ulong unchecked
unsafe ushort using using static
void volatile while
Note-
Although keywords are reserved words, they can be used as identifiers if @ is added as prefix.
For example,
int @void;
The above statement will create a variable @void of type int.

*Type Inference-
Type inference refers to the automatic detection of the data type of an expression in a formal
language.

var keyword is used in C# to implement Type Inference.

C# is a strongly typed language, and its default type declaration is explicit. This means we have to
specify a type for a new variable or the compiler will throw an error. With version 3 of C#, a new
keyword, var, was introduced that allows developers to store any type of value in an implicit way.
This means that the compiler decides during compile time, when the first assignment happens,
what the type will be for that variable. This can be easily integrated with LINQ.

Syntax - var variablename = value;

SANGOLA COLLEGE SANGOLA 11 | P a g e


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

internal class Program


{
static void Main(string[] args)
{
var nm='A';
var a = 10;
var name = "XYZ";
[Link](nm);
[Link](a);
[Link](name);

[Link](“DataType of nm=”+[Link]());
[Link](“DataType of a=”+[Link]());
[Link](“DataType of name=”+[Link]());

[Link]();
}
}

*Console Input Output-


The Console class from the System namespace helps you with system I/O to the command
prompt window or console.
C# Output
In order to output something in C#, we can use
[Link]()
OR
[Link]()
Here, System is a namespace, Console is a class within
namespace System and WriteLine and Write are methods of class Console.

Difference between WriteLine() and Write() method


The main difference between WriteLine() and Write() is that the Write() method only prints
the string provided to it, while the WriteLine() method prints the string and moves to the start
of next line as well.
Ex.
class Test
{
public static void Main(string[] args)
{
[Link]("Prints on ");
[Link]("New line");

[Link]("Prints on ");
[Link]("Same line");
}
}
}
When we run the program, the output will be
Prints on
New line
Prints on Same line

SANGOLA COLLEGE SANGOLA 12 | P a g e


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

Combining (Concatenating) two strings using + operator and printing them


Strings can be combined/concatenated using the + operator while printing.
class Test
{ public static void Main(string[] args)
{
int val = 55;
[Link]("Hello " + "World");
[Link]("Value = " + val);
}
}
}
When we run the program, the output will be
Hello World
Value = 55

Printing concatenated string using Formatted String [Better Alternative]


A better alternative for printing concatenated string is using formatted string. Formatted
string allows programmer to use placeholders for variables.
For example,
The following line,
[Link]("Value = " + val);
can be replaced by,
[Link]("Value = {0}", val);
{0} is the placeholder for variable val which will be replaced by value of val. Since only one
variable is used so there is only one placeholder.
Multiple variables can be used in the formatted string. We will see that in the example below.

namespace Sample
{
class Test
{
public static void Main(string[] args)
{
int firstNumber = 5, secondNumber = 10, result;
result = firstNumber + secondNumber;
[Link]("{0} + {1} = {2}", firstNumber, secondNumber, result);
}
}
}
When we run the program, the output will be
5 + 10 = 15
Here, {0} is replaced by firstNumber, {1} is replaced by secondNumber and {2} is replaced
by result. This approach of printing output is more readable and less error prone than
using + operator.

SANGOLA COLLEGE SANGOLA 13 | P a g e


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

C# Input
In C#, the simplest method to get input from the user is by using the ReadLine() method of
the Console class.
However, Read() and ReadKey() are also available for getting input from the user.
They are also included in Console class.

The difference between ReadLine(), Read() and ReadKey() method is:


 ReadLine(): The ReadLine() method reads the next line of input from the standard
input stream. It returns the same string.

 Read(): The Read() method reads the next character from the standard input stream. It
returns the ascii value of the character.

 ReadKey(): The ReadKey() method obtains the next key pressed by user.
This method is usually used to hold the screen until user press a key.

*C# Operators-
Operators in C# are symbols that are used to perform operations on operands.
For example, consider the expression 2 + 3 = 5, here 2 and 3 are operands and + and = are
called operators. So, the Operators in C# are used to manipulate the variables and values in a
program.
Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operator
6. Special Operator
In C#, the Operators can also be categorized based on the Number of Operands:
1. Unary Operator: The Operator that requires one operand (variable or value) to perform
the operation is called Unary Operator.(Ex. i++,-9)
2. Binary Operator: Then Operator that requires two operands (variables or values) to
perform the operation is called Binary Operator. (Ex. a+b)
3. Ternary Operator: The Operator that requires three operands (variables or values) to
perform the operation is called Ternary Operator. Ternary Operator is also called
Conditional Operator.( Ex. a>b?a:b)

For a better understanding of the different types of operators supported in C# Programming


Language, please have a look at the below image.

SANGOLA COLLEGE SANGOLA 14 | P a g e


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

1. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations such as addition,
subtraction, multiplication, division, etc.
C# Arithmetic Operators

Operator Operator Name Example

+ Addition Operator 6 + 3 evaluates to 9

- Subtraction Operator 10 - 6 evaluates to 4

* Multiplication Operator 4 * 2 evaluates to 8

/ Division Operator 10 / 5 evaluates to 2

% Modulo Operator (Remainder) 16 % 3 evaluates to 1

2. Relational Operators
Relational operators are used to check the relationship between two operands. If the
relationship is true the result will be true, otherwise it will result in false.
Relational operators are used in decision making and loops.
C# Relational Operators

Operator Operator Name Example

== Equal to 6 == 4 evaluates to false

> Greater than 3 > -1 evaluates to true

SANGOLA COLLEGE SANGOLA 15 | P a g e


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

C# Relational Operators

Operator Operator Name Example

< Less than 5 < 3 evaluates to false

>= Greater than or equal to 4 >= 4 evaluates to true

<= Less than or equal to 5 <= 3 evaluates to false

!= Not equal to 10 = 2 evaluates to true

3. Logical Operators

Logical operators are used to determine the logic between variables or values:
Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

4. Assignment Operators
There are following assignment operators supported by C# −
Operator Description Example

= Simple assignment operator, Assigns values from right side operands to C=A+B
left side operand assigns value
of A + B into
C

+= Add AND assignment operator, It adds right operand to the left operand C += A is
and assign the result to left operand equivalent to
C=C+A

SANGOLA COLLEGE SANGOLA 16 | P a g e


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

-= Subtract AND assignment operator, It subtracts right operand from the left C -= A is
operand and assign the result to left operand equivalent to
C=C-A

*= Multiply AND assignment operator, It multiplies right operand with the C *= A is


left operand and assign the result to left operand equivalent to
C=C*A

/= Divide AND assignment operator, It divides left operand with the right C /= A is
operand and assign the result to left operand equivalent to
C=C/A

[Link] OR Ternary Operator


The Conditional or ternary operator (? :) operates on three operands. It is a shorthand for if-
then-else statement.

Syntax- variable = Condition? Expression1: Expression2;


The ternary operator works as follows:
 If the expression stated by Condition is true, the result of Expression1 is assigned to
variable.
 If it is false, the result of Expression2 is assigned to variable.

class TernaryOperator
{
public static void Main(string[] args)
{
int number = 10;
string result;
result = (number % 2 == 0)? "Even Number" : "Odd Number";
[Link](number + “is” +result);
}
}

When we run the program, the output will be:

10 is Even Number

SANGOLA COLLEGE SANGOLA 17 | P a g e


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

[Link] Operator-
Special operators are operators which are used to perform specific task.

*C# Operator Precedence


 Operator precedence is a set of rules which defines how an expression is evaluated.
 In C#, each C# operator has an assigned priority and based on these priorities, the
expression is evaluated.
 For example, the precedence of multiplication (*) operator is higher than the precedence
of addition (+) operator. Therefore, operation involving multiplication is carried out
before addition.
Take a look at the statement below.
int x=4+3*5;
 What will be the value of x after executing this statement?
 The operand 3 is associated with + and *. As stated earlier, multiplication has a higher
precedence than addition. So, the operation 3 * 5 is carried out instead of 4 + 3. The
value of variable x will be 19.
 If addition would have a higher precedence, 4 + 3 would be evaluated first and the value
of x would be 35.
Operator Precedence Table
The higher the precedence of operator is, the higher it appears in the table
Category Operators

Postfix Increment and Decrement ++, --

Prefix Increment, Decrement and Unary ++, --, +, -, !, ~

Multiplicative *, /, %

Additive +, -

SANGOLA COLLEGE SANGOLA 18 | P a g e


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

Category Operators

Shift <<, >>

Relational <, <=, >, >=

Equality ==, !=

Bitwise AND &

Bitwise XOR ^

Bitwise OR |

Logical AND &&

Logical OR ||

Ternary ?:

Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

The assignment operators have the lowest precedence while the postfix increment and
decrement operators have the highest precedence.

*Type Conversion-

Type conversion is converting one type of data to another type.

It is also known as Type Casting.

In C#, type casting has two forms −


Implicit type conversion − In implicit type conversion, the C# compiler automatically
converts one type to another.

Generally, smaller types like int (having less memory size) are automatically converted to
larger types like double (having larger memory size) and conversions from derived classes to
base classes.

Example-
static void Main(string[] args)
{
int num = 10;
double db;
db = num; //Implicit Type Conversion.

SANGOLA COLLEGE SANGOLA 19 | P a g e


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

[Link](db);
[Link]();
}

Explicit type conversion – In explicit type conversion, we explicitly convert one type to
another.
Generally, larger types like double (having large memory size) are converted to smaller types
like int (having small memory size).

These conversions are done explicitly by users using the pre-defined functions. Explicit
conversions require a cast operator.
Example-
static void Main(string[] args)
{
int num = 10;
double db;
db = num;
int tr = (int)db;//Explicit Type Conversion
[Link](tr);
[Link]();
}
}

*C# Decision Making and Branching-


1) if Statement

The C# if statement tests the condition. It is executed if condition is true.


Syntax:
If (condition)
{
//code to be executed
}
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 10;
if (num % 2 == 0)
{
[Link]("It is even number");
}

}
}
Output:47
It is even number

SANGOLA COLLEGE SANGOLA 20 |


Page
[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

2) if-else Statement

The C# if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax: if(condition) {
//code if condition is true
}
else {
//code if condition is false
}
using System;
public class IfExample
{ public static void Main(string[] args)
{ int num = 11;
if (num % 2 == 0)
{
[Link]("It is even number");
}
else
{
[Link]("It is odd number");
}

}
Output-
It is odd number

3) Nested if...else Statement


An if...else statement can exist within another if...else statement. Such statements are called
nested if...else statement.
Syntax:
if (boolean-expression)
{
if (nested-expression-1)
{
// code to be executed
}
else
{
// code to be executed
}
}
else
{
if (nested-expression-2)
{
// code to be executed
}
else

SANGOLA COLLEGE SANGOLA 21 | P a g e


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

{
// code to be executed
}
}
Ex.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x = 5, y = 20;
if (x > y)
{
if (x >= 10)
{
[Link]("x value greater than or equal to 10");
}
else
{
[Link]("x value less than 10");
}
}
else
{
if (y <= 20)
{
[Link]("y value less than or equal to 20");
}
else
{
[Link]("y value greater than 20");
}
}
[Link]("Press Enter Key to Exit..");
[Link]();
}
}
}

4) If – else – if ladder Statement


The if-else-if ladder statement executes one condition from multiple statements.
The execution starts from top and checked for each if condition.
The statement of if block will be executed which evaluates to be true. If none of the if condition
evaluates to be true then the last else block is evaluated.
Syntax-
if(condition 1)
{
// code to be executed if condition1 is true
}
else if(condition 2)

SANGOLA COLLEGE SANGOLA 22 |


Page
[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

{
// code to be executed if condition2 is true
}
else if(condition n)
{
// code to be executed if condition3 is true
}
...
else
{
// code to be executed if all the conditions are false
}
class Program {
public static void Main(String[] args)
{ int i = 20;
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

5) Switch Case-
Switch statement is an alternative to long if-else-if ladders.
The expression is checked for different cases and the one match is executed.
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 value N : // statement sequence
break;
default: // default statement sequence

SANGOLA COLLEGE SANGOLA 23 |


Page
[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

namespace Conditional
{
class SwitchCase
{
public static void Main(string[] args)
{
char ch;
[Link]("Enter an alphabet");
ch = [Link]([Link]());
switch([Link](ch))
{
case 'a':
[Link]("Vowel");
break;
case 'e':
[Link]("Vowel");
break;
case 'i':
[Link]("Vowel");
break;
case 'o':
[Link]("Vowel");
break;
case 'u':
[Link]("Vowel");
break;
default:
[Link]("Not a vowel");
break;
}
}
}
}
Output- Enter an alphabet
X
Not a vowel

C# Decision Making and Looping-

Loops are used to execute one or more statements multiple times until a specified condition is
fulfilled.

There are many loops in C# such as for loop, while loop, do while loop etc. Details about these
are given as follows:

[Link] loop

The while loop continuously executes loop body until loop condition is TRUE.

While loop is Entry Controlled Loop

SANGOLA COLLEGE SANGOLA 24 |


Page
[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

If the loop condition is true, the body of the loop is executed. Otherwise, the control flow jumps
to the next statement after the while loop.

The while loop may never run if the condition is false the first time it is tested. The control skips
the loop and goes directly to the next statement.
The syntax of the while loop is given as follows:
while (condition)
{
// These statements will be executed if the condition evaluates to true
}
using System;
namespace LoopDemo
{
class Example {
static void Main(string[] args) {
int i = 1;
[Link]("First 10 Natural Numbers are: ");
while (i <= 10)
{
[Link]( i );
i++;
}
}
}
}

The output of the above program is as follows:


First 10 Natural Numbers are:
1
2
3
4
5
6
7
8
9
10

2. do-while loop

Exit Controlled Loop

The do while loop executes one or more statements multiple times as long as the loop
condition is satisfied.

It is similar to the while loop but the while loop has the test condition at the start of the loop and
the do while loop has the test condition at the end of the loop. So it executes at least once
always.
The syntax of the do while loop is given as follows:
do

SANGOLA COLLEGE SANGOLA 25 |


Page
[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

{
// These statements will be executed if the condition evaluates to true
}while (condition);
using System;
namespace LoopDemo
{
class Example {
static void Main(string[] args) {
int i = 1;
[Link]("First 10 Natural Numbers are: ");
do
{
[Link]( i );
i++;
} while (i <= 10);
}
}
}
The output of the above program is as follows:
First 10 Natural Numbers are:
1
2
3
4
5
6
7
8
9
10

3. for loop -The for loop executes one or more statements multiple times as long as the loop
condition is satisfied.

If the loop condition is true, the body of the for loop is executed. Otherwise, the control flow
jumps to the next statement after the for loop.

In For loop, first the initialization is done. This declares and initializes the loop variables, if there
are any. Then the condition is evaluated. If it is true, loop body is executed. If it is false, the
control passes to the next statement after the for loop body. After the loop body is executed, the
loop variables are updated. Then the condition is checked again and the cycle continues.
The syntax of the for loop is given below:
for ( initialization, condition, increment )
{
// These statements will be executed if the condition evaluates to true
}

namespace LoopDemo
{

SANGOLA COLLEGE SANGOLA 26 |


Page
[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

class Example {
static void Main(string[] args) {
[Link]("First 5 Natural Numbers are: ");
for (int i = 1; i <= 5; i++)
[Link](i);
}
}
}
The output of the above program is as follows:
First 10 Natural Numbers are:
1
2
3
4
5

4. Nested loops
Nested loops are loop where one loop is written inside another.
Nested loops can be created from for loops, while loops and do while loops.
The syntax of nested loops is given as follows:
Outer loop
{
// Statements in the outer loop
Inner Loop
{
// Statements in the inner loop
}
// Statements in the outer loop
}

class Example {
static void Main(string[] args) {
[Link]("Nested for loop");
for( int i = 0; i < 5; i++)
{
for(int j=0; j<=i; j++)
{ [Link](" *");
}
[Link]();
}
}
}
}
The output of the above program is as follows:
Nested for loop
*
**
***
****
*****

SANGOLA COLLEGE SANGOLA 27 |


Page
[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

5. foreach loop
The foreach loop executes one or more statements for all the elements in an Array/Collection
such as List, Hash Table etc.
Syntax
foreach(datatype loopvariable in array,collectionname)
{
//body
}
namespace LoopDemo
{
class Example {
static void Main(string[] args) {
[Link]("First 10 Natural Numbers are: ");
int[] naturalNos = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (int i in naturalNos)
{
[Link](i);
}
}
}
}
The output of the above program is as follows:
First 10 Natural Numbers are:
1
2
3
4
5
6
7
8
9
10

*Complex data types-

1)Arrays

Array is a collection of data elements of the same type.

These data elements are stored in contiguous memory locations. Some of the arrays in C# are 1-
D arrays, 2-D arrays etc. Details about these are given as follows:
1-D Arrays
One dimensional arrays consist of a single row with as many elements as required.
These arrays can be declared using the following syntax:
data_type[ ] name_of_array;
In the above syntax, data_type is the data type of array elements and name_of_array is the name
given to the array.
The syntax to create the array is given as follows:
data_type[ ] name_of_array = new data_type[array_size];

SANGOLA COLLEGE SANGOLA 28 |


Page
[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

In the above syntax, data_type is the data type of array elements, name_of_array is the name
given to the array, new is a keyword that creates an instance of the array and array_size is the
size of the array.
There are many methods to assign values to the array. Some of these are given as follows:
int[ ] arr = { 1, 2, 3, 4, 5};
int[ ] arr = new int[] { 1, 2, 3, 4, 5};
int[ ] arr = new int[5] { 1, 2, 3, 4, 5};
namespace ArrayDemo
{
class Example
{
static void Main(string[ ] args)
{
int [ ] arr = new int[5] {1, 2, 3, 4, 5};
int i;
[Link]("Elements in the array are:");
for ( i = 0; i < 5; i++ )
{
[Link](arr[i]);
}
}
}
}
The output of the above program is as follows:
Elements in the array are:
1
2
3
4
5

2-D Arrays
Two dimensional arrays contain multiple rows and columns.
Each element of the 2-D array is identified as arr[i,j] where i and j are the subscripts for row
and column index respectively and the name of the array is arr.
The 2-D arrays can be declared using the following syntax:
data_type[ , ] name_of_array = new data_type[row_size, column_size];
In the above syntax, data_type is the data type of array elements, name_of_array is the name
given to the array, new is a keyword that creates an instance of the array,row_size is the number
of rows and column_size is the number of columns.
One of the methods to assign values in a 2-D array is given as follows:
int[ , ] arr = new int [2,2] { {1,4} , {8,3} };
class Example
{
static void Main(string[] args)
{
int[,] arr = new int[2, 3] { {4,1,7}, {3, 8, 2} };
int i, j;
[Link]("The elements in the 2-D array are:");
for (i = 0; i < 2; i++)
{

SANGOLA COLLEGE SANGOLA 29 |


Page
[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

for (j = 0; j < 3; j++)


{
[Link]( “ “+arr[i,j]);
}
[Link]();
}
}
}
The output of the above program is as follows:
The elements in the 2-D array are:
417
382

Array Class
The Array class is defined in the System namespace.

Using Array class, you can easily work with arrays. It is the base class for all the arrays in C#.’

Most Common Properties in Array Class


Property Description

IsFixedSize This property gets a value indicating whether the Array has a fixed size.

IsReadOnly This property gets a value indicating whether the Array is read-only.
Length This property gets the total number of elements in all the dimensions of the Array.
Rank This property gets the rank (number of dimensions) of the Array. For example, a one-dimensional
array returns 1, a two-dimensional array returns 2, and so on.

Most Common Methods in Array Class


Methods Description
Clear(Array, Int32, Int32) This method sets a range of elements in an array to the default value
of each element type.

Clone() This method creates a shallow copy of the Array.


Copy(Array, Array, Int32)
This method copies a range of elements from an Array starting at the
first element and pastes them into another Array starting at the first
element. The length is specified as a 32-bit integer.

This method gets a 32-bit integer that represents the number of


GetLength(Int32)
elements in the specified dimension of the Array.

SANGOLA COLLEGE SANGOLA 30 |


Page
[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

Methods Description
GetValue(Int32)
This method gets the value at the specified position in the one-
dimensional Array. The index is specified as a 32-bit integer.

IndexOf(Array, Object)
This method searches for the specified object and returns the index
of its first occurrence in a one-dimensional array.

Reverse(Array) This method reverses the sequence of the elements in the entire one-
dimensional Array.
SetValue(Object, Int32)
This method sets a value to the element at the specified position in the
one-dimensional Array. The index is specified as a 32-bit integer.

Sort(Array)
This method sorts the elements in an entire one-dimensional Array
using the IComparableimplementation of each element of the Array.

ToString()
This method returns a string that represents the current object.

Examples On Array Class Methods Sort(),Reverse()-

1. Sort one dimensional array in descending order using Array Class method
using System;
namespace Demo
{
public class MyApplication
{
public static void Main(string[] args)
{
int [] arr = {34, 76, 1, 99, 68};
[Link]("The original unsorted array is: ");
foreach (int i in arr)
{
[Link](i + " ");
}
[Link](arr);
[Link](arr);
[Link]();
[Link]("The sorted array is: ");
for(int i=0; i<[Link]; i++)
{
[Link](arr[i] + " ");
}
}

SANGOLA COLLEGE SANGOLA 31 | P a g e


[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

}
}
The output of the above program is as follows:
The original unsorted array is: 34 76 1 99 68
The sorted array is: 99 76 68 34 1

2.A program that demonstrates the copy(, ,) method of array class is given as follows:
using System;
class Example
{
static void Main()
{
int[] arr1 = new int[5] { 45, 12, 9, 77, 34};
int[] arr2 = new int[5];
[Link](arr1, arr2, 5);
[Link]("arr1: ");
foreach (int i in arr1)
{
[Link](i + " ");
}
[Link]();
[Link]("arr2: ");
foreach (int i in arr2)
{
[Link](i + " ");
}
}
}

The output of the above program is as follows:


arr1:
45 12 9 77 34
arr2:
45 12 9 77 34

2)Enumeration –
Enumeration (or enum) is a value data type in C#.

It is mainly used to assign the names or string values to Numbers , that make a program easy
to read and maintain.
The main objective of enum is to define our own data types (Enumerated Data Types).

Enumeration is declared using enum keyword directly inside a namespace, class, or structure.

Syntax:
enum Enum_name { string_1...; string_2...; . . }

Example : Consider the below code for the enum. Here enum with name month is created and
its data members are the name of months like jan, feb, mar, apr, may. Now let’s try to print the
default integer values of these enums. An explicit cast is required to convert from enum type to
an integral type.

SANGOLA COLLEGE SANGOLA 32 |


Page
[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

using System;
namespace ConsoleApplication1 {

// making an enumerator 'month'


enum month
{

// following are the data members


jan,
feb,
mar,
apr,
may

class Program {

// Main Method
static void Main(string[] args)
{

// getting the integer values of data members..


[Link]("The value of jan in month " +
"enum is " + (int)[Link]);
[Link]("The value of feb in month " +
"enum is " + (int)[Link]);
[Link]("The value of mar in month " +
"enum is " + (int)[Link]);
[Link]("The value of apr in month " +
"enum is " + (int)[Link]);
[Link]("The value of may in month " +
"enum is " + (int)[Link]);
}
}
}

Output-
The value of jan in month enum is 0
The value of feb in month enum is 1
The value of mar in month enum is 2
The value of apr in month enum is 3
The value of may in month enum is 4

SANGOLA COLLEGE SANGOLA 33 |


Page
[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

3)Tuples-
A tuple in C# allows us to store elements of different data types.

Tuples allow us to,


 Create, access, and manipulate a data set
 Return a data set from a method without using the out parameter
 Pass multiple values to a method through a single parameter
1. Tuple Using Parentheses
 We can create a tuple by directly assigning different values using parentheses ().
 For example,
static void Main(string[] args)
{
var emp = (101, "ABC”,5000,4,5,6,7,8,9,1,2,3,54,"asd",'w',12.5F,252.21);//Method-1

[Link](emp.Item1);//Display Item Number 1 i.e 101


[Link](emp.Item2); //Display Item Number 2 i.e ABC
[Link](emp.Item3);//Display Item Number 3 i.e 5000
[Link](emp.Item10);//Display Item Number 10 i.e
[Link](emp);//Displays all Items from emp
emp.Item3 = 1111;//Changing item from Tuple
[Link](emp);//Displays all Items from emp after changing item
}

2. Tuple using Create() Method


In C# we can also use the Create() method to create a tuple without having to mention the
datatypes of the tuple elements.
The syntax for creating tuple using Create() is:

var t1 = [Link](value);

To understand it clearly, let's see an example:


static void Main(string[] args)
{
var stud = [Link](111, "XYZ", 123456789);//Method-2
[Link](stud.Item1);
[Link](stud.Item2);
[Link](stud.Item3);
}
Nested Tuple
We can create a tuple inside another tuple. A tuple within a tuple is called a nested tuple. For
example,

class Program {
public static void Main() {
var myTuple= [Link]("Taylor", "Jack", [Link](7, 8, 9));
[Link]("The elements inside myTuple: " + myTuple);
[Link](“Nested Tuple Element=”myTuple.Item3.Item1);
}
}

SANGOLA COLLEGE SANGOLA 34 |


Page
[Link]. (ECS)-III Dot NET Core 2024-25 SHIVRATNA HONRAO

Output

The elements inside myTuple: (Taylor, Jack, (7, 8, 9))


Nested Tuple Element=7

Here, we have a tuple (7, 8, 9) inside the myTuple tuple. This is called a nested tuple.

Tuple as a Method Parameter


In C#, you are allowed to pass a tuple as a method parameter as shown in the below example

internal class Program


{

static void Main(string[] args)


{
var t = [Link](10, 20,"ABC");
PRINT(t);//Method call with actual parameter Tuple t
[Link]();
}
public static void PRINT(Tuple<int,int,string> tmp)

{
[Link](tmp.Item1+" "+tmp.Item2+" "+tmp.Item3);
}

Tuple as a Return Type


In C#, methods are allowed to use tuple as a return type. Or in other words a method can return
a tuple as shown in the below example:
internal class Program
{

static void Main(string[] args)


{
var t = MyTuple(); //Calling Method
[Link](t.Item1);
[Link](t.Item2);
[Link](t.Item3);
[Link]();
}
public static Tuple<int,int,string> MyTuple()

{
return [Link](10, 20, "XYZ");
}

SANGOLA COLLEGE SANGOLA 35 |


Page

You might also like