Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 371

What Does It Mean "To Program"?

Nowadays computers have become irreplaceable. We use them to solve complex problems at the
workplace, look for driving directions, have fun and communicate. They have countless
applications in the business world, the entertainment industry, telecommunications and finance.
It’s not an over-statement to say that computers build the neural system of our contemporary
society and it is difficult to imagine its existence without them.
Despite the fact that computers are so wide-spread, few people know how they really work. In
reality, it is not the computers, but the programs (the software), which run on them, that matter. It
is the software that makes computers valuable to the end-user, allowing for many different types
of services that change our lives.

The Essence of Programming


The essence of programming is to control the work of the computer on all levels. This is done
with the help of "orders" and "commands" from the programmer, also known as programming
instructions. To "program" means to organize the work of the computer through sequences of
instructions. These commands (instructions) are given in written form and are implicitly
followed by the computer (respectively by the operating system, the CPU and the peripheral
devices).

To “program” means writing sequences of instructions in order to organize the work of the
computer to perform something. These sequences of instructions are called “computer
programs” or “scripts”.
Before we learn how to write simple C# programs, let’s take a good look at the different stages
of software development, because programming, despite being the most important stage, is not
the only one.
Stages in Software Development
Writing software can be a very complex and time-consuming task, involving a whole team of
software engineers and other specialists. As a result, many methods and practices, which make
the life of programmers easier, have emerged. All they have in common is that the development
of each software product goes through several different stages:
- Gathering the requirements for the product and creating a task;

- Planning and preparing the architecture and design;

- Implementation (includes the writing of program code);

- Product trials (testing);

- Deployment and exploitation;

- Support.

Implementation, testing, deployment and support are mostly accomplished using programming.

C# Tutorials
C# is a simple & powerful object-oriented programming language
developed by Microsoft. C# can be used to create various types of
applications, such as web, windows, console applications, or other
types of applications using Visual studio.

These C# tutorials will help you learn the essentials of C#, from the
basic to advance level topics. These tutorials are broken down into
sections, where each section contains a number of related topics that
are packed with easy to understand explanations, real-world
examples, useful tips, informative notes and a "points to remember"
section.

These tutorials are designed for beginners and professionals who


want to learn C# step-by-step.

C# Version History
C# was first introduced with .NET Framework 1.0 in the year 2002
and evolved much since then. The following table lists important
features introduced in each version of C#:

Version .NET Framework Visual Studio Important Features

C# 1.0 .NET Framework 1.0/1.1 Visual Studio .NET 2002  Basic features
Version .NET Framework Visual Studio Important Features

C# 2.0 .NET Framework 2.0 Visual Studio 2005  Generics


 Partial types
 Anonymous methods
 Iterators
 Nullable types
 Private setters (properties)
 Method group conversions (delegates)
 Covariance and Contra-variance
 Static classes

C# 3.0 .NET Framework 3.0\3.5 Visual Studio 2008  Implicitly typed local variables
 Object and collection initializers
 Auto-Implemented properties
 Anonymous types
 Extension methods
 Query expressions
 Lambda expressions
 Expression trees
 Partial Methods

C# 4.0 .NET Framework 4.0 Visual Studio 2010  Dynamic binding (late binding)
 Named and optional arguments
 Generic co- and contravariance
 Embedded interop types

C# 5.0 .NET Framework 4.5 Visual Studio 2012/2013  Async features


 Caller information

C# 6.0 .NET Framework 4.6 Visual Studio 2013/2015  Expression Bodied Methods
 Auto-property initializer
 nameof Expression
 Primary constructor
 Await in catch block
 Exception Filter
 String Interpolation

C# 7.0 .NET Core 2.0 Visual Studio 2017  out variables


 Tuples
 Discards
 Pattern Matching
 Local functions
 Generalized async return types
 more..

C# 8.0 .NET Core 3.0 Visual Studio 2019  Readonly members


 Default interface methods
Version .NET Framework Visual Studio Important Features

 Using declarations
 Static local functions
 Disposable ref structs
 Nullable reference types
 more..

The C# Language and the .NET Platform


The first version of C# was developed by Microsoft between 1999 and 2002 and was officially
released to the public in 2002 as a part of the .NET platform. The .NET platform aims to make
software development for Windows easier by providing a new quality approach to programming,
based on the concepts of the "virtual machine" and "managed code". At that time the Java
language and platform reaped an enormous success in all fields of software development; C# and
.NET were Microsoft’s natural response to the Java technology.
The C# Language
C# is a modern, general-purpose, object-oriented, high-level prog-ramming language. Its
syntax is similar to that of C and C++ but many features of those languages are not supported in
C# in order to simplify the language, which makes programming easier.
The C# programs consist of one or several files with a .cs extension, which contain definitions
of classes and other types. These files are compiled by the C# compiler (csc) to executable code
and as a result assemblies are created, which are files with the same name but with a different
extension (.exe or .dll). For example, if we compile HelloCSharp.cs, we will get a file with the
name HelloCSharp.exe (some additional files will be created as well, but we will not discuss
them at the moment).
We can run the compiled code like any other program on our computer (by double clicking it). If
we try to execute the compiled C# code (for example HelloCSharp.exe) on a computer that does
not have the .NET Framework, we will receive an error message.

The main program elements in C# (which are defined and used with the help of keywords) are
classes, methods, operators, expressions, conditional statements, loops, data types,
exceptions and few others.

Automatic Memory Management


One of the biggest advantages of the .NET Framework is the built-in automatic memory
management. It protects the programmers from the complex task of manually allocating
memory for objects and then waiting for a suitable moment to release it. This significantly
increases the developer productivity and the quality of the programs written in C#.
In the .NET Framework, there is a special component of the CLR that looks after memory
management. It is called a "garbage collector" (automated memory cleaning system). The
garbage collector has the following main tasks: to check when the allocated memory for
variables is no longer in use, to release it and make it available for allocation of new objects.

In order to program in C#, we need two basic things – an installed .NET Framework and a text
editor. We need the text editor to write and edit the C# code and the .NET Framework to
compile and execute it.
.NET Framework
By default, the .NET Framework is installed along with Windows, but in old Windows versions
it could be missing. To install the .NET Framework, we must download it from Microsoft’s
website (http://download.microsoft.com). It is best if we download and install the latest version.

Text Editor
The text editor is used to write the source code of the program and to save it in a file. After that,
the code is compiled and executed. There are many text editing programs. We can use Windows’
built-in Notepad (it is very basic and inconvenient) or a better free text editor like Notepad++
(notepad-plus.sourceforge.net) or PSPad (www.pspad.com).

First C# Program
Here, you will learn to create a simple console application in C# and
understand the basic building blocks of a console application.

C# can be used in a window-based, web-based, or console


application. To start with, we will create a console application to work
with C#.

Open Visual Studio (2017 or later) installed on your local machine.


Click on File -> New Project... from the top menu, as shown below.
Create a New Project in Visual Studio 2017

From the New Project popup, shown below, select Visual C# in the
left side panel and select the Console App in the right-side panel.

Select Visual C# Console App Template


In the name section, give any appropriate project name, a location
where you want to create all the project files, and the name of the
project solution.

Click OK to create the console project. Program.cs will be created as


default a C# file in Visual Studio where you can write your C# code
in Program class, as shown below. (The .cs is a file extension for C#
file.)

C# Console Program

Every console application starts from the Main() method of


the Program class. The following example displays "Hello World!!" on
the console.

Example: C# Console Application


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

namespace CSharpTutorials
{
class Program
{
static void Main(string[] args)
{
string message = "Hello World!!";

Console.WriteLine(message);
}

The following image illustrates the important parts of the above


example.

C# Code Structure

Let's understand the above C# structure.

1. Every .NET application takes the reference of the necessary .NET framework
namespaces that it is planning to use with the using keyword, e.g., using
System.Text.
2. Declare the namespace for the current class using the namespace keyword,
e.g., namespace CSharpTutorials.FirstProgram
3. We then declared a class using the class keyword: class Program
4. The Main() is a method of Program class is the entry point of the console
application.
5. String is a data type.
6. A message is a variable that holds the value of a specified data type.
7. "Hello World!!" is the value of the message variable.
8. The Console.WriteLine() is a static method, which is used to display a text
on the console.

Note:
Every line or statement in C# must end with a semicolon (;).
C# Distinguishes between Uppercase and Lowercase!
The C# language distinguishes between uppercase and lowercase letters so we should use the
correct casing when we write C# code

Main Formatting Rules


If we want our code to be correctly formatted, we must follow several important rules regarding
indentation:
- Methods are indented inside the definition of the class (move to the right by one or more [Tab]
characters);
- Method contents are indented inside the definition of the method;
- The opening curly bracket { must be on its own line and placed exactly under the method or
class it refers to;
- The closing curly bracket } must be on its own line, placed exactly vertically under the
respective opening bracket (with the same indentation);
- All class names must start with a capital letter;
- Variable names must begin with a lower-case letter;
- Method names must start with a capital letter;

Code indentation follows a very simple rule: when some piece of code is logically inside
another piece of code, it is indented (moved) on the right with a single [Tab]. For example if a
method is defined inside a class, it is indented (moved to the right). In the same way if a method
body is inside a method, it is indented. To simplify this, we can assume that when we have the
character “{“, all the code after it until its closing “}” should be indented on the right.
File Names Correspond to Class Names
Every C# program consists of one or several class definitions. It is accepted that each class is
defined in a separate file with a name corresponding to the class name and a .cs extension. When
these requirements are not met, the program will still work but navigating the code

will be difficult

Compile and Run C# Program


To see the output of the above C# program, we have to compile it
and run it by pressing Ctrl + F5 or clicking the Run button or by
clicking the "Debug" menu and clicking "Start Without Debugging".
You will see the following output in the console:

Output:
Hello World!!

So, this is the basic code items that you will probably use in every
C# code.

C# Keywords
C# contains reserved words that have special meaning for the
compiler. These reserved words are called "keywords". Keywords
cannot be used as an identifier (name of a variable, class, interface,
etc.).

Keywords in C# are distributed under the following categories:

Modifier Keywords
Modifier keywords are specific keywords that indicate who can modify
types and type members. Modifiers allow or prevent certain parts of
programs from being modified by other parts.

Modifier keywords

abstract

async

const

event

extern

new

override

partial

readonly
Modifier keywords

sealed

static

unsafe

virtual

volatile

Access Modifier Keywords:


Access modifiers are applied to the declaration of the class, method,
properties, fields, and other members. They define the accessibility
of the class and its members.

Access Modifiers Usage

public The Public modifier allows any part of the program in the same assembly or another assembly to
access the type and its members.

private The Private modifier restricts other parts of the program from accessing the type and its members.
Only code in the same class or struct can access it.

internal The Internal modifier allows other program code in the same assembly to access the type or its
members. This is default access modifiers if no modifier is specified.

protected The Protected modifier allows codes in the same class or a class that derives from that class to access
the type or its members.

Statement Keywords
Statement keywords are related to program flow.

Statement Keywords

if

else

switch

case

do
for

foreach

in

while

break

continue

default

goto

return

yield

throw

try

catch

finally

checked

unchecked

fixed

lock

Method Parameter Keywords


These keywords are applied to the parameters of a method.

Method Parameter Keywords

params

ref

out
Namespace Keywords
These keywords are applied with namespace and related operators.

Namespace Keywords

using

. operator

:: operator

extern alias

Operator Keywords
Operator keywords perform miscellaneous actions.

Operator Keywords

as

await

is

new

sizeof

typeof

stackalloc

checked

unchecked

Access Keywords
Access keywords are used to access the containing class or the base
class of an object or class.
Access keywords

base

this

Literal Keywords
Literal keywords apply to the current instance or value of an object.

Literal Keywords

null

false

true

value

void

Type Keywords
Type keywords are used for data types.

Type keywords

bool

byte

char

class

decimal

double

enum

float

int

long
Type keywords

sbyte

short

string

struct

uint

ulong

ushort
ADVERTISEMENT

Contextual Keywords
Contextual keywords are considered as keywords, only if used in
specific contexts. They are not reserved and so can be used as
names or identifiers.

Contextual Keywords

add

var

dynamic

global

set

value

Contextual keywords are not converted into blue color (default color
for keywords in visual studio) when used as an identifier in Visual
Studio. For example, var in the below figure is not in blue, whereas
the color of this is the blue color. So var is a contextual keyword.
C# Keywords

Query Keywords
Query keywords are contextual keywords used in LINQ queries.

Query Keywords

from

where

select

group

into

orderby

join

let

in

on

equals

by

ascending

descending

As mentioned above, a keyword cannot be used as an identifier


(name of the variable, class, interface, etc.). However, they can be
used with the prefix '@'. For example, the class is a reserved
keyword, so it cannot be used as an identifier, but @class can be
used as shown below.

Example: Use Keyword as Identifier


public class @class
{
public static int MyProperty { get; set; }
}

@class.MyProperty = 100;

C# Class
A class is like a blueprint of a specific object. In the real world, every
object has some color, shape, and functionalities - for example, the
luxury car Ferrari. Ferrari is an object of the luxury car type. The
luxury car is a class that indicates some characteristics like speed,
color, shape, interior, etc. So any company that makes a car that
meets those requirements is an object of the luxury car type. For
example, every single car of BMW, Lamborghini, Cadillac are an
object of the class called 'Luxury Car'. Here, 'Luxury Car' is a class,
and every single physical car is an object of the luxury car class.

Likewise, in object-oriented programming, a class defines some


properties, fields, events, methods, etc. A class defines the kinds of
data and the functionality their objects will have.

A class enables you to create your custom types by grouping


variables of other types, methods, and events.

In C#, a class can be defined by using the class keyword.

Example: C# Class
public class MyClass
{
public string myField = string.Empty;

public MyClass()
{
}
public void MyMethod(int parameter1, string parameter2)
{
Console.WriteLine("First Parameter {0}, second parameter {1}",
parameter1,
parameter2);
}

public int MyAutoImplementedProperty { get; set; }

private int myPropertyVar;

public int MyProperty


{
get { return myPropertyVar; }
set { myPropertyVar = value; }
}
}

The following image shows the important building blocks of C# class.

C# Class
C# Access Modifiers
Access modifiers are applied to the declaration of the class, method,
properties, fields, and other members. They define the accessibility
of the class and its members. Public, private, protected, and internal
are access modifiers in C#. We will learn about it in
the keyword section.

C# Field
The field is a class-level variable that holds a value. Generally, field
members should have a private access modifier and used with
property.

C# Constructor
A class can have parameterized or parameterless constructors. The
constructor will be called when you create an instance of a class.
Constructors can be defined by using an access modifier and class
name: <access modifiers> <class name>(){ }

Example: Constructor in C#
class MyClass
{
public MyClass()
{

}
}

C# Method
A method can be defined using the following template:

{access modifier} {return type} MethodName({parameterType


parameterName})

Example: Method in C#
public void MyMethod(int parameter1, string parameter2)
{
// write your method code here..

}
ADVERTISEMENT

Property
A property can be defined using getters and setters, as shown below:

Example: Property in C#
private int _myPropertyVar;

public int MyProperty


{
get { return _myPropertyVar; }
set { _myPropertyVar = value; }
}

Property encapsulates a private field. It provides getters (get{}) to


retrieve the value of the underlying field and setters (set{}) to set
the value of the underlying field. In the above example,
_myPropertyVar is a private field that cannot be accessed directly. It
will only be accessed via MyProperty. Thus, MyProperty encapsulates
_myPropertyVar.

You can also apply some additional logic in get and set, as in the
below example.

Example: Property in C#
private int _myPropertyVar;

public int MyProperty


{
get {
return _myPropertyVar / 2;
}

set {
if (value > 100)
_myPropertyVar = 100;
else
_myPropertyVar = value; ;
}
}

Auto-implemented Property
From C# 3.0 onwards, property declaration has been made easy if
you don't want to apply some logic in get or set.

The following is an example of an auto-implemented property:

Example: Auto implemented property in C#


public int MyAutoImplementedProperty { get; set; }

Notice that there is no private backing field in the above property


example. The backing field will be created automatically by the
compiler. You can work with an automated property as you would
with a normal property of the class. Automated-implemented
property is just for easy declaration of the property when no
additional logic is required in the property accessors.

Namespace
The namespace is a container for a set of related classes and
namespaces. The namespace is also used to give unique names to
classes within the namespace name. Namespace and classes are
represented using a dot (.).

In C#, namespace can be defined using the namespace keyword.

Example: Namespace
namespace CSharpTutorials
{
class MyClass
{

}
}

In the above example, the fully qualified class name


of MyClass is CSharpTutorials.MyClass.
A namespace can contain other namespaces. Inner namespaces can
be separated using (.).

Example: Namespace
namespace CSharpTutorials.Examples
{
class MyClassExample
{

}
}

In the above example, the fully qualified class name


of MyClassExample is CSharpTutorials.Examples.MyClassExample

C# Variables
In C#, a variable contains a data value of the specific data type.

Syntax
<data type> <variable name> = <value>;

The following declares and initializes a variable of an int type.

Example: C# Variable
int num = 100;

Above, int is a data type, num is a variable name (identifier).


The = operator is used to assign a value to a variable. The right side
of the = operator is a value that will be assigned to left side variable.
Above, 100 is assigned to a variable num.

The following declares and initializes variables of different data types.

Example: C# Variables
int num = 100;
float rate = 10.2f;
decimal amount = 100.50M;
char code = 'C';
bool isValid = true;
string name = "Steve";

The followings are naming conventions for declaring variables in C#:

 Variable names must be unique.


 Variable names can contain letters, digits, and the underscore _ only.
 Variable names must start with a letter.
 Variable names are case-sensitive, num and Num are considered different
names.
 Variable names cannot contain reserved keywords. Must
prefix @ before keyword if want reserve keywords as identifiers.

C# is the strongly typed language. It means you can assign a value


of the specified data type. You cannot assign an integer value to
string type or vice-versa.

Example: Cannot assign string to int type variable


int num = "Steve";

Variables can be declared first and initialized later.

Example: Late Initialization


int num;
num = 100;

A variable must be assigned a value before using it, otherwise, C#


will give a compile-time error.

Error: Invalid Assignment


int i;
int j = i; //compile-time error: Use of unassigned local variable 'i'

The value of a variable can be changed anytime after initializing it.

Example: C# Variable
int num = 100;
num = 200;
Console.WriteLine(num); //output: 200

Multiple variables of the same data type can be declared and


initialized in a single line separated by commas.

Example: Multiple Variables in a Single Line


int i, j = 10, k = 100;
Multiple variables of the same type can also be declared in multiple
lines separated by a comma. The compiler will consider it to be one
statement until it encounters a semicolon ;.

Example: Multi-Line Declarations


int i = 0,
j = 10,
k = 100;

In C#, variables are categorized based on how they store their value
in memory. Variables can be value type or reference type or pointer
type.

It is not necessary to specify the specific type when declaring


variables. Use the var keyword instead of a data type.

In C#, variables must be declared with the data type. These are
called explicitly typed variables.

Example: Explicitly Typed Variable


int i = 100;// explicitly typed variable

C# 3.0 introduced var keyword to declare method level variables


without specifying a data type explicitly.

Example: Implicitly Typed Local Variable


var j = 100; // implicitly typed local variable

The compiler will infer the type of a variable from the expression on
the right side of the = operator. Above, var will be compiled as int.

The following infers the type from an expression.

Example: var from expression


int i = 10;
var j = i + 1; // compiles as int

varcan be used to declare any built-in data type or a user-defined


type or an anonymous type variable. The following example shows
C# compiler infers type based on the value:
Example: Implicitly-Typed Variable
static void Main(string[] args)
{
var i = 10;
Console.WriteLine("Type of i is {0}", i.GetType());

var str = "Hello World!!";


Console.WriteLine("Type of str is {0}", str.GetType());

var dbl = 100.50d;


Console.WriteLine("Type of dbl is {0}", dbl.GetType());

var isValid = true;


Console.WriteLine("Type of isValid is {0}", isValid.GetType());

var ano = new { name = "Steve" };


Console.WriteLine("Type of ano is {0}", ano.GetType());

var arr = new[] { 1, 10, 20, 30 };


Console.WriteLine("Type of arr is {0}", arr.GetType());

var file = new FileInfo("MyFile");


Console.WriteLine("Type of file is {0}", file.GetType());

Implicitly-typed variables must be initialized at the time of


declaration; otherwise C# compiler would give an error: Implicitly-
typed variables must be initialized.

var i; // Compile-time error: Implicitly-typed variables must be


initialized
i = 100;

Multiple declarations of var variables in a single statement are not


allowed.

var i = 100, j = 200, k = 300; // Error: cannot declare var variables


in a single statement

//The followings are also valid


var i = 100;
var j = 200;
var k = 300;
var cannot be used for function parameters.

void Display(var param) //Compile-time error


{
Console.Write(param);
}

var can be used in for, and foreach loops.

for(var i = 0; i < 10; i++)


{
Console.WriteLine(i);
}

var can also be used with LINQ queries.

Example: LINQ Query Syntax in C#


// string collection
IList<string> stringList = new List<string>() {
"C# Tutorials",
"VB.NET Tutorials",
"Learn C++",
"MVC Tutorials" ,
"Java"
};

// LINQ Query Syntax


var result = from s in stringList
where s.Contains("Tutorials")
select s;

C# - Data Types
C# is a strongly-typed language. It means we must declare the type
of a variable that indicates the kind of values it is going to store,
such as integer, float, decimal, text, etc.

The following declares and initialized variables of different data


types.

Example: Variables of Different Data Types


string stringVar = "Hello World!!";
int intVar = 100;
float floatVar = 10.2f;
char charVar = 'A';
bool boolVar = true;

C# mainly categorized data types in two types: Value types and


Reference types. Value types include simple types (such as int, float,
bool, and char), enum types, struct types, and Nullable value types.
Reference types include class types, interface types, delegate types,
and array types. Learn about value types and reference types in
detail in the next chapter.

Predefined Data Types in C#


C# includes some predefined value types and reference types. The
following table lists predefined data types:

Type Description Range Suffix

byte 8-bit unsigned integer 0 to 255

sbyte 8-bit signed integer -128 to 127

short 16-bit signed integer -32,768 to 32,767

ushort 16-bit unsigned integer 0 to 65,535

int 32-bit signed integer -2,147,483,648


to
Type Description Range Suffix

2,147,483,647

uint 32-bit unsigned integer 0 to 4,294,967,295 u

long 64-bit signed integer -9,223,372,036,854,775,808 l


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

ulong 64-bit unsigned integer 0 to 18,446,744,073,709,551,615 ul

float 32-bit Single-precision floating point type -3.402823e38 to 3.402823e38 f

double 64-bit double-precision floating point type -1.79769313486232e308 to 1.79769313486232e308 d

decimal 128-bit decimal type for financial and monetary (+ or -)1.0 x 10e-28 m
calculations to
7.9 x 10e28

char 16-bit single Unicode character Any valid character, e.g. a,*, \x0058 (hex), or\u0058
(Unicode)

bool 8-bit logical true/false value True or False

object Base type of all other types.

string A sequence of Unicode characters

DateTim Represents date and time 0:00:00am 1/1/01


e to
11:59:59pm 12/31/9999

As you can see in the above table that each data type (except string
and object) includes value range. The compiler will give an error if
the value goes out of datatype's permitted range. For example, int
data type's range is -2,147,483,648 to 2,147,483,647. So if you
assign a value which is not in this range, then the compiler would
give an error.

Example: Compile time error


// compile time error: Cannot implicitly convert type 'long' to 'int'.
int i = 21474836470;

The value of unsigned integers, long, float, double, and decimal type
must be suffix by u,l,f,d, and m, respectively.
Example: Value Suffix
uint ui = 100u;
float fl = 10.2f;
long l = 45755452222222l;
ulong ul = 45755452222222ul;
double d = 11452222.555d;
decimal mon = 1000.15m;

Alias vs .NET Type


The predefined data types are alias to their .NET type (CLR class)
name. The following table lists alias for predefined data types and
related .NET class name.

Alias .NET Type Type

byte System.Byte struct

sbyte System.SByte struct

int System.Int32 struct

uint System.UInt32 struct

short System.Int16 struct

ushort System.UInt16 struct

long System.Int64 struct

ulong System.UInt64 struct

float System.Single struct

double System.Double struct

char System.Char struct

bool System.Boolean struct

object System.Object Class

string System.String Class

decimal System.Decimal struct

DateTime System.DateTime struct


It means that whether you define a variable of int or Int32, both are
the same.

int i = 345;
Int32 i = 345;// same as above

Default Values
Every data type has a default value. Numeric type is 0, boolean has
false, and char has '\0' as default value. Use the default(typename) to
assign a default value of the data type or C# 7.1 onward, use default
literal.

int i = default(int); // 0
float f = default(float);// 0
decimal d = default(decimal);// 0
bool b = default(bool);// false
char c = default(char);// '\0'

// C# 7.1 onwards
int i = default; // 0
float f = default;// 0
decimal d = default;// 0
bool b = default;// false
char c = default;// '\0'

Conversions
The values of certain data types are automatically converted to
different data types in C#. This is called an implicit conversion.

Example: Implicit Conversion


int i = 345;
float f = i;

Console.WriteLine(f); //output: 345

In the above example, the value of an integer variable i is assigned


to the variable of float type f because this conversion operation is
predefined in C#.

The following is an implicit data type conversion table.


Implicit Conversion From To

sbyte short, int, long, float, double, decimal

byte short, ushort, int, uint, long, ulong, float, double, decimal

short int, long, float, double, or decimal

ushort int, uint, long, ulong, float, double, or decimal

int long, float, double, or decimal.

uint long, ulong, float, double, or decimal

long float, double, or decimal

ulong float, double, or decimal

char ushort, int, uint, long, ulong, float, double, or decimal

float Double

Conversions from int, uint, long, or ulong to float and from long or
ulong to double may cause a loss of precision. No data type implicitly
converted to the char type.

However, not all data types are implicitly converted to other data
types. For example, int type cannot be converted to uint implicitly. It
must be specified explicitly, as shown below.

Example: Explicit Conversion


public static void Main()
{
int i = 100;
uint u = (uint) i;
Console.Write(i);
}

In the above example, integer i is converted to uint explicitly by


specifying uint in the brackets (uint). This will convert an integer to
uint.

Numbers in C#
Numbers, in general, can be divided into two types: Integer type and
floating-point types.

Integer type numbers are whole numbers without decimal points. It


can be negative or positive numbers.

Floating-point type is numbers with one or more decimal points. It


can be negative or positive numbers.

C# includes different data types for integer types and floating-point


types based on their size in the memory and capacity to store
numbers.

The following figure illustrates numeric types in C#.

Numeric Types

Integer Types
Integer type numbers are positive or negative whole numbers
without decimal points. C# includes four data types for integer
numbers: byte, short, int, and long.

Byte
The byte data type stores numbers from 0 to 255. It occupies 8-bit in
the memory. The byte keyword is an alias of the Byte struct in .NET.

The sbyte is the same as byte, but it can store negative numbers
from -128 to 127. The sbyte keyword is an alias for SByte struct
in .NET.
Example: byte, sbyte
byte b1 = 255;
byte b2 = -128;// compile-time error: Constant value '-128' cannot be
converted to a 'byte'
sbyte sb1 = -128;
sbyte sb2 = 127;

Console.WriteLine(Byte.MaxValue);//255
Console.WriteLine(Byte.MinValue);//0
Console.WriteLine(SByte.MaxValue);//127
Console.WriteLine(SByte.MinValue);//-128

Short
The short data type is a signed integer that can store numbers from -
32,768 to 32,767. It occupies 16-bit memory. The short keyword is
an alias for Int16 struct in .NET.

The ushort data type is an unsigned integer. It can store only


positive numbers from 0 to 65,535. The ushort keyword is an alias
for UInt16 struct in .NET.

Example: short, ushort


short s1 = -32768;
short s2 = 32767;
short s3 = 35000;//Compile-time error: Constant value '35000' cannot
be converted to a 'short'

ushort us1 = 65535;


ushort us2 = -32000; //Compile-time error: Constant value '-32000'
cannot be converted to a 'ushort'

Console.WriteLine(Int16.MaxValue);//32767
Console.WriteLine(Int16.MinValue);//-32768
Console.WriteLine(UInt16.MaxValue);//65535
Console.WriteLine(UInt16.MinValue);//0
Try it
Int
The int data type is 32-bit signed integer. It can store numbers from
-2,147,483,648 to 2,147,483,647. The int keyword is an alias
of Int32 struct in .NET.

The uint is 32-bit unsigned integer. The uint keyword is an alias


of UInt32 struct in .NET. It can store positive numbers from 0 to
4,294,967,295. Optionally use U or u suffix after a number to assign
it to uint variable.

Example: int, uint


int i = -2147483648;
int j = 2147483647;
int k = 4294967295; //Compile-time error: Cannot implicitly convert
type 'uint' to 'int'.

uint ui1 = 4294967295;


uint ui2 =-1; //Compile-time error: Constant value '-1' cannot be
converted to a 'uint'

Console.WriteLine(Int32.MaxValue);//2147483647
Console.WriteLine(Int32.MinValue);//-2147483648
Console.WriteLine(UInt32.MaxValue);//4294967295
Console.WriteLine(UInt32.MinValue);//0

The int data type is also used for hexadecimal and binary numbers. A
hexadecimal number starts with 0x or 0X prefix. C# 7.2 onwards, a
binary number starts with 0b or 0B.

Example: Hexadecimal, Binary


int hex = 0x2F;
int binary = 0b_0010_1111;

Console.WriteLine(hex);
Console.WriteLine(binary);

Long
The long type is 64-bit signed integers. It can store numbers from -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use l or
L suffix with number to assign it to long type variable. The long
keyword is an alias of Int64 struct in .NET.

The ulong type stores positive numbers from 0 to


18,446,744,073,709,551,615. If a number is suffixed by UL, Ul, uL,
ul, LU, Lu, lU, or lu, its type is ulong. The uint keyword is an alias
of UInt64 struct in .NET.

Example: long, ulong


long l1 = -9223372036854775808;
long l2 = 9223372036854775807;

ulong ul1 = 18223372036854775808ul;


ulong ul2 = 18223372036854775808UL;

Console.WriteLine(Int64.MaxValue);//9223372036854775807
Console.WriteLine(Int64.MinValue);//-9223372036854775808
Console.WriteLine(UInt64.MaxValue);//18446744073709551615
Console.WriteLine(UInt64.MinValue);//0
Try it

Floating Point Types


Floating-point numbers are positive or negative numbers with one or
more decimal points. C# includes three data types for floating-point
numbers: float, double, and decimal.

Float
The float data type can store fractional numbers from 3.4e−038 to
3.4e+038. It occupies 4 bytes in the memory. The float keyword is
an alias of Single struct in .NET.

Use f or F suffix with literal to make it float type.

Example: float
float f1 = 123456.5F;
float f2 = 1.123456f;

Console.WriteLine(f1);//123456.5
Console.WriteLine(f2);//1.123456
Try it

Double
The double data type can store fractional numbers from 1.7e−308 to
1.7e+308. It occupies 8 bytes in the memory. The double keyword is
an alias of the Double struct in .NET.

Use d or D suffix with literal to make it double type.

Example: double
double d1 = 12345678912345.5d;
double d2 = 1.123456789123456d;

Console.WriteLine(d1);//12345678912345.5
Console.WriteLine(d2);//1.123456789123456

Decimal
The decimal data type can store fractional numbers from ±1.0 x 10-
28 to ±7.9228 x 1028. It occupies 16 bytes in the memory. The
decimal is a keyword alias of the Decimal struct in .NET.

The decimal type has more precision and a smaller range than both
float and double, and so it is appropriate for financial and monetary
calculations.

Use m or M suffix with literal to make it decimal type.

Example: decimal
decimal d1 = 123456789123456789123456789.5m;
decimal d2 = 1.1234567891345679123456789123m;

Console.WriteLine(d1);
Console.WriteLine(d2);
Try it

Scientific Notation
Use e or E to indicate the power of 10 as exponent part of scientific
notation with float, double or decimal.
Example:
double d = 0.12e2;
Console.WriteLine(d); // 12;

float f = 123.45e-2f;
Console.WriteLine(f); // 1.2345

decimal m = 1.2e6m;
Console.WriteLine(m);// 1200000

C# Strings
In C#, a string is a series of characters that is used to represent
text. It can be a character, a word or a long passage surrounded with
the double quotes ". The following are string literals.

Example: String Literals


"S"
"String"
"This is a string."

C# provides the String data type to store string literals. A variable of


the string type can be declared and assign string literal, as shown
below.

Example: String Type Variables


string ch = "S";
string word = "String";
string text = "This is a string.";

The maximum size of a String object in memory is 2GB or about 1


billion characters. However, practically it will be less depending upon
CPU and memory of the computer.

There two ways to declare a string variable in C#.


Using System.String class and using string keyword. Both are the same
and make no difference. Learn string vs String for more info.

Example: String and string


string str1 = "Hello"; // uses string keyword
String str2 = "Hello"; // uses System.String class

In C#, a string is a collection or an array of characters. So, string


can be created using a char array or accessed like a char array.

Example: String as char Array


char[] chars = {'H','e','l','l','o'};

string str1 = new string(chars);


String str2 = new String(chars);

foreach (char c in str1)


{
Console.WriteLine(c);
}

Special Characters
A text in the real world can include any character. In C#, because a
string is surrounded with double quotes, it cannot include " in a
string. The following will give a compile-time error.

Example: Invalid String


string text = "This is a "string" in C#.";

C# includes escaping character \ (backslash) before these special


characters to include in a string.

Use backslash \ before double quotes and some special characters


such as \,\n,\r,\t, etc. to include it in a string.

Example: Escape Char \


string text = "This is a \"string\" in C#.";
string str = "xyzdef\\rabc";
string path = "\\\\mypc\\ shared\\project";

However, it will be very tedious to prefix \ for every special


character. Prefixing the string with an @ indicates that it should be
treated as a literal and should not escape any character.

Example: Escape Sequence


string str = @"xyzdef\rabc";
string path = @"\\mypc\shared\project";
string email = @"test@test.com";

Use @ and \ to declare a multi-line string.

Example: Multi-line String


string str = @"this is a \
multi line \
string";

Please note that you must use a backslash to allow " in a string. @ is
only for special characters in C#.

string text = @"This is a "string." in C#."; // error


string text = @"This is a \"string\" in C#."; // error
string text = "This is a \"string\" in C#."; // valid

String Concatenation
Multiple strings can be concatenated with + operator.

Example: String Concatenation


string name = "Mr." + "James " + "Bond" + ", Code: 007";

string firstName = "James";


string lastName = "Bond";
string code = "007";

string agent = "Mr." + firstName + " " + lastName + ", Code: " + code;

A String is immutable in C#. It means it is read-only and cannot be


changed once created in the memory. Each time you concatenate
strings, .NET CLR will create a new memory location for the
concatenated string. So, it is recommended to
use StringBuilder instead of string if you concatenate more than five
strings.

String Interpolation
String interpolation is a better way of concatenating strings. We use
+ sign to concatenate string variables with static strings.
C# 6 includes a special character $ to identify an interpolated string.
An interpolated string is a mixture of static string and string variable
where string variables should be in {} brackets.

Example: String Interpolation


string firstName = "James";
string lastName = "Bond";
string code = "007";

string fullName = $"Mr. {firstName} {lastName}, Code: {code}";

In the above example of interpolation, $ indicates the interpolated


string, and {} includes string variable to be incorporated with a
string.

Use two braces, "{{" or "}}" to include { or } in a string.

Working with Date and Time in C#


C# includes DateTime struct to work with dates and times.

To work with date and time in C#, create an object of


the DateTime struct using the new keyword. The following creates
a DateTime object with the default value.

Example: Create DateTime Object


DateTime dt = new DateTime(); // assigns default value 01/01/0001
00:00:00

The default and the lowest value of a DateTime object is January 1,


0001 00:00:00 (midnight). The maximum value can be December
31, 9999 11:59:59 P.M.

Use different constructors of the DateTime struct to assign an initial


value to a DateTime object.

Example: Set Date & Time


//assigns default value 01/01/0001 00:00:00
DateTime dt1 = new DateTime();
//assigns year, month, day
DateTime dt2 = new DateTime(2015, 12, 31);

//assigns year, month, day, hour, min, seconds


DateTime dt3 = new DateTime(2015, 12, 31, 5, 10, 20);

//assigns year, month, day, hour, min, seconds, UTC timezone


DateTime dt4 = new DateTime(2015, 12, 31, 5, 10, 20,
DateTimeKind.Utc);

In the above example, we specified a year, a month, and a day in the


constructor. The year can be from 0001 to 9999, and the Month can
be from 1 to 12, and the day can be from 1 to 31. Setting any other
value out of these ranges will result in a run-time exception.

Example: Invalid Date


DateTime dt = new DateTime(2015, 12, 32); //throws exception: day out
of range

Use different DateTime constructors to set date, time, time zone,


calendar, and culture.

Ticks
Ticks is a date and time expressed in the number of 100-nanosecond
intervals that have elapsed since January 1, 0001, at 00:00:00.000
in the Gregorian calendar. The following initializes a DateTime object
with the number of ticks.

Example: Ticks
DateTime dt = new DateTime(636370000000000000);
DateTime.MinValue.Ticks; //min value of ticks
DateTime.MaxValue.Ticks; // max value of ticks
DateTime Static Fields
The DateTime struct includes static fields, properties, and methods. The
following example demonstrates important static fields and
properties.

Example: Static Fields


DateTime currentDateTime = DateTime.Now; //returns current date and
time
DateTime todaysDate = DateTime.Today; // returns today's date
DateTime currentDateTimeUTC = DateTime.UtcNow;// returns current UTC
date and time

DateTime maxDateTimeValue = DateTime.MaxValue; // returns max value of


DateTime
DateTime minDateTimeValue = DateTime.MinValue; // returns min value of
DateTime

TimeSpan
TimeSpan is a struct that is used to represent time in days, hour,
minutes, seconds, and milliseconds.

Example: TimeSpan
DateTime dt = new DateTime(2015, 12, 31);

TimeSpan ts = new TimeSpan(25,20,55);

DateTime newDate = dt.Add(ts);

Console.WriteLine(newDate);//1/1/2016 1:20:55 AM

Subtraction of two dates results in TimeSpan.

Example: Subtract Dates


DateTime dt1 = new DateTime(2015, 12, 31);
DateTime dt2 = new DateTime(2016, 2, 2);
TimeSpan result = dt2.Subtract(dt1);//33.00:00:00
Operators
The DateTime struct overloads +, -, ==, !=, >, <, <=, >= operators to ease out addition,
subtraction, and comparison of dates. These make it easy to work with dates.

Example: Operators
DateTime dt1 = new DateTime(2015, 12, 20);
DateTime dt2 = new DateTime(2016, 12, 31, 5, 10, 20);
TimeSpan time = new TimeSpan(10, 5, 25, 50);

Console.WriteLine(dt2 + time); // 1/10/2017 10:36:10 AM


Console.WriteLine(dt2 - dt1); //377.05:10:20
Console.WriteLine(dt1 == dt2); //False
Console.WriteLine(dt1 != dt2); //True
Console.WriteLine(dt1 > dt2); //False
Console.WriteLine(dt1 < dt2); //True
Console.WriteLine(dt1 >= dt2); //False
Console.WriteLine(dt1 <= dt2);//True

Convert String to DateTime


A valid date and time string can be converted to a DateTime object
using Parse(), ParseExact(), TryParse() and TryParseExact() methods.

The Parse() and ParseExact() methods will throw an exception if the specified string is
not a valid representation of a date and time. So, it's recommended to use TryParse() or
TryParseExact() method because they return false if a string is not valid.

Example:
var str = "5/12/2020";
DateTime dt;

var isValidDate = DateTime.TryParse(str, out dt);

if(isValidDate)
Console.WriteLine(dt);
else
Console.WriteLine($"{str} is not a valid date string");

C# - Struct
Updated on: June 25, 2020

In C#, struct is the value type data type that represents data
structures. It can contain a parameterized constructor, static
constructor, constants, fields, methods, properties, indexers,
operators, events, and nested types.

struct can be used to hold small data values that do not require
inheritance, e.g. coordinate points, key-value pairs, and complex
data structure.

Structure Declaration
A structure is declared using struct keyword. The default modifier is
internal for the struct and its members.

The following example declares a structure Coordinate for the graph.

Example: Structure
struct Coordinate
{
public int x;
public int y;
}

A struct object can be created with or without the new operator, same
as primitive type variables.

Example: Create Structure


struct Coordinate
{
public int x;
public int y;
}

Coordinate point = new Coordinate();


Console.WriteLine(point.x); //output: 0
Console.WriteLine(point.y); //output: 0
Above, an object of the Coordinate structure is created using
the new keyword. It calls the default parameterless constructor of
the struct, which initializes all the members to their default value of
the specified data type.

If you declare a variable of struct type without using new keyword, it


does not call any constructor, so all the members remain unassigned.
Therefore, you must assign values to each member before accessing
them, otherwise, it will give a compile-time error.

Example: Create Structure Without new Keyword


struct Coordinate
{
public int x;
public int y;
}

Coordinate point;
Console.Write(point.x); // Compile time error

point.x = 10;
point.y = 20;
Console.Write(point.x); //output: 10
Console.Write(point.y); //output: 20

Constructors in Structure
A struct cannot contain a parameterless constructor. It can only
contain parameterized constructors or a static constructor.

Example: Parameterized Constructor in Struct


struct Coordinate
{
public int x;
public int y;

public Coordinate(int x, int y)


{
this.x = x;
this.y = y;
}
}
Coordinate point = new Coordinate(10, 20);

Console.WriteLine(point.x); //output: 10
Console.WriteLine(point.y); //output: 20

You must include all the members of the struct in the parameterized
constructor and assign parameters to members; otherwise C#
compiler will give a compile-time error if any member remains
unassigned.

Methods and Properties in Structure


A struct can contain properties, auto-implemented properties,
methods, etc., same as classes.

Example: Methods and Properties in Struct


struct Coordinate
{
public int x { get; set; }
public int y { get; set; }

public void SetOrigin()


{
this.x = 0;
this.y = 0;
}
}

Coordinate point = Coordinate();


point.SetOrigin();

Console.WriteLine(point.x); //output: 0
Console.WriteLine(point.y); //output: 0

The following struct includes the static method.

Example: Static Constructor in Struct


struct Coordinate
{
public int x;
public int y;

public Coordinate(int x, int y)


{
this.x = x;
this.y = y;
}

public static Coordinate GetOrigin()


{
return new Coordinate();
}
}

Coordinate point = Coordinate.GetOrigin();

Console.WriteLine(point.x); //output: 0
Console.WriteLine(point.y); //output: 0

Events in Structure
A struct can contain events to notify subscribers about some action.
The following struct contains an event.

Example: Event in Structure


struct Coordinate
{
private int _x, _y;

public int x
{
get{
return _x;
}

set{
_x = value;
CoordinatesChanged(_x);
}
}
public int y
{
get{
return _y;
}

set{
_y = value;
CoordinatesChanged(_y);
}
}

public event Action<int> CoordinatesChanged;


}

The above structure contains CoordinatesChanged event, which will be


raised when x or y coordinate changes. The following example
demonstrates the handling of the CoordinatesChanged event.

Example: Handle Structure Events


class Program
{
static void Main(string[] args)
{

Coordinate point = new Coordinate();

point.CoordinatesChanged += StructEventHandler;
point.x = 10;
point.y = 20;
}

static void StructEventHandler(int point)


{
Console.WriteLine("Coordinate changed to {0}", point);
}
}

structis a value type, so it is faster than a class object. Use struct


whenever you want to just store the data. Generally, structs are
good for game programming. However, it is easier to transfer a class
object than a struct. So do not use struct when you are passing data
across the wire or to other classes.
Summary
 struct can include constructors, constants, fields, methods, properties,
indexers, operators, events & nested types.
 struct cannot include a parameterless constructor or a destructor.
 struct can implement interfaces, same as class.
 struct cannot inherit another structure or class, and it cannot be the
base of a class.
 struct members cannot be specified as abstract, sealed, virtual, or
protected.

C# Enumerations Type - Enum


In C#, an enum (or enumeration type) is used to assign constant
names to a group of numeric integer values. It makes constant
values more readable, for example, WeekDays.Monday is more readable
then number 0 when referring to the day in a week.

An enum is defined using the enum keyword, directly inside a


namespace, class, or structure. All the constant names can be
declared inside the curly brackets and separated by a comma. The
following defines an enum for the weekdays.

Example: Define an Enum


enum WeekDays
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}

Above, the WeekDays enum declares members in each line separated by


a comma.
Enum Values
If values are not assigned to enum members, then the compiler will
assign integer values to each member starting with zero by default.
The first member of an enum will be 0, and the value of each
successive enum member is increased by 1.

Example: Default Enum Values


enum WeekDays
{
Monday, // 0
Tuesday, // 1
Wednesday, // 2
Thursday, // 3
Friday, // 4
Saturday, // 5
Sunday // 6
}

You can assign different values to enum member. A change in the


default value of an enum member will automatically assign
incremental values to the other members sequentially.

Example: Assign Values to Enum Members


enum Categories
{
Electronics, // 0
Food, // 1
Automotive = 6, // 6
Arts, // 7
BeautyCare, // 8
Fashion // 9
}

You can even assign different values to each member.

Example: Assign Values to Enum Members


enum Categories
{
Electronics = 1,
Food = 5,
Automotive = 6,
Arts = 10,
BeautyCare = 11,
Fashion = 15,
WomanFashion = 15
}

The enum can be of any numeric data type such as byte, sbyte,
short, ushort, int, uint, long, or ulong. However, an enum cannot be
a string type.

Specify the type after enum name as : type. The following defines the
byte enum.

Example: byte Enum


enum Categories: byte
{
Electronics = 1,
Food = 5,
Automotive = 6,
Arts = 10,
BeautyCare = 11,
Fashion = 15
}

Access an Enum
An enum can be accessed using the dot syntax: enum.member

Example: Access Enum


enum WeekDays
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}

Console.WriteLine(WeekDays.Monday); // Monday
Console.WriteLine(WeekDays.Tuesday); // Tuesday
Console.WriteLine(WeekDays.Wednesday); // Wednesday
Console.WriteLine(WeekDays.Thursday); // Thursday
Console.WriteLine(WeekDays.Friday); // Friday
Console.WriteLine(WeekDays.Saturday); // Saturday
Console.WriteLine(WeekDays.Sunday); // Sunday

Conversion
Explicit casting is required to convert from an enum type to its
underlying integral type.

Example: Enum Conversion


enum WeekDays
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}

Console.WriteLine(WeekDays.Friday); //output: Friday


int day = (int) WeekDays.Friday; // enum to int conversion
Console.WriteLine(day); //output: 4

var wd = (WeekDays) 5; // int to enum conversion


Console.WriteLine(wd);//output: Saturday

C# - StringBuilder
In C#, the string type is immutable. It means a string cannot be
changed once created. For example, a new string, "Hello World!" will
occupy a memory space on the heap. Now, by changing the initial
string "Hello World!" to "Hello World! from Tutorials Teacher" will
create a new string object on the memory heap instead of modifying
an original string at the same memory address. This behavior would
hinder the performance if the original string changed multiple times
by replacing, appending, removing, or inserting new strings in the
original string.

Memory Allocation for String Object

To solve this problem, C# introduced the StringBuilder in


the System.Text namespace. The StringBuilder doesn't create a new
object in the memory but dynamically expands memory to
accommodate the modified string.

Memory Allocation for StringBuilder


Object
Creating a StringBuilder Object
You can create an object of the StringBuilder class using
the new keyword and passing an initial string. The following example
demonstrates creating StringBuilder objects.

Example: StringBuilder
using System.Text; // include at the top

StringBuilder sb = new StringBuilder(); //string will be appended


later
//or
StringBuilder sb = new StringBuilder("Hello World!");

Optionally, you can also specify the maximum capacity of


the StringBuilder object using overloaded constructors, as shown
below.

Example: StringBuilder
StringBuilder sb = new StringBuilder(50); //string will be appended
later
//or
StringBuilder sb = new StringBuilder("Hello World!", 50);

Above, C# allocates a maximum of 50 spaces sequentially on the


memory heap. This capacity will automatically be doubled once it
reaches the specified capacity. You can also use
the capacity or length property to set or retrieve
the StringBuilder object's capacity.

You can iterate the using for loop to get or set a character at the
specified index.

Example: StringBuilder Iteration


StringBuilder sb = new StringBuilder("Hello World!");

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


Console.Write(sb[i]); // output: Hello World!
Retrieve String from StringBuilder
The StringBuilder is not the string. Use the ToString() method to retrieve
a string from the StringBuilder object.

Example: Retrieve String from StringBuilder


StringBuilder sb = new StringBuilder("Hello World!");

var greet = sb.ToString(); //returns "Hello World!"

Add/Append String to StringBuilder


Use the Append() method to append a string at the end of the
current StringBuilder object. If a StringBuilder does not contain any
string yet, it will add it. The AppendLine() method append a string with
the newline character at the end.

Example: Adding or Appending Strings in StringBuilder


StringBuilder sb = new StringBuilder();
sb.Append("Hello ");
sb.AppendLine("World!");
sb.AppendLine("Hello C#");
Console.WriteLine(sb);

Output:

Hello World!

Hello C#.

Append Formated String to StringBuilder


Use the AppendFormat() method to format an input string into the
specified format and append it.

Example: AppendFormat()
StringBuilder sbAmout = new StringBuilder("Your total amount is ");
sbAmout.AppendFormat("{0:C} ", 25);

Console.WriteLine(sbAmout);//output: Your total amount is $ 25.00

Insert String into StringBuilder


Use the Insert() method inserts a string at the specified index in
the StringBuilder object.

Example: Insert()
StringBuilder sb = new StringBuilder("Hello World!");
sb.Insert(5," C#");

Console.WriteLine(sb); //output: Hello C# World!

Remove String in StringBuilder


Use the Remove() method to remove a string from the specified index
and up to the specified length.

Example: Remove()
StringBuilder sb = new StringBuilder("Hello World!",50);
sb.Remove(6, 7);

Console.WriteLine(sb); //output: Hello

Replace String in StringBuilder


Use the Replace() method to replace all the specified string
occurrences with the specified replacement string.

Example: Replace()
StringBuilder sb = new StringBuilder("Hello World!");
sb.Replace("World", "C#");

Console.WriteLine(sb);//output: Hello C#!


Points to Remember :

1. StringBuilder is mutable.
2. StringBuilder performs faster than string when appending multiple string
values.
3. Use StringBuilder when you need to append more than three or four strings.
4. Use the Append() method to add or append strings to
the StringBuilder object.
5. Use the ToString() method to retrieve a string from
the StringBuilder object.

C# - Anonymous Type

Updated on: May 2, 2020

In C#, an anonymous type is a type (class) without any name that


can contain public read-only properties only. It cannot contain other
members, such as fields, methods, events, etc.

You create an anonymous type using the new operator with an object
initializer syntax. The implicitly typed variable- var is used to hold
the reference of anonymous types.

The following example demonstrates creating an anonymous type


variable student that contains three properties named Id, FirstName,
and LastName.

Example: Anonymous Type


var student = new { Id = 1, FirstName = "James", LastName = "Bond" };

The properties of anonymous types are read-only and cannot be


initialized with a null, anonymous function, or a pointer type. The
properties can be accessed using dot (.) notation, same as object
properties. However, you cannot change the values of properties as
they are read-only.

Example: Access Anonymous Type


var student = new { Id = 1, FirstName = "James", LastName = "Bond" };
Console.WriteLine(student.Id); //output: 1
Console.WriteLine(student.FirstName); //output: James
Console.WriteLine(student.LastName); //output: Bond

student.Id = 2;//Error: cannot chage value


student.FirstName = "Steve";//Error: cannot chage value

An anonymous type's property can include another anonymous type.

Example: Nested Anonymous Type


var student = new {
Id = 1,
FirstName = "James",
LastName = "Bond",
Address = new { Id = 1, City = "London", Country =
"UK" }
};

You can create an array of anonymous types also.

Example: Array of Anonymous Types


var students = new[] {
new { Id = 1, FirstName = "James", LastName = "Bond" },
new { Id = 2, FirstName = "Steve", LastName = "Jobs" },
new { Id = 3, FirstName = "Bill", LastName = "Gates" }
};

An anonymous type will always be local to the method where it is


defined. It cannot be returned from the method. However, an
anonymous type can be passed to the method as object type
parameter, but it is not recommended. If you need to pass it to
another method, then use struct or class instead of an anonymous
type.
Mostly, anonymous types are created using the Select clause of a
LINQ queries to return a subset of the properties from each object in
the collection.

Example: LINQ Query returns an Anonymous Type


class Program
{
static void Main(string[] args)
{
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", age =
18 },
new Student() { StudentID = 2, StudentName = "Steve", age
= 21 },
new Student() { StudentID = 3, StudentName = "Bill", age
= 18 },
new Student() { StudentID = 4, StudentName = "Ram" , age =
20 },
new Student() { StudentID = 5, StudentName = "Ron" , age =
21 }
};

var students = from s in studentList


select new { Id = s.StudentID, Name =
s.StudentName };

foreach(var stud in students)


Console.WriteLine(stud.Id + "-" + stud.Name);
}
}

public class Student


{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int age { get; set; }
}

Output:
1-John

2-Steve

3-Bill

4-Ram

5-Ron

In the above example, a select clause in the LINQ query selects


only StudentID and StudentName properties and renames it
to Id and Name, respectively. Thus, it is useful in saving memory and
unnecessary code. The query result collection includes
only StudentID and StudentName properties, as shown in the following
debug view.

Visual Studio supports IntelliSense for anonymous types, as shown


below.

An
onymous Type Intellisense Support in Visual Studio

Internally, all the anonymous types are directly derived from


the System.Object class. The compiler generates a class with some
auto-generated name and applies the appropriate type to each
property based on the value expression. Although your code cannot
access it. Use GetType() method to see the name.

Example: Internal Name of an Anonymous Type


static void Main(string[] args)
{
var student = new { Id = 1, FirstName = "James", LastName = "Bond"
};
Console.WriteLine(student.GetType().ToString());
}

C# - Dynamic Types
C# 4.0 (.NET 4.5) introduced a new type called dynamic that avoids
compile-time type checking. A dynamic type escapes type checking at
compile-time; instead, it resolves type at run time.

A dynamic type variables are defined using the dynamic keyword.

Example: dynamic Variable


dynamic MyDynamicVar = 1;

The compiler compiles dynamic types into object types in most cases.
However, the actual type of a dynamic type variable would be
resolved at run-time.

Example: dynamic Type at run-time


dynamic MyDynamicVar = 1;

Console.WriteLine(MyDynamicVar.GetType());
Output:

System.Int32

Dynamic types change types at run-time based on the assigned


value. The following example shows how a dynamic variable changes
type based on assigned value.

Example: dynamic
static void Main(string[] args)
{
dynamic MyDynamicVar = 100;
Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar,
MyDynamicVar.GetType());

MyDynamicVar = "Hello World!!";


Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar,
MyDynamicVar.GetType());

MyDynamicVar = true;
Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar,
MyDynamicVar.GetType());

MyDynamicVar = DateTime.Now;
Console.WriteLine("Value: {0}, Type: {1}", MyDynamicVar,
MyDynamicVar.GetType());
}

Output:

Value: 100, Type: System.Int32

Value: Hello World!!, Type: System.String

Value: True, Type: System.Boolean

Value: 01-01-2014, Type: System.DateTime

The dynamic type variables is converted to other types implicitly.

Example: dynamic Type Conversion


dynamic d1 = 100;
int i = d1;

d1 = "Hello";
string greet = d1;

d1 = DateTime.Now;
DateTime dt = d1;
Methods and Parameters
If you assign a class object to the dynamic type, then the compiler
would not check for correct methods and properties name of a
dynamic type that holds the custom class object. Consider the
following example.

Example: Calling Methods


class Program
{
static void Main(string[] args)
{
dynamic stud = new Student();

stud.DisplayStudentInfo(1, "Bill");// run-time error, no


compile-time error
stud.DisplayStudentInfo("1");// run-time error, no compile-
time error
stud.FakeMethod();// run-time error, no compile-time error
}
}

public class Student


{
public void DisplayStudentInfo(int id)
{
}
}

In the above example, the C# compiler does not check for the
number of parameters, parameters type, or non-existent. It validates
these things at run-time, and if it is not valid, then throws a run-time
exception. Note that Visual Studio IntelliSense is not supported for
the dynamic types. Note that Visual Studio IntelliSense is not
supported for the dynamic types.

The dynamic language runtime (DLR) API provides the infrastructure


that supports the dynamic type in C#. For more information about
the DLR, visit Dynamic Language Runtime Overview .
C# - Nullable Types
As you know, a value type cannot be assigned a null value. For
example, int i = null will give you a compile time error.

C# 2.0 introduced nullable types that allow you to assign null to


value type variables. You can declare nullable types
using Nullable<t> where T is a type.

Example: Nullable type


Nullable<int> i = null;

A nullable type can represent the correct range of values for its
underlying value type, plus an additional null value. For example,
Nullable<int> can be assigned any value from -2147483648 to
2147483647, or a null value.

The Nullable types are instances of System.Nullable<T> struct. Think it as


something like the following structure.

Example: Nullable struct


[Serializable]
public struct Nullable<T> where T : struct
{
public bool HasValue { get; }

public T Value { get; }

// other implementation
}

A nullable of type int is the same as an ordinary int plus a flag that
says whether the int has a value or not (is null or not). All the rest is
compiler magic that treats "null" as a valid value.

Example: HasValue
static void Main(string[] args)
{
Nullable<int> i = null;

if (i.HasValue)
Console.WriteLine(i.Value); // or Console.WriteLine(i)
else
Console.WriteLine("Null");
}

Output:

Null

The HasValue returns true if the object has been assigned a value; if it
has not been assigned any value or has been assigned a null value, it
will return false.

Accessing the value using NullableType.value will throw a runtime


exception if nullable type is null or not assigned any value. For
example, i.Value will throw an exception if i is null:

Invalid
use of Nullable Type

Use the GetValueOrDefault() method to get an actual value if it is not


null and the default value if it is null. For example:

Example: GetValueOrDefault()
static void Main(string[] args)
{
Nullable<int> i = null;

Console.WriteLine(i.GetValueOrDefault());
}
Shorthand Syntax for Nullable Types
You can use the '?' operator to shorthand the syntax e.g. int?, long?
instead of using Nullable<T>.

Example: Shorthand syntax for Nullable types


int? i = null;
double? D = null;

?? Operator
Use the '??' operator to assign a nullable type to a non-nullable type.

Example: ?? operator with Nullable Type


int? i = null;

int j = i ?? 0;

Console.WriteLine(j);

Output:

In the above example, i is a nullable int and if you assign it to the


non-nullable int j then it will throw a runtime exception if i is null. So
to mitigate the risk of an exception, we have used the '??' operator
to specify that if i is null then assign 0 to j.
ADVERTISEMENT

Assignment Rules
A nullable type has the same assignment rules as a value type. It
must be assigned a value before using it if nullable types are
declared in a function as local variables. If it is a field of any class
then it will have a null value by default.
For example, the following nullable of int type is declared and used
without assigning any value. The compiler will give "Use of
unassigned local variable 'i'" error:

Unassigned
nullable type-error

In the following example, a nullable of int type is a field of the class,


so it will not give any error.

Example: Nullable type as Class Field


class MyClass
{
public Nullable<int> i;
}
class Program
{
static void Main(string[] args)
{
MyClass mycls = new MyClass();

if(mycls.i == null)
Console.WriteLine("Null");
}
}

Output:

Null

Nullable Helper Class


Null is considered to be less than any value. So comparison operators
won't work against null. Consider the following example where i is
neither less than j, greater than j nor equal to j:
Example: Nullable Type Comparison
static void Main(string[] args)
{
int? i = null;
int j = 10;

if (i < j)
Console.WriteLine("i < j");
else if( i > 10)
Console.WriteLine("i > j");
else if( i == 10)
Console.WriteLine("i == j");
else
Console.WriteLine("Could not compare");
}

Output:

Could not compare

Nullable static class is a helper class for Nullable types. It provides a


compare method to compare nullable types. It also has a
GetUnderlyingType method that returns the underlying type
argument of nullable types.

Example: Helper Class


static void Main(string[] args)
{
int? i = null;
int j = 10;

if (Nullable.Compare<int>(i, j) < 0)
Console.WriteLine("i < j");
else if (Nullable.Compare<int>(i, j) > 0)
Console.WriteLine("i > j");
else
Console.WriteLine("i = j");
}

Output:
i < j

Characteristics of Nullable Types


1. Nullable types can only be used with value types.
2. The Value property will throw an InvalidOperationException if value is null;
otherwise it will return the value.
3. The HasValue property returns true if the variable contains a value, or false if
it is null.
4. You can only use == and != operators with a nullable type. For other
comparison use the Nullable static class.
5. Nested nullable types are not allowed. Nullable<Nullable<int>> i; will give a
compile time error.

Points to Remember :

1. Nullable<T> type allows assignment of null to value types.


2. ? operator is a shorthand syntax for Nullable types.
3. Use value property to get the value of nullable type.
4. Use HasValue property to check whether value is assigned to nullable
type or not.
5. Static Nullable class is a helper class to compare nullable types.

Value Type and Reference Type


In C#, these data types are categorized based on how they store
their value in the memory. C# includes the following categories of
data types:

1. Value type
2. Reference type
3. Pointer type

Value Type
A data type is a value type if it holds a data value within its own
memory space. It means the variables of these data types directly
contain values.
All the value types derive from System.ValueType, which in-turn, derives
from System.Object.

For example, consider integer variable int i = 100;

The system stores 100 in the memory space allocated for the
variable i. The following image illustrates how 100 is stored at some
hypothetical location in the memory (0x239110) for 'i':

Memory Allocation of Value Type Variable

The following data types are all of value type:

 bool
 byte
 char
 decimal
 double
 enum
 float
 int
 long
 sbyte
 short
 struct
 uint
 ulong
 ushort

Passing Value Type Variables


When you pass a value-type variable from one method to another,
the system creates a separate copy of a variable in another method.
If value got changed in the one method, it wouldn't affect the
variable in another method.
Example: Passing Value Type Variables
static void ChangeValue(int x)
{
x = 200;

Console.WriteLine(x);
}

static void Main(string[] args)


{
int i = 100;

Console.WriteLine(i);

ChangeValue(i);

Console.WriteLine(i);
}

Output:

100

200

100

In the above example, variable i in the Main() method remains


unchanged even after we pass it to the ChangeValue() method and
change it's value there.
ADVERTISEMENT

Reference Type
Unlike value types, a reference type doesn't store its value directly.
Instead, it stores the address where the value is being stored. In
other words, a reference type contains a pointer to another memory
location that holds the data.
For example, consider the following string variable:
string s = "Hello World!!";

The following image shows how the system allocates the memory for
the above string variable.

Memory Allocation of
Reference Type Variable

As you can see in the above image, the system selects a random
location in memory (0x803200) for the variable s. The value of a
variable s is 0x600000, which is the memory address of the actual data
value. Thus, reference type stores the address of the location where
the actual value is stored instead of the value itself.

The followings are reference type data types:

 String
 Arrays (even if their elements are value types)
 Class
 Delegate

Passing Reference Type Variables


When you pass a reference type variable from one method to
another, it doesn't create a new copy; instead, it passes the
variable's address. So, If we change the value of a variable in a
method, it will also be reflected in the calling method.

Example: Passing Reference Type Variable


static void ChangeReferenceType(Student std2)
{
std2.StudentName = "Steve";
}

static void Main(string[] args)


{
Student std1 = new Student();
std1.StudentName = "Bill";

ChangeReferenceType(std1);

Console.WriteLine(std1.StudentName);
}

Output:

Steve

In the above example, we pass the Student object std1 to


the ChangeReferenceType() method. Here, it actually pass the memory
address of std1. Thus, when the ChangeReferenceType() method
changes StudentName, it is actually changing StudentName of std1 object,
because std1 and std2 are both pointing to the same address in
memory.

String is a reference type, but it is immutable. It means once we


assigned a value, it cannot be changed. If we change a string value,
then the compiler creates a new string object in the memory and
point a variable to the new memory location. So, passing a string
value to a function will create a new variable in the memory, and any
change in the value in the function will not be reflected in the original
value, as shown below.

Example: Passing String


static void ChangeReferenceType(string name)
{
name = "Steve";
}

static void Main(string[] args)


{
string name = "Bill";
ChangeReferenceType(name);

Console.WriteLine(name);
}

Output:

Bill

Null
The default value of a reference type variable is null when they are
not initialized. Null means not refering to any object.

Null Reference Type

A value type variable cannot be null because it holds value, not a


memory address. C# 2.0 introduced nullable types, using which you
can assign null to a value type variable or declare a value type
variable without assigning a value to it.

C# - Interface
In the human world, a contract between the two or more humans
binds them to act as per the contract. In the same way, an interface
includes the declarations of related functionalities. The entities that
implement the interface must provide the implementation of declared
functionalities.

In C#, an interface can be defined using the interface keyword. An


interface can contain declarations of methods, properties, indexers,
and events. However, it cannot contain fields, auto-implemented
properties.

The following interface declares some basic functionalities for the file
operations.

Example: C# Interface
interface IFile
{
void ReadFile();
void WriteFile(string text);
}

You cannot apply access modifiers to interface members. All the


members are public by default. If you use an access modifier in an
interface, then the C# compiler will give a compile-time error "The
modifier 'public/private/protected' is not valid for this item.". (Visual
Studio will show an error immediately without compilation.)

Example: Invalid Interface with Access Modifiers


interface IFile
{
protected void ReadFile(); //compile-time error
private void WriteFile(string text);//compile-time error
}

An interface can only contain declarations but not implementations.


The following will give a compile-time error.

Example: Invalid Interface with Implementation


interface IFile
{
void ReadFile();
void WriteFile(string text){
Console.Write(text); //error: cannot implement method
}
}

Implementing an Interface
A class or a Struct can implement one or more interfaces using colon
(:).
Syntax: <Class or Struct Name> : <Interface Name>

For example, the following class implements the IFile interface


implicitly.

Example: Interface Implementation


interface IFile
{
void ReadFile();
void WriteFile(string text);
}

class FileInfo : IFile


{
public void ReadFile()
{
Console.WriteLine("Reading File");
}

public void WriteFile(string text)


{
Console.WriteLine("Writing to file");
}
}

In the above example, the FileInfo class implements


the IFile interface. It defines all the members of the IFile interface
with public access modifier. The FileInfo class can also contain
members other than interface members.

Note:
Interface members must be implemented with the public modifier;
otherwise, the compiler will give compile-time errors.

You can create an object of the class and assign it to a variable of an


interface type, as shown below.

Example: Interface Implementation


public class Program
{
public static void Main()
{
IFile file1 = new FileInfo();
FileInfo file2 = new FileInfo();
file1.ReadFile();
file1.WriteFile("content");

file2.ReadFile();
file2.WriteFile("content");
}
}

Above, we created objects of the FileInfo class and assign it


to IFile type variable and FileInfo type variable. When interface
implemented implicitly, you can access IFile members with
the IFile type variables as well as FileInfo type variable.
ADVERTISEMENT

Explicit Implementation
An interface can be implemented explicitly
using <InterfaceName>.<MemberName>. Explicit implementation is useful
when class is implementing multiple interfaces; thereby, it is more
readable and eliminates the confusion. It is also useful if interfaces
have the same method name coincidently.

Note:
Do not use public modifier with an explicit implementation. It will give a
compile-time error.
Example: Explicit Implementation
interface IFile
{
void ReadFile();
void WriteFile(string text);
}

class FileInfo : IFile


{
void IFile.ReadFile()
{
Console.WriteLine("Reading File");
}

void IFile.WriteFile(string text)


{
Console.WriteLine("Writing to file");
}
}

When you implement an interface explicitly, you can access interface


members only through the instance of an interface type.

Example: Explicit Implementation


interface IFile
{
void ReadFile();
void WriteFile(string text);
}

class FileInfo : IFile


{
void IFile.ReadFile()
{
Console.WriteLine("Reading File");
}

void IFile.WriteFile(string text)


{
Console.WriteLine("Writing to file");
}

public void Search(string text)


{
Console.WriteLine("Searching in file");
}
}

public class Program


{
public static void Main()
{
IFile file1 = new FileInfo();
FileInfo file2 = new FileInfo();

file1.ReadFile();
file1.WriteFile("content");
//file1.Search("text to be searched")//compile-time error

file2.Search("text to be searched");
//file2.ReadFile(); //compile-time error
//file2.WriteFile("content"); //compile-time error
}
}

In the above example, file1 object can only access members


of IFile, and file2 can only access members of FileInfo class. This is
the limitation of explicit implementation.

Implementing Multiple Interfaces


A class or struct can implement multiple interfaces. It must provide
the implementation of all the members of all interfaces.

Example: Implement Multiple Interfaces


interface IFile
{
void ReadFile();
}

interface IBinaryFile
{
void OpenBinaryFile();
void ReadFile();
}

class FileInfo : IFile, IBinaryFile


{
void IFile.ReadFile()
{
Console.WriteLine("Reading Text File");
}

void IBinaryFile.OpenBinaryFile()
{
Console.WriteLine("Opening Binary File");
}

void IBinaryFile.ReadFile()
{
Console.WriteLine("Reading Binary File");
}

public void Search(string text)


{
Console.WriteLine("Searching in File");
}
}

public class Program


{
public static void Main()
{
IFile file1 = new FileInfo();
IBinaryFile file2 = new FileInfo();
FileInfo file3 = new FileInfo();

file1.ReadFile();
//file1.OpenBinaryFile(); //compile-time error
//file1.SearchFile("text to be searched"); //compile-time
error

file2.OpenBinaryFile();
file2.ReadFile();
//file2.SearchFile("text to be searched"); //compile-time
error

file3.Search("text to be searched");
//file3.ReadFile(); //compile-time error
//file3.OpenBinaryFile(); //compile-time error
}
}

Above, the FileInfo implements two


interfaces IFile and IBinaryFile explicitly. It is recommended to
implement interfaces explicitly when implementing multiple
interfaces to avoid confusion and more readability.

Points to Remember :

1. Interface can contain declarations of method, properties, indexers,


and events.
2. Interface cannot include private, protected, or internal members. All
the members are public by default.
3. Interface cannot contain fields, and auto-implemented properties.
4. A class or a struct can implement one or more interfaces implicitly or
explicitly. Use public modifier when implementing interface implicitly,
whereas don't use it in case of explicit implementation.
5. Implement interface explicitly using InterfaceName.MemberName.
6. An interface can inherit one or more interfaces.

C# Operators
Operators in C# are some special symbols that perform some action
on operands. In mathematics, the plus symbol (+) do the sum of the
left and right numbers. In the same way, C# includes various
operators for different types of operations.

The following example demonstrates the + operator in C#.

Example: + Operator
int x = 5 + 5;
int y = 10 + x;
int z = x + y;

In the above example, + operator adds two number literals and


assign the result to a variable. It also adds the values of two int
variables and assigns the result to a variable.

Some operators behave differently based on the type of the


operands. For example, + operator concatenates two strings.

Example: + Operator with Strings


string greet1 = "Hello " + "World!";
string greet2 = greeting + name;

Note:

There are two types of operators in C#, Unary operators and Binary operators.
Unary operators act on single operand, whereas binary operators act on two
operands (left-hand side and right-hand side operand of an operator).

C# includes the following categories of operators:


 Arithmetic operators
 Assignment operators
 Comparison operators
 Equality operators
 Boolean logical operators
 Betwise and shift operators
 Member access operators
 Type-cast operators
 Pointer related operators

Arithmetic Operators
The arithmetic operators perform arithmetic operations on all the
numeric type operands such as sbyte, byte, short, ushort, int, uint,
long, ulong, float, double, and decimal.

Operator Name Description Example

+ Addition Computes the sum of left and right operands. int x = 5 + 5; Try it

- Subtraction Subtract the right operand from the left operand int x = 5 - 1; Try it

* Multiplication Multiply left and right operand int x = 5 * 1; Try it

/ Division Divides the left operand by the right operand int x = 10 / 2; Try it

% Reminder Computes the remainder after dividing its left int x = 5 % 2; Try it
operand by its right operand

++ Unary increment Unary increment ++ operator increases its operand x++ Try it
by 1

-- Unary decrement Unary decrement -- operator decreases its operand x-- Try it
by 1

+ Unary plus Returns the value of operand +5 Try it

- Unary minus Computes the numeric negation of its operand. -5 Try it

Assignment Operators
The assignment operator = assigns its right had value to its left-hand
variable, property, or indexer. It can also be used with other
arithmetic, Boolean logical, and bitwise operators.
Operator Name Description Example

= Assignment Assigns its right had value to its left-hand variable, property or indexer. x = 10; Try
it

x op= y Compound assignment Short form of x =x op y where op = any arithmetic, Boolean logical, and x += 5; Try
bitwise operator. it

??= Null-coalescing C# 8 onwards, ??= assigns value of the right operand only if the left operand x ??= 5; Try
assignment is null it

Comparison Operators
Comparison operators compre two numeric operands and returns
true or false.

Operator Description Example

< Returns true if the right operand is less than the left operand x < y; Try it

> Returns true if the right operand is greater than the left operand x > y; Try it

<= Returns true if the right operand is less than or equal to the left operand x <= y Try it

>= Returns true if the right operand is greater than or equal to the left operand x >= y; Try it
ADVERTISEMENT

Equality Operators
The equality operator checks whether the two operands are equal or
not.

Operator Description Example

== Returns true if operands are equal otherwise false. x == y; Try it

!= Returns true if operands are not equal otherwise false. x != y; Try it

Boolean Logical Operators


The Boolean logical operators perform a logical operation on bool
operands.
Operator Description Example

! Reverses the bool result of bool expression. Returns false if result is true and returns true if result is !false Try
false. it

&& Computes the logical AND of its bool operands. Returns true both operands are true, otherwise x && y; Try
returns false. it

|| Computes the logical OR of its bool operands. Returns true when any one operand is true. x || y; Try
it

Operator Evaluation & Precedence


Evaluation of the operands in an expression starts from left to right.
If multiple operators are used in an expression, then the operators
with higher priority are evaluated before the operators with lower
priority.

The following table lists operators starting with the higher


precedence operators to lower precedence operators.

Operators Category

x.y, x?.y, x?[y], f(x), a[i], x++, x--, new, typeof, checked, unchecked, default, nameof, delegate, Primary
sizeof, stackalloc, x->y

+x, -x, !x, ~x, ++x, --x, ^x, (T)x, await, &x, *x, true and false Unary

x..y Range

x * y, x / y, x % y Multiplicative

x + y, x � y Additive

x << y, x >> y Shift

x < y, x > y, x <= y, x >= y, is, as Relational and type-testing

x == y, x != y Equality

x&y Boolean logical AND

x^y Boolean logical XOR

x|y Boolean logical OR

x && y Conditional AND


Operators Category

x || y Conditional OR

x ?? y Null-coalescing operator

c?t:f Conditional operator

x = y, x += y, x -= y, x *= y, x /= y, x %= y, x &= y, x |= y, x ^= y, x <<= y, x >>= y, x ??= y, => Assignment and lambda


declaration

The following example demonstrates operator precedence:

Example: Operator Precedence


int a = 5 + 3 * 3;
int b = 5 + 3 * 3 / 2;
int c = (5 + 3) * 3 / 2;
int d = (3 * 3) * (3 / 3 + 5);

C# - if, else if, else Statements


C# provides many decision-making statements that help the flow of the C# program
based on certain logical conditions. Here, you will learn about if, else if, else, and
nested if else statements to control the flow based on the conditions.

C# includes the following flavors of if statements:

1. if statement
2. else-if statement
3. else statement

C# if Statement
The if statement contains a boolean condition followed by a single or multi-line code
block to be executed. At runtime, if a boolean condition evaluates to true, then the code
block will be executed, otherwise not.

Syntax:
if(condition)
{
// code block to be executed when if condition evaluates to true
}
Example: if Statement
int i = 10, j = 20;

if (i < j)
{
Console.WriteLine("i is less than j");
}

if (i > j)
{
Console.WriteLine("i is greater than j");
}

Output:

i is less than j

In the above example, a boolean condition in the first if statement i < j evaluates to
true, so the C# compiler will execute the following code block. The
second if statement's condition i > j evaluates to false, so the compiler will not
execute its code block.

The conditional expression must return a boolean value, otherwise C# compiler will
give a compile-time error.

Example: Wrong if Statement


int i = 10, j = 20;

if (i + 1)
{
Console.WriteLine("i is less than j");
}

if (i + j)
{
Console.WriteLine("i is greater than j");
}

You can call a function in the if statement that returns a boolean value.
Example: Calling Function as Condition
static void Main(string[] args)
{
int i = 10, j = 20;

if (isGreater(i, j))
{
Console.WriteLine("i is less than j");
}

if (isGreater(j, i))
{
Console.WriteLine("j is greater than i");
}
}

static bool isGreater(int i, int j)


{
return i > j;
}

else if Statement
Multiple else if statements can be used after an if statement. It will only be executed
when the if condition evaluates to false. So, either if or one of the else if statements
can be executed, but not both.

Syntax:
if(condition1)
{
// code block to be executed when if condition1 evaluates to true
}
else if(condition2)
{
// code block to be executed when
// condition1 evaluates to flase
// condition2 evaluates to true
}
else if(condition3)
{
// code block to be executed when
// condition1 evaluates to flase
// condition2 evaluates to false
// condition3 evaluates to true
}

The following example demonstrates else if statements.

Example: else if Statements


int i = 10, j = 20;

if (i == j)
{
Console.WriteLine("i is equal to j");
}
else if (i > j)
{
Console.WriteLine("i is greater than j");
}
else if (i < j)
{
Console.WriteLine("i is less than j");
}

Output:

i is less than j

ADVERTISEMENT

else Statement
The else statement can come only after if or else if statement and can be used only
once in the if-else statements. The else statement cannot contain any condition and
will be executed when all the previous if and else if conditions evaluate to false.

Example: else Statement


int i = 20, j = 20;

if (i > j)
{
Console.WriteLine("i is greater than j");
}
else if (i < j)
{
Console.WriteLine("i is less than j");
}
else
{
Console.WriteLine("i is equal to j");
}

Output:

i is equal to j

Nested if Statements
C# supports if else statements inside another if else statements. This are called
nested if else statements. The nested if statements make the code more readable.

Syntax:
if(condition1)
{
if(condition2)
{
// code block to be executed when
// condition1 and condition2 evaluates to true
}
else if(condition3)
{
if(condition4)
{
// code block to be executed when
// only condition1, condition3, and condition4
evaluates to true
}
else if(condition5)
{
// code block to be executed when
// only condition1, condition3, and condition5
evaluates to true
}
else
{
// code block to be executed when
// condition1, and condition3 evaluates to true
// condition4 and condition5 evaluates to false
}
}
}

The following example demonstrates the nested if else statements.

Example: Nested if else statements


int i = 10, j = 20;

if (i != j)
{
if (i < j)
{
Console.WriteLine("i is less than j");
}
else if (i > j)
{
Console.WriteLine("i is greater than j");
}
}
else
Console.WriteLine("i is equal to j");

Output:

i is less than j

Use Ternary operator ?: instead of a simple if else statement.

C# - Ternary Operator ?:

C# includes a decision-making operator ?: which is called the


conditional operator or ternary operator. It is the short form of the if
else conditions.

Syntax:
condition ? statement 1 : statement 2

The ternary operator starts with a boolean condition. If this condition


evaluates to true then it will execute the first statement after ?,
otherwise the second statement after : will be executed.

The following example demonstrates the ternary operator.

Example: Ternary operator


int x = 20, y = 10;

var result = x > y ? "x is greater than y" : "x is less than y";

Console.WriteLine(result);

output:

x is greater than y

Above, a conditional expression x > y returns true, so the first


statement after ? will be execute.

The following executes the second statement.

Example: Ternary operator


int x = 10, y = 100;

var result = x > y ? "x is greater than y" : "x is less than y";

Console.WriteLine(result);
output:

x is less than y

Thus, a ternary operator is short form of if else statement. The


above example can be re-write using if else condition, as shown
below.

Example: Ternary operator replaces if statement


int x = 10, y = 100;

if (x > y)
Console.WriteLine("x is greater than y");
else
Console.WriteLine("x is less than y");

output:

x is greater than y

Nested Ternary Operator


Nested ternary operators are possible by including a conditional
expression as a second statement.

Example: Nested ?:
int x = 10, y = 100;

string result = x > y ? "x is greater than y" :


x < y ? "x is less than y" :
x == y ? "x is equal to y" : "No result";

Console.WriteLine(result);

The ternary operator is right-associative. The expression a ? b : c ?


d : e is evaluated as a ? b : (c ? d : e), not as (a ? b : c) ? d : e.

Example: Nested ?:
var x = 2, y = 10;

var result = x * 3 > y ? x : y > z? y : z;


Console.WriteLine(result);

C# - Switch Statement

The switch statement can be used instead of if else statement when


you want to test a variable against three or more conditions. Here,
you will learn about the switch statement and how to use it efficiently
in the C# program.
The following is the general syntax of the switch statement.

Syntax:
switch(match expression/variable)
{
case constant-value:
statement(s) to be executed;
break;
default:
statement(s) to be executed;
break;
}

The switch statement starts with the switch keyword that contains a
match expression or a variable in the bracket switch(match
expression). The result of this match expression or a variable will be
tested against conditions specified as cases, inside the curly braces {
}. A case must be specified with the unique constant value and ends
with the colon :. Each case includes one or more statements to be
executed. The case will be executed if a constant value and the value
of a match expression/variable are equal. The switch statement can
also contain an optional default label. The default label will be
executed if no cases executed. The break, return, or goto keyword is
used to exit the program control from a switch case.

The following example demonstrates a simple switch statement.

Example: C# Switch Statement


int x = 10;

switch (x)
{
case 5:
Console.WriteLine("Value of x is 5");
break;
case 10:
Console.WriteLine("Value of x is 10");
break;
case 15:
Console.WriteLine("Value of x is 15");
break;
default:
Console.WriteLine("Unknown value");
break;
}

Output:

Value of x is 10

Above, the switch(x) statement includes a variable x whose value will


be matched with the value of each case value. The
above switch statement contains three cases with constant values 5,
10, and 15. It also contains the default label, which will be executed
if none of the case value match with the switch variable/expression.
Each case starts after : and includes one statement to be executed.
The value of x matches with the second case case 10:, so the output
would be Value of x is 10.

Note:
The switch statement can include any non-null expression that returns a
value of type: char, string, bool, int, or enum.

The switch statement can also include an expression whose result will
be tested against each case at runtime.

Example: C# Switch Statement


int x = 125;

switch (x % 2)
{
case 0:
Console.WriteLine($"{x} is an even value");
break;
case 1:
Console.WriteLine($"{x} is an odd Value");
break;
}

Output:

125 is an odd value


ADVERTISEMENT

Switch Case
The switch cases must be unique constant values. It can be bool,
char, string, integer, enum, or corresponding nullable type.

Note
C# 7.0 onward, switch cases can include non-unique values. In this case,
the first matching case will be executed.

Consider the following example of a simple switch statement.

Example: switch statement


string statementType = "switch";

switch (statementType)
{
case "if.else":
Console.WriteLine("if...else statement");
break;
case "ternary":
Console.WriteLine("Ternary operator");
break;
case "switch":
Console.WriteLine("switch statement");
break;
}

Output:

switch statement

Multiple cases can be combined to execute the same statements.

Example: C# Combined Switch Cases


int x = 5;

switch (x)
{
case 1:
Console.WriteLine("x = 1");
break;
case 2:
Console.WriteLine("x = 2");
break;
case 4:
case 5:
Console.WriteLine("x = 4 or x = 5");
break;
default:
Console.WriteLine("x > 5");
break;
}

Each case must exit the case explicitly by


using break, return, goto statement, or some other way, making sure
the program control exits a case and cannot fall through to the
default case.

The following use the return keyword.

Example: return in Switch Case


static void Main(string[] args)
{
int x = 125;
Console.Write( isOdd(x)? "Even value" : "Odd value");
}

static bool isOdd(int i, int j)


{
switch (x % 2)
{
case 0:
return true;
case 1:
return false;
default:
return false;
}

return false;
}

Output:

Odd value

The switch cases without break, return, or goto statement or with


the same constant values would give a compile-time error.
Example: C# Switch Statement
int x = 1;

switch (x)
{
case 0:
Console.WriteLine($"{x} is even value");
break;
case 1:
Console.WriteLine($"{x} is odd Value");
break;
case 1: // Error - Control cannot fall through from one case label
('case 1:') to another
Console.WriteLine($"{x} is odd Value");
defaut:
Console.WriteLine($"{x} is odd Value");
break;
}

Nested Switch Statements


A switch statement can be used inside another switch statement.

Example: Nested switch statements


int j = 5;

switch (j)
{
case 5:
Console.WriteLine(5);
switch (j - 1)
{
case 4:
Console.WriteLine(4);
switch (j - 2)
{
case 3:
Console.WriteLine(3);
break;
}
break;
}
break;
case 10:
Console.WriteLine(10);
break;
case 15:
Console.WriteLine(15);
break;
default:
Console.WriteLine(100);
break;
}

Output:

Points to Remember :

1. The switch statement is an alternative to if else statement.


2. The switch statement tests a match expression/variable against a set
of constants specified as cases.
3. The switch case must include break, return, goto keyword to exit a
case.
4. The switch can include one optional default label, which will be
executed when no case executed.
5. C# compiler will give errors on missing :, constant value with cases,
exit from a case.
6. C# 7.0 onward, switch cases can include non-unique values. In this
case, the first matching case will be executed.

C# for Loop

Here, you will learn how to execute a statement or code block


multiple times using the for loop, structure of the for loop, nested for
loops, and how to exit from the for loop.
The for keyword indicates a loop in C#. The for loop executes a block
of statements repeatedly until the specified condition returns false.

Syntax:
for (initializer; condition; iterator)
{
//code block
}

The for loop contains the following three optional sections, separated
by a semicolon:

Initializer: The initializer section is used to initialize a variable that


will be local to a for loop and cannot be accessed outside loop. It can
also be zero or more assignment statements, method call, increment,
or decrement expression e.g., ++i or i++, and await expression.

Condition: The condition is a boolean expression that will return


either true or false. If an expression evaluates to true, then it will
execute the loop again; otherwise, the loop is exited.

Iterator: The iterator defines the incremental or decremental of the


loop variable.

The following for loop executes a code block 10 times.

Example: for Loop


for(int i = 0; i < 10; i++)
{
Console.WriteLine("Value of i: {0}", i);
}

Output:

Value of i: 0

Value of i: 1

Value of i: 2
Value of i: 3

Value of i: 4

Value of i: 5

Value of i: 6

Value of i: 7

Value of i: 8

Value of i: 9

In the above example, int i = 0 is an initializer where we define an int


variable i and initialize it with 0. The second section is the condition
expression i < 10, if this condition returns true then it will execute a
code block. After executing the code block, it will go to the third
section, iterator. The i++ is an incremental statement that increases
the value of a loop variable i by 1. Now, it will check the conditional
expression again and repeat the same thing until conditional
expression returns false. The below figure illustrates the execution
steps of the for loop.

The below figure illustrates the execution steps of the for loop.

for Loop Execution


Steps
If a code block only contains a single statement, then you don't need
to wrap it inside curly brackets { }, as shown below.

Example: for Loop


for(int i = 0; i < 10; i++)
Console.WriteLine("Value of i: {0}", i);

An Initializer, condition, and iterator sections are optional. You can


initialize a variable before for loop, and condition and iterator can be
defined inside a code block, as shown below.

Example: for loop C#


int i = 0;

for(;;)
{
if (i < 10)
{
Console.WriteLine("Value of i: {0}", i);
i++;
}
else
break;
}

Output:

Value of i: 0

Value of i: 1

Value of i: 2

Value of i: 3

Value of i: 4
Value of i: 5

Value of i: 6

Value of i: 7

Value of i: 8

Value of i: 9

Since all three sections are optional in the for loop, be careful in
defining a condition and iterator. Otherwise, it will be an infinite loop
that will never end the loop.

Example: Infinite for Loop


for ( ; ; )
{
Console.Write(1);
}
Output:

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.....

The control variable for the for loop can be of any numeric data type,
such as double, decimal, etc.

Example: Decimal for Loop


for (double d = 1.01D; d < 1.10; d+= 0.01D)
{
Console.WriteLine("Value of i: {0}", d);
}

Output:
Value of i: 1.01

Value of i: 1.02

Value of i: 1.03

Value of i: 1.04

Value of i: 1.05

Value of i: 1.06

Value of i: 1.07

Value of i: 1.08

Value of i: 1.09

The steps part in a for loop can either increase or decrease the value
of a variable.

Example: Reverse for Loop


for(int i = 10; i > 0; i--)
{
Console.WriteLine("Value of i: {0}", i);
}

Output:

Value of i: 10

Value of i: 9
Value of i: 8

Value of i: 7

Value of i: 6

Value of i: 5

Value of i: 4

Value of i: 3

Value of i: 2

Value of i: 1

ADVERTISEMENT

Exit the for Loop


You can also exit from a for loop by using the break keyword.

Example: break in for loop


for (int i = 0; i < 10; i++)
{
if( i == 5 )
break;

Console.WriteLine("Value of i: {0}", i);


}

Output:
Value of i: 0

Value of i: 1

Value of i: 2

Value of i: 3

Value of i: 4

Multiple Expressions
A for loop can also include multiple initializer and iterator statements
separated by comma, as shown below.

Example: Multiple Expressions


for (int i = 0, j = 0; i+j < 5; i++, j++)
{
Console.WriteLine("Value of i: {0}, J: {1} ", i,j);
}

Output:

Value of i: 0, J: 0

Value of i: 1, J: 1

Value of i: 2, J: 2

A for loop can also contain statements as an initializer and iterator.

Example: Initializer and Iterator Statements


int i = 0, j = 5;
for (Console.WriteLine($"Initializer: i={i}, j={j}");
i++ < j--;
Console.WriteLine($"Iterator: i={i}, j={j}"))
{
}

Output:

Initializer: i=0, j=5

Iterator: i=1, j=4

Iterator: i=2, j=3

Iterator: i=3, j=2

Nested for Loop


C# allows a for loop inside another for loop.

Example: Nested for loop


for (int i = 0; i < 2; i++)
{
for(int j =i; j < 4; j++)
Console.WriteLine("Value of i: {0}, J: {1} ", i,j);
}

Output:

Value of i: 0, J: 0

Value of i: 0, J: 1

Value of i: 0, J: 2
Value of i: 0, J: 3

Value of i: 1, J: 1

Value of i: 1, J: 2

Value of i: 1, J: 3

C# - while Loop
C# provides the while loop to repeatedly execute a block of code as
long as the specified condition returns false.

Syntax:
While(condition)
{
//code block
}

The while loop starts with the while keyword, and it must include a
boolean conditional expression inside brackets that returns either
true or false. It executes the code block until the specified conditional
expression returns false.

The for loop contains the initialization and increment/decrement


parts. When using the while loop, initialization should be done before
the loop starts, and increment or decrement steps should be inside
the loop.

Example: C# while Loop


int i = 0; // initialization

while (i < 10) // condition


{
Console.WriteLine("i = {0}", i);
i++; // increment
}

Output:

i = 0

i = 1

i = 2

i = 3

i = 4

i = 5

i = 6

i = 7

i = 8

i = 9

Above, a while loop includes an expression i < 10. Inside a while loop,
the value of i increased to 1 using i++. The above while loop will be
executed when the value of i equals to 10 and a condition i <
10 returns false.

Use the break or return keyword to exit from a while loop on some
condition, as shown below.
Example: Exit from the while Loop
int i = 0;

while (true)
{
Console.WriteLine("i = {0}", i);

i++;

if (i > 10)
break;
}

Ensure that the conditional expression evaluates to false or exit from


the while loop on some condition to avoid an infinite loop. The
following loop is missing an appropriate condition or break the loop,
which makes it an infinite while loop.

Example: Infinite While Loop


int i = 0;

while (i > 0)
{
Console.WriteLine("i = {0}", i);
i++;
}

Nested while Loop


C# allows while loops inside another while loop, as shown below.
However, it is not recommended to use nested while loop because it
makes it hard to debug and maintain.

Example: Nested while Loop


int i = 0, j = 1;

while (i < 2)
{
Console.WriteLine("i = {0}", i);
i++;
while (j < 2)
{
Console.WriteLine("j = {0}", j);
j++;
}
}

Output:

i = 0

j = 1

i = 1

C# - do while Loop
The do while loop is the same as while loop except that it executes the
code block at least once.

Syntax:
do
{
//code block

} while(condition);

The do-while loop starts with the do keyword followed by a code block
and a boolean expression with the while keyword. The do while loop
stops execution exits when a boolean condition evaluates to false.
Because the while(condition) specified at the end of the block, it
certainly executes the code block at least once.

Example: do-while Loop


int i = 0;

do
{
Console.WriteLine("i = {0}", i);
i++;

} while (i < 5);

Output:

i = 0

i = 1

i = 2

i = 3

i = 4

Specify initialization out of the loop and increment/decrement


counter inside do while loop.

Use break or return to exit from the do while loop.

Example: Exit from the do-while Loop


int i = 0;

do
{
Console.WriteLine("i = {0}", i);
i++;

if (i > 5)
break;

} while (i < 10);

Output:
i = 0

i = 1

i = 2

i = 3

i = 4

i = 5

Nested do-while
The do-while loop can be used inside another do-while loop.

Example: Nested do-while Loop


int i = 0;

do
{
Console.WriteLine("Value of i: {0}", i);
int j = i;

i++;

do
{
Console.WriteLine("Value of j: {0}", j);
j++;
} while (j < 2);

} while (i < 2);

Output:
i = 0

j = 0

j = 1

i = 1

j = 1

C# - Partial Classes and Methods


In C#, you can split the implementation of a class, a struct, a
method, or an interface in multiple .cs files using the partial keyword.
The compiler will combine all the implementation from
multiple .cs files when the program is compiled.

Consider the following EmployeeProps.cs and EmployeeMethods.cs files that


contain the Employee class.

EmployeeProps.cs
public partial class Employee
{
public int EmpId { get; set; }
public string Name { get; set; }
}
EmployeeMethods.cs
public partial class Employee
{
//constructor
public Employee(int id, string name){
this.EmpId = id;
this.Name = name;
}

public void DisplayEmpInfo() {


Console.WriteLine(this.EmpId + " " this.Name);
}
}

Above, EmployeeProps.cs contains properties of the Employee class,


and EmployeeMethods.cs contains all the methods of the Employee class.
These will be compiled as one Employee class.

Example: Combined Class


public class Employee
{
public int EmpId { get; set; }
public string Name { get; set; }

public Employee(int id, string name){


this.EmpId = id;
this.Name = name;
}

public void DisplayEmpInfo(){


Console.WriteLine(this.EmpId + " " this.Name );
}
}

Rules for Partial Classes


 All the partial class definitions must be in the same assembly and
namespace.
 All the parts must have the same accessibility like public or private, etc.
 If any part is declared abstract, sealed or base type then the whole class is
declared of the same type.
 Different parts can have different base types and so the final class will inherit
all the base types.
 The Partial modifier can only appear immediately before the
keywords class, struct, or interface.
 Nested partial types are allowed.

Partial Methods
Partial classes or structs can contain a method that split into two
separate .cs files of the partial class or struct. One of the two .cs files
must contain a signature of the method, and other file can contain an
optional implementation of the partial method. Both declaration and
implementation of a method must have the partial keyword.

EmployeeProps.cs
public partial class Employee
{
public Employee() {
GenerateEmpId();
}
public int EmpId { get; set; }
public string Name { get; set; }

partial void GenerateEmployeeId();

}
EmployeeMethods.cs
public partial class Employee
{
partial void GenerateEmployeeId()
{
this.EmpId = random();
}
}

Above, EmployeeProps.cs contains the declaration of the partial


method GenerateEmployeeId() which is being used in the
constructor. EmployeeMethods.cs contains the implementation of
the GenerateEmployeeId() method. The following demonstrates creates an
object the Employee class which used the partial method.

EmployeeMethods.cs
class Program
{
static void Main(string[] args)
{
var emp = new Employee();
Console.WriteLine(emp.EmpId); // prints genereted id

Console.ReadLine();
}
}
Rules for Partial Methods
 Partial methods must use the partial keyword and must return void.
 Partial methods can have in or ref but not out parameters.
 Partial methods are implicitly private methods, so cannot be virtual.
 Partial methods can be static methods.
 Partial methods can be generic.

C# - Static Class, Methods, Constructors,


Fields

In C#, static means something which cannot be instantiated. You


cannot create an object of a static class and cannot access static
members using an object.

C# classes, variables, methods, properties, operators, events, and


constructors can be defined as static using the static modifier
keyword.

Static Class
Apply the static modifier before the class name and after the access
modifier to make a class static. The following defines a static class
with static fields and methods.

Example: C# Static Class


public static class Calculator
{
private static int _resultStorage = 0;

public static string Type = "Arithmetic";

public static int Sum(int num1, int num2)


{
return num1 + num2;
}
public static void Store(int result)
{
_resultStorage = result;
}
}

Above, the Calculator class is a static. All the members of it are also
static.

You cannot create an object of the static class; therefore the


members of the static class can be accessed directly using a class
name like ClassName.MemberName, as shown below.

Example: Accessing Static Members


class Program
{
static void Main(string[] args)
{
var result = Calculator.Sum(10, 25); // calling static method
Calculator.Store(result);

var calcType = Calculator.Type; // accessing static variable


Calculator.Type = "Scientific"; // assign value to static
variable
}
}

Rules for Static Class


1. Static classes cannot be instantiated.
2. All the members of a static class must be static; otherwise the compiler will
give an error.
3. A static class can contain static variables, static methods, static properties,
static operators, static events, and static constructors.
4. A static class cannot contain instance members and constructors.
5. Indexers and destructors cannot be static
6. var cannot be used to define static members. You must specify a type of
member explicitly after the static keyword.
7. Static classes are sealed class and therefore, cannot be inherited.
8. A static class cannot inherit from other classes.
9. Static class members can be accessed using ClassName.MemberName.
10. A static class remains in memory for the lifetime of the application
domain in which your program resides.
Static Members in Non-static Class
The normal class (non-static class) can contain one or more static
methods, fields, properties, events and other non-static members.

It is more practical to define a non-static class with some static


members, than to declare an entire class as static.

Static Fields
Static fields in a non-static class can be defined using
the static keyword.

Static fields of a non-static class is shared across all the instances.


So, changes done by one instance would reflect in others.

Example: Shared Static Fields


public class StopWatch
{
public static int InstanceCounter = 0;
// instance constructor
public StopWatch()
{
}
}

class Program
{
static void Main(string[] args)
{
StopWatch sw1 = new StopWatch();
StopWatch sw2 = new StopWatch();
Console.WriteLine(StopWatch.NoOfInstances); //2

StopWatch sw3 = new StopWatch();


StopWatch sw4 = new StopWatch();
Console.WriteLine(StopWatch.NoOfInstances);//4
}
}

ADVERTISEMENT
Static Methods
You can define one or more static methods in a non-static class.
Static methods can be called without creating an object. You cannot
call static methods using an object of the non-static class.

The static methods can only call other static methods and access
static members. You cannot access non-static members of the class
in the static methods.

Example: Static Method


class Program
{
static int counter = 0;
string name = "Demo Program";

static void Main(string[] args)


{
counter++; // can access static fields
Display("Hello World!"); // can call static methods

name = "New Demo Program"; //Error: cannot access non-static


members
SetRootFolder("C:\MyProgram"); //Error: cannot call non-static
method
}

static void Display(string text)


{
Console.WriteLine(text);
}

public void SetRootFolder(string path) { }


}

Rules for Static Methods


1. Static methods can be defined using the static keyword before a return
type and after an access modifier.
2. Static methods can be overloaded but cannot be overridden.
3. Static methods can contain local static variables.
4. Static methods cannot access or call non-static variables unless they are
explicitly passed as parameters.
Static Constructors
A non-static class can contain a parameterless static constructor. It
can be defined with the static keyword and without access modifiers
like public, private, and protected.

The following example demonstrates the difference between static


constructor and instance constructor.

Example: Static Constructor vs Instance Constructor


public class StopWatch
{
// static constructor
static StopWatch()
{
Console.WriteLine("Static constructor called");
}

// instance constructor
public StopWatch()
{
Console.WriteLine("Instance constructor called");
}

// static method
public static void DisplayInfo()
{
Console.WriteLine("DisplayInfo called");
}

// instance method
public void Start() { }

// instance method
public void Stop() { }
}

Above, the non-static class StopWatch contains a static constructor and


also a non-static constructor.
The static constructor is called only once whenever the static method
is used or creating an instance for the first time. The following
example shows that the static constructor gets called when the static
method called for the first time. Calling the static method second
time onwards won't call a static constructor.

Example: Static Constructor Execution


StopWatch.DisplayInfo(); // static constructor called here
StopWatch.DisplayInfo(); // none of the constructors called here
Output:

Static constructor called.

DisplayInfo called

DisplayInfo called

The following example shows that the static constructor gets called
when you create an instance for the first time.

Example: Static Constructor Execution


StopWatch sw1 = new StopWatch(); // First static constructor and then
instance constructor called
StopWatch sw2 = new StopWatch();// only instance constructor called
StopWatch.DisplayInfo();
Output:

Static constructor called

instance constructor called

instance constructor called

DisplayInfo called
Rules for Static Constructors
1. The static constructor is defined using the static keyword and without using
access modifiers public, private, or protected.
2. A non-static class can contain one parameterless static constructor.
Parameterized static constructors are not allowed.
3. Static constructor will be executed only once in the lifetime. So, you cannot
determine when it will get called in an application if a class is being used at
multiple places.
4. A static constructor can only access static members. It cannot contain or
access instance members.

Learn more about Static class and static constructor.

Note:

Static members are stored in a special area in the memory called High-Frequency
Heap. Static members of non-static classes are shared across all the instances of
the class. So, the changes done by one instance will be reflected in all the other
instances.

C# Arrays

A variable is used to store a literal value, whereas an array is used to


store multiple literal values.

An array is the data structure that stores a fixed number of literal


values (elements) of the same data type. Array elements are stored
contiguously in the memory.

In C#, an array can be of three types: single-dimensional,


multidimensional, and jagged array. Here you will learn about the
single-dimensional array.

The following figure illustrates an array representation.


Array Representation

Array Declaration and Initialization


An array can be declared using by specifying the type of its elements
with square brackets.

Example: Array Declaration


int[] evenNums; // integer array

string[] cities; // string array

The following declares and adds values into an array in a single


statement.

Example: Array Declaration & Initialization


int[] evenNums = new int[5]{ 2, 4, 6, 8, 10 };

string[] cities = new string[3]{ "Mumbai", "London", "New York" };

Above, evenNums array can store up to five integers. The number 5 in


the square brackets new int[5] specifies the size of an array. In the
same way, the size of cities array is three. Array elements are added
in a comma-separated list inside curly braces { }.

Arrays type variables can be declared using var without square


brackets.

Example: Array Declaration using var


var evenNums = new int[]{ 2, 4, 6, 8, 10};

var cities = new string[]{ "Mumbai", "London", "New York" };


If you are adding array elements at the time of declaration, then size
is optional. The compiler will infer its size based on the number of
elements inside curly braces, as shown below.

Example: Short Syntax of Array Declaration


int[] evenNums = { 2, 4, 6, 8, 10};

string[] cities = { "Mumbai", "London", "New York" }

The following example demonstrate invalid array declarations.

Example: Invalid Array Creation


//must specify the size
int[] evenNums = new int[];

//number of elements must be equal to the specified size


int[] evenNums = new int[5] { 2, 4 };

//cannot use var with array initializer


var evenNums = { 2, 4, 6, 8, 10};

Late Initialization
It is not necessary to declare and initialize an array in a single
statement. You can first declare an array then initialize it later on
using the new operator.

Example: Late Initialization


int[] evenNums;

evenNums = new int[5];


// or
evenNums = new int[]{ 2, 4, 6, 8, 10 };
ADVERTISEMENT

Accessing Array Elements


Array elements can be accessed using an index. An index is a
number associated with each array element, starting with index 0
and ending with array size - 1.
The following example add/update and retrieve array elements using
indexes.

Example: Access Array Elements using Indexes


int[] evenNums = new int[5];
evenNums[0] = 2;
evenNums[1] = 4;
//evenNums[6] = 12; //Throws run-time exception IndexOutOfRange

Console.WriteLine(evenNums[0]); //prints 2
Console.WriteLine(evenNums[1]); //prints 4

Note that trying to add more elements than its specified size will
result in IndexOutOfRangeException.

Accessing Array using for Loop


Use the for loop to access array elements. Use the length property of
an array in conditional expression of the for loop.

Example: Accessing Array Elements using for Loop


int[] evenNums = { 2, 4, 6, 8, 10 };

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


Console.WriteLine(evenNums[i]);

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


evenNums[i] = evenNums[i] + 10; // update the value of each
element by 10

Accessing Array using foreach Loop


Use foreach loop to read values of an array elements without using
index.

Example: Accessing Array using foreach Loop


int[] evenNums = { 2, 4, 6, 8, 10};
string[] cities = { "Mumbai", "London", "New York" };
foreach(var item in evenNums)
Console.WriteLine(item);

foreach(var city in cities)


Console.WriteLine(city);

LINQ Methods
All the arrays in C# are derived from an abstract base
class System.Array.

The Array class implements the IEnumerable interface, so you can LINQ
extension methods such as Max(), Min(), Sum(), reverse(), etc. See the list
of all extension methods here.

Example: LINQ Methods


int[] nums = new int[5]{ 10, 15, 16, 8, 6 };

nums.Max(); // returns 16
nums.Min(); // returns 6
nums.Sum(); // returns 55
nums.Average(); // returns 55

The System.Array class also includes methods for creating,


manipulating, searching, and sorting arrays. See list of all Array
methods here.

Example: Array Methods


int[] nums = new int[5]{ 10, 15, 16, 8, 6 };

Array.Sort(nums); // sorts array


Array.Reverse(nums); // sorts array in descending order
Array.ForEach(nums, n => Console.WriteLine(n)); // iterates array
Array.BinarySearch(nums, 5);// binary search
Passing Array as Argument
An array can be passed as an argument to a method parameter.
Arrays are reference types, so the method can change the value of
the array elements.

Example: Passing Array as Argument


public static void Main(){
int[] nums = { 1, 2, 3, 4, 5 };

UpdateArray(nums);

foreach(var item in nums)


Console.WriteLine(item);
}

public static void UpdateArray(int[] arr)


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

C# - Multidimensional Arrays
C# supports multidimensional arrays up to 32 dimensions. The
multidimensional array can be declared by adding commas in the
square brackets. For example, [,] declares two-dimensional array,
[, ,] declares three-dimensional array, [, , ,] declares four-
dimensional array, and so on. So, in a multidimensional array, no of
commas = No of Dimensions - 1.

The following declares multidimensional arrays.

Example: Multidimensional Arrays


int[,] arr2d; // two-dimensional array
int[, ,] arr3d; // three-dimensional array
int[, , ,] arr4d ; // four-dimensional array
int[, , , ,] arr5d; // five-dimensional array
Let's understand the two-dimensional array. The following initializes
the two-dimensional array.

Example: two-dimensional Array


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

// or
int[,] arr2d = {
{1, 2},
{3, 4},
{5, 6}
};

In the above example of a two-dimensional array, [3, 2] defines the


no of rows and columns. The first rank denotes the no of rows, and
the second rank defines no of columns. The following figure
illustrates the two-dimensional array divided into rows and columns.

Two-dimensional
Array

The following access values of the two-dimensional array.

Example: Access two-dimensional Array


int[,] arr2d = new int[3,2]{
{1, 2},
{3, 4},
{5, 6}
};
arr2d[0, 0]; //returns 1
arr2d[0, 1]; //returns 2
arr2d[1, 0]; //returns 3
arr2d[1, 1]; //returns 4
arr2d[2, 0]; //returns 5
arr2d[2, 1]; //returns 6
//arr2d[3, 0]; //throws run-time error as there is no 4th row

In the above example, the value of a two-dimensional array can be


accessed by index no of row and column as [row index, column
index]. So, [0, 0] returns the value of the first row and first column
and [1, 1] returns the value from the second row and second
column.

Now, let's understand the three-dimensional array. The following


declares and initializes three-dimensional arrays.

Example: Three-dimensional Array


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

int[, ,] arr3d2 = new int[2, 2, 2]{


{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} }
};

int[, ,] arr3d3 = new int[2, 2, 3]{


{ { 1, 2, 3}, {4, 5, 6} },
{ { 7, 8, 9}, {10, 11, 12} }
};

arr3d2[0, 0, 0]; // returns 1


arr3d2[0, 0, 1]; // returns 2
arr3d2[0, 1, 0]; // returns 3
arr3d2[0, 1, 1]; // returns 4
arr3d2[1, 0, 0]; // returns 5
arr3d2[1, 0, 1]; // returns 6
arr3d2[1, 1, 0]; // returns 7
arr3d2[1, 1, 1]; // returns 8
As you can see in the above example, [1, 2, 2] of arr3d1 specifies
that it will contain one row of two-dimensional array [2,
2]. arr3d2 specifies dimensions [2, 2, 2], which indicates that it
includes two rows of two-dimensional array of [2, 2]. Thus, the first
rank indicates the number of rows of inner two-dimensional arrays.

Now, consider the following four-dimensional array.

Example: Four-dimensional Array


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

arr4d1[0, 0, 0, 0]; // returns 1


arr4d1[0, 0, 0, 1]; // returns 2
arr4d1[0, 0, 1, 0]; // returns 3
arr4d1[0, 0, 1, 1]; // returns 4

int[,,,] arr4d2 = new int[1, 2, 2, 2]{


{
{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} }
}
};

arr4d2[0, 0, 0, 0]; // returns 1


arr4d2[0, 0, 0, 1]; // returns 2
arr4d2[0, 0, 1, 0]; // returns 3
arr4d2[0, 0, 1, 1]; // returns 4
arr4d2[0, 1, 0, 0]; // returns 5
arr4d2[0, 1, 0, 1]; // returns 6
arr4d2[0, 1, 1, 0]; // returns 7
arr4d2[0, 1, 1, 1]; // returns 8

In the above example, the four-dimensional array arr4d1 specifies [1,


1, 2, 2], which indicates that it includes one row of the three-
dimensional array.

In the same way, you can declare and initialize five-dimensional, six-
dimensional array, and up to 32-dimensional arrays in C#.
C# Jagged Arrays: An Array of Array
A jagged array is an array of array. Jagged arrays store arrays
instead of literal values.

A jagged array is initialized with two square brackets [][]. The first
bracket specifies the size of an array, and the second bracket
specifies the dimensions of the array which is going to be stored.

The following example declares jagged arrays.

Example: Jagged Arrays


int[][] jArray1 = new int[2][]; // can include two single-dimensional
arrays
int[][,] jArray2 = new int[3][,]; // can include three two-dimensional
arrays

In the above example, jArray1 can store up to two single-dimensional


arrays. jArray2 can store up to three two-dimensional, arrays [,]
specifies the two-dimensional array.

Example: Jagged Array


int[][] jArray = new int[2][];

jArray[0] = new int[3]{1, 2, 3};

jArray[1] = new int[4]{4, 5, 6, 7 };

You can also initialize a jagged array upon declaration like the below.

Example: Jagged Array


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

new int[4]{4, 5, 6, 7}
};

jArray[0][0]; //returns 1
jArray[0][1]; //returns 2
jArray[0][2]; //returns 3
jArray[1][0]; //returns 4
jArray[1][1]; //returns 5
jArray[1][2]; //returns 6
jArray[1][3]; //returns 7

You can access a jagged array using two for loops, as shown below.

Example: Jagged Array


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

new int[4]{4, 5, 6, 7}
};

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


{
for(int j=0; j < (jArray[i]).Length; j++)
Console.WriteLine(jArray[i][j]);
}

The following jagged array stores two-dimensional arrays where the


second bracket [,] indicates the two-dimensional array.

Example: Jagged Array


int[][,] jArray = new int[2][,];

jArray[0] = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };


jArray[1] = new int[2, 2] { { 7, 8 }, { 9, 10 } };

jArray[0][1, 1]; //returns 4

jArray[1][1, 0]; //returns 9

jArray[1][1, 1]; //returns 10

If you add one more bracket then it will be array of array of arry.

Example: Jagged Array


int[][][] intJaggedArray = new int[2][][]
{
new int[2][]
{
new int[3] { 1, 2, 3},
new int[2] { 4, 5}
},
new int[1][]
{
new int[3] { 7, 8, 9}
}
};

Console.WriteLine(intJaggedArray[0][0][0]); // 1

Console.WriteLine(intJaggedArray[0][1][1]); // 5

Console.WriteLine(intJaggedArray[1][0][2]); // 9

In the above example of a jagged array, three brackets [][][] means


an array of array of array. So, intJaggedArray will contain two
elements, which means two arrays. Now, each of these arrays also
contains an array (single-dimension). intJaggedArray[0][0][0] points
to the first element of first inner array. intJaggedArray[1][0][2] points
to the third element of the second inner array. The following figure
illustrates this.

Jagged Array
ASP.NET Core Tutorials
ASP.NET Core is a new version of ASP.NET by Microsoft. It is an
open-source web framework which can be run on Windows, Mac, or
Linux.

These tutorials will help you understand ASP.NET Core web


application step by step. Tutorials are broken down into chapters,
where each chapter contains a number of related topics that are
packed with easy to understand explanations and real-world
examples.

These tutorials are designed for beginners and professionals who


want learn how to build ASP.NET Core web applications step by step.

Prerequisites
Basic knowledge of C#, HTML, Visual Studio, and Object Oriented
Programming is required.

.NET Core Overview


.NET Core is a new version of .NET Framework, which is a free, open-
source, general-purpose development platform maintained by
Microsoft. It is a cross-platform framework that runs on Windows,
macOS, and Linux operating systems.

.NET Core Framework can be used to build different types of


applications such as mobile, desktop, web, cloud, IoT, machine
learning, microservices, game, etc.

.NET Core is written from scratch to make it modular, lightweight,


fast, and cross-platform Framework. It includes the core features
that are required to run a basic .NET Core app. Other features are
provided as NuGet packages, which you can add it in your application
as needed. In this way, the .NET Core application speed up the
performance, reduce the memory footprint and becomes easy to
maintain.
Why .NET Core?
There are some limitations with the .NET Framework. For example, it
only runs on the Windows platform. Also, you need to use
different .NET APIs for different Windows devices such as Windows
Desktop, Windows Store, Windows Phone, and Web applications. In
addition to this, the .NET Framework is a machine-wide framework.
Any changes made to it affect all applications taking a dependency
on it. Learn more about the motivation behind .NET Core here.

Today, it's common to have an application that runs across devices;


a backend on the web server, admin front-end on windows desktop,
web, and mobile apps for consumers. So, there is a need for a single
framework that works everywhere. So, considering this, Microsoft
created .NET Core. The main objective of .NET Core is to make .NET
Framework open-source, cross-platform compatible that can be used
in a wide variety of verticals, from the data center to touch-based
devices.

.NET Core Characteristics


Open-source Framework: .NET Core is an open-source
framework maintained by Microsoft and available on GitHub
under MIT and Apache 2 licenses. It is a .NET Foundation project .

You can view, download, or contribute to the source code using the
following GitHub repositories:

 Language compiler platform Roslyn: https://github.com/dotnet/roslyn


 .NET Core runtime: https://github.com/dotnet/runtime
 .NET Core SDK repository. https://github.com/dotnet/sdk
 ASP.NET Core repository. https://github.com/dotnet/aspnetcore

Cross-platform: .NET Core runs on Windows, macOS, and Linux


operating systems. There are different runtime for each operating
system that executes the code and generates the same output.

Consistent across Architectures: Execute the code with the same


behavior in different instruction set architectures, including x64, x86,
and ARM.
Wide-range of Applications: Various types of applications can be
developed and run on .NET Core platform such as mobile, desktop,
web, cloud, IoT, machine learning, microservices, game, etc.

Supports Multiple Languages: You can use C#, F#, and Visual
Basic programming languages to develop .NET Core applications. You
can use your favorite IDE, including Visual Studio 2017/2019, Visual
Studio Code, Sublime Text, Vim, etc.

Modular Architecture: .NET Core supports modular architecture


approach using NuGet packages. There are different NuGet packages
for various features that can be added to the .NET Core project as
needed. Even the .NET Core library is provided as a NuGet package.
The NuGet package for the default .NET Core application model
is Microsoft.NETCore.App.

This way, it reduces the memory footprint, speeds up the


performance, and easy to maintain.

CLI Tools: .NET Core includes CLI tools (Command-line interface)


for development and continuous-integration.

Flexible Deployment: .NET Core application can be deployed user-


wide or system-wide or with Docker Containers.

Compatibility: Compatible with .NET Framework and Mono APIs by


using .NET Standard specification .

.NET Core Version History


Version Latest Version Visual Studio Release Date End of Support

.NET 5 Preview 1 VS 2019 16th March, 2020

.NET Core 3.x - latest 3.1.3 VS 209 24th March, 2020 12th March, 2022

.NET Core 2.x 2.1.17 VS 2017, 2019 24th March, 2020 21st August, 2021

.NET Core 1.x 1.1.13 VS 2017 14th May, 2019 27th May, 2019

Both, .NET 3.1, and .NET Core 2.1 will have long term support.

.NET Core 3.x applications only run on .NET Core Framework.


.NET Core 2.x applications run on .NET Core as well as .NET
Framework.

.NET Core Composition


The .NET Core Framework composed of the following parts:

.NET Core

 CLI Tools: A set of tooling for development and deployment.


 Roslyn: Language compiler for C# and Visual Basic
 CoreFX: Set of framework libraries.
 CoreCLR: A JIT based CLR (Command Language Runtime).

ASP.NET Core Overview


ASP.NET Core is the new version of the ASP.NET web framework
mainly targeted to run on .NET Core platform.

ASP.NET Core is a free, open-source, and cross-platform framework


for building cloud-based applications, such as web apps, IoT apps,
and mobile backends. It is designed to run on the cloud as well as
on-premises.

Same as .NET Core, it was architected modular with minimum


overhead, and then other more advanced features can be added as
NuGet packages as per application requirement. This results in high
performance, require less memory, less deployment size, and easy to
maintain.

ASP.NET Core is an open source framework supported by Microsoft


and the community, so you can also contribute or download the
source code from the ASP.NET Core Repository on Github .

ASP.NET 3.x runs only on .NET Core 3.x, whereas ASP.NET Core 2.x
runs on .NET Core 2.x as well as .NET Framework.

ASP.NET Core

Why ASP.NET Core?


 Supports Multiple Platforms: ASP.NET Core applications can run on
Windows, Linux, and Mac. So you don't need to build different apps for
different platforms using different frameworks.
 Fast: ASP.NET Core no longer depends on System.Web.dll for browser-
server communication. ASP.NET Core allows us to include packages that we
need for our application. This reduces the request pipeline and improves
performance and scalability.
 IoC Container: It includes the built-in IoC container for automatic
dependency injection which makes it maintainable and testable.
 Integration with Modern UI Frameworks: It allows you to use and
manage modern UI frameworks such as AngularJS, ReactJS, Umber,
Bootstrap, etc. using Bower (a package manager for the web).
 Hosting: ASP.NET Core web application can be hosted on multiple platforms
with any web server such as IIS, Apache etc. It is not dependent only on IIS
as a standard .NET Framework.
 Code Sharing: It allows you to build a class library that can be used with
other .NET frameworks such as .NET Framework 4.x or Mono. Thus a single
code base can be shared across frameworks.
 Side-by-Side App Versioning: ASP.NET Core runs on .NET Core, which
supports the simultaneous running of multiple versions of applications.
 Smaller Deployment Footprint: ASP.NET Core application runs on .NET
Core, which is smaller than the full .NET Framework. So, the application
which uses only a part of .NET CoreFX will have a smaller deployment size.
This reduces the deployment footprint.

.NET Core vs ASP.NET Core


.NET Core ASP.NET Core

Open-source and Cross-platform Open-source and Cross-platform

.NET Core is a runtime to execute ASP.NET Core is a web framework to build web apps, IoT apps, and mobile
applications build on it. backends on the top of .NET Core or .NET Framework.

Install .NET Core Runtime to run There is no separate runtime and SDK are available for ASP.NET Core. .NET Core
applications and install .NET Core SDK to runtime and SDK includes ASP.NET Core libraries.
build applications.

.NET Core GitHub Repository: ASP.NET Core GitHub Repository: https://github.com/dotnet/aspnetcore


.NET Core Runtime
.NET Core SDK

.NET Core 3.1 - latest version ASP.NET Core 3.1


There is no separate versioning for ASP.NET Core. It is the same as .NET Core
versions.

Install .NET Core, ASP.NET Core


Here you will learn to prepare a development environment for
building .NET Core/ASP.NET Core applications.

.NET Core can be installed in two ways: By installing Visual Studio


2017/2019 or by installing .NET Core Runtime or SDK.

.NET Core installer already contains ASP.NET Core libraries, so there


is no separate installer for ASP.NET Core.

Install Visual Studio


Currently, .NET Core 2.1 and .NET Core 3.1 is having long term
support. Visual Studio 2017 supports .NET Core 2.1, whereas Visual
Studio 2019 supports both the versions.
You can use your favorite IDE, such as Visual Studio, Visual Studio
Code, Sublime Text, etc. to develop, restore, build, and run .NET
Core application. Here, we will use Visual Studio 2019.

If you don�t have Visual Studio on your development PC, then it is


recommended to install the latest Visual Studio 2019. If you already
have either Visual Studio 2017 or 2019, then you already have
installed .NET Core 2.1.

Download and install Visual Studio 2019 based on your OS


from here. Select the appropriate edition as per your license. The
community edition is free for students, open-source contributors, and
individuals.

During installation, select ".NET Core cross-platform development"


workload. This will install .NET Core 2.1. However, you need to install
.NET Core 3.1 SDK separately.

Once installed, you can verify it by opening a command prompt (or


terminal in Mac) and type dotnet --version and press Enter. This
will display the installed version and usage information, as shown
below.
C:\Users\dev>dotnet --version

2.1.805

ADVERTISEMENT

Install .NET Core 3.x


As you have seen, Visual Studio 2019 installer includes .NET Core 2.1
but not .NET Core 3.x. You need to install it separately.

To download the latest version of .NET Core, go


to https://dotnet.microsoft.com/download and select the platform
you are using.

Install .NET Core SDK for Windows

As you can see above, .NET Core Runtime and .NET Core SDK are
different things. .NET Core Runtime is only used to run .NET Core
application, whereas .NET Core SDK includes tools and libraries to
develop .NET Core applications. To set up a development
environment, we need to install .NET Core SDK for the platform we
use for development such as Windows, Linux, or Mac. Here we will
install .NET Core SDK because we are preparing a development
environment for building .NET Core applications. If you are aiming to
run .NET Core application, then install .NET Core Runtime on your
server or cloud or client desktop.

Click on the Download .NET Core SDK button to download the


latest version of .NET Core SDK installer. It will download .NET Core
3.1 SDK as of this writing.

After downloading the installer, click on it to start the installation.

Click on Install button and follow the wizard to install .NET Core 3.1
SDK.
After installation, you can now develop .NET Core/ASP.NET Core
applications

Create ASP.NET Core Application


Here, we will learn how to create our first ASP.NET Core 3.0
application in Visual Studio 2019.

Open Visual Studio 2019 and click on Create a new project, as


shown below.

Create a New ASP.NET Core 3.0 Project

The "Create a new project" dialog box includes different .NET Core
3.0 application templates. Each will create predefined project files
and folders depends on the application type. Here we will create a
simple web application, so select ASP.NET Core Web
Application template and click Next, as shown below.
Select Application Template

Next, give the appropriate name, location, and the solution name for
the ASP.NET Core application. In this example, we will give the name
"MyFirstCoreWebApp" and click on the Create button, as shown
below.
Configure Project

Next, select appropriate ASP.NET Core Web application template


such as Empty, API, Web Application, MVC, etc. Here, we want to
create a web application, so select the Web Application template.
We don't want HTTPS at this point, so uncheck Configure for
HTTPS checkbox, as shown below. Also, make sure you have
selected the appropriate .NET Core and ASP.NET Core versions. Click
on the Create button to create a project.
Select Web Application Template

This will create a new ASP.NET Core web project in Visual Studio
2019, as shown below. Wait for some time till Visual Studio restores
the packages in the project. Restoring process means Visual Studio
will automatically add, update or delete configured dependencies as
NuGet packages in the project.
Create ASP.NET Core 3 Application

We will understand the project structure in the next chapter. To run


this web application, click on IIS Express or press Ctrl + F5. This
will open the browser and display the following result.
The above output comes from the Index.cshtml page under
the Pages folder.

You can also see the IIS express icon on the system tray. Right click
on it. You can see the ASP.NET sites currently running in your
development machine.

ASP.NET Core sites in System Tray

Thus, we can create a new cross-platform ASP.NET Core 3.0


application that runs on .NET Core.

ASP.NET Core - Project Structure


Here, you will learn about the project structure and significance of
each file created by ASP.NET Core 2.0 application template using
Visual Studio 2017.

The following is a default project structure when you create an empty


ASP.NET Core application in Visual Studio.

ASP.NET Core Project Structure

The above solution explorer displays project solution. We can change


it to folder view by clicking Solution and Folders icon and selecting
Folder View option. This displays the solution explorer with all project
folders and files as shown below.
Solution Explorer - Folder View

Note:

ASP.NET Core project files and folders are synchronized with physical files and
folders. If you add a new file or folder in project folder then it will directly reflect in
the solution explorer. You don't need to add it in the project explicitly by right
clicking on the project.

.csproj
ASP.NET Core 1.0 does not create .csproj file, instead, it uses .xproj
and project.json files to manage the project. This has changed in
ASP.NET Core 2.0. Visual Studio now uses .csproj file to manage
projects. We can edit the .csproj settings by right clicking on the
project and selecting Edit <project-name>.csproj as shown below.

Edi
t .csproj

The .csproj for the above project looks like below.

Edit .csproj
The csproj file includes settings related to targeted .NET Frameworks,
project folders, NuGet package references etc.
ADVERTISEMENT

Dependencies
The Dependencies in the ASP.NET Core 2.1 project contain all the
installed server-side NuGet packages, as shown below.

Dependencies

Right click on "Dependencies" and then click "Manage NuGet


Packages.." to see the installed NuGet packages, as shown below.
Dependencies

As you can see, it has installed three


packages, Microsoft.AspNetCore.App package is for ASP.NET web
application, Microsoft.AspNetCore.Razor.Design package is for
Razor engine, and Microsoft.NETCore.App package is for .NET Core
API.

You can install all other required server side dependencies as NuGet
packages from Manage NuGte Packages window or using Package
Manager Console.

Properties
The Properties node includes launchSettings.json file which includes
Visual Studio profiles of debug settings. The following is a default
launchSettings.json file.
launchSettings.json

We can also edit settings from the debug tab of project properties.
Right click on the project -> select Properties -> click Debug tab.

Project Properties
In the debug tab, select a profile which you want to edit as shown
above. You may change environment variables, url etc.

ASP.NET Core - wwwroot Folder


By default, the wwwroot folder in the ASP.NET Core project is
treated as a web root folder. Static files can be stored in any folder
under the web root and accessed with a relative path to that root.

In the standard ASP.NET application, static files can be served from


the root folder of an application or any other folder under it. This has
been changed in ASP.NET Core. Now, only those files that are in the
web root - wwwroot folder can be served over an http request. All
other files are blocked and cannot be served by default.

Generally, there should be separate folders for the different types of


static files such as JavaScript, CSS, Images, library scripts etc. in the
wwwroot folder as shown below.
wwwroot

You can access static files with base URL and file name. For example,
we can access above app.css file in the css folder
by http://localhost:<port>/css/app.css .

Remember, you need to include a middleware for serving static files


in the Configure method of Startup.cs. Learn more about it
in Serving Static File section.
Rename wwwroot Folder
You can rename wwwroot folder to any other name as per your
choice and set it as a web root while preparing hosting environment
in the program.cs.

For example, let's rename wwwroot folder to Content folder. Now,


call UseWebRoot() method to configure Content folder as a web root
folder in the Main() method of Program class as shown below.

public class Program


{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseWebRoot("Content")
.UseIISIntegration()
.UseStartup<MyStartup>()
.Build();

host.Run();
}
}

Thus, you can rename the default web root folder wwwroot as per
your choice.

ASP.NET Core - Program.cs


ASP.NET Core web application is actually a console project which
starts executing from the entry point public static void
Main() in Program class where we can create a host for the web
application.

Setup Host in ASP.NET Core 2.x


The following is the Program class in ASP.NET Core 2.x:
Program.cs

Copy

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;

namespace MyFirstCoreApp
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}

As you can see above, the Main() method calls method


expression BuildWebHost() to build web host with pre-configured
defaults. The BuildWebHost expression can also be written as a method
that returns IWebHost as shown below.

public static void Main(string[] args)


{
BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args)


{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}

Let's understand hosting steps.


The WebHost is a static class which can be used for creating an instance
of IWebHost and IWebHostBuilder with pre-configured defaults.
The CreateDefaultBuilder() method creates a new instance
of WebHostBuilder with pre-configured defaults. Internally, it configures
Kestrel, IISIntegration and other configurations. The following
is CreateDefaultBuilder() method.

CreateDefaultBuilder()

Copy

public static IWebHostBuilder CreateDefaultBuilder(string[] args)


{
var builder = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;

config.AddJsonFile("appsettings.json", optional: true,


reloadOnChange: true)
.AddJsonFile($ "appsettings.
{env.EnvironmentName}.json", optional: true, reloadOnChange: true);

if (env.IsDevelopment())
{
var appAssembly = Assembly.Load(new
AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional:
true);
}
}

config.AddEnvironmentVariables();

if (args != null)
{
config.AddCommandLine(args);
}
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetS
ection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.UseIISIntegration()
.UseDefaultServiceProvider((context, options) =>
{
options.ValidateScopes =
context.HostingEnvironment.IsDevelopment();
});

return builder;
}

As you can see above, the CreateDefaultBuilder method creates an


instance of WebHostBuilder and sets up Kestrel, content root directory,
IIS integration.

Kestrel is an open-source, cross-platform web server for ASP.NET


Core. It is designed to be used behind proxy because it has not yet
matured to be exposed as a full-fledge web server.

It also calls ConfigureAppConfiguration() to load configurations from


appsettings.json files, environment variables and user secrets.
The ConfigureLogging() method setup logging to console and debug
window

ASP.NET Core - Startup Class


Here, we will have an overview of Startup class contained in
Startup.cs in the root folder of the project.

ASP.NET Core application must include Startup class. It is like


Global.asax in the traditional .NET application. As the name suggests,
it is executed first when the application starts.

The startup class can be configured using UseStartup<T>() method at the


time of configuring the host in the Main() method of Program class as
shown below.

public class Program


{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args)


{
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}

The name "Startup" is by ASP.NET Core convention. However, we


can give any name to the Startup class, just specify it as the generic
parameter in the UseStartup<T>() method. For example, to name the
Startup class as MyStartup, specify it as .UseStartup<MyStartup>() .

Open Startup class in Visual Studio by clicking on the Startup.cs in


the solution explorer. The following is a default Startup class in
ASP.NET Core 2.x.

startup.cs

As you can see, Startup class includes two public


methods: ConfigureServices and Configure.
The Startup class must include a Configure method and can
optionally include ConfigureService method.

ConfigureServices()
The Dependency Injection pattern is used heavely in ASP.NET Core
architecture. It includes built-in IoC container to provide dependent
objects using constructors.

The ConfigureServices method is a place where you can register your


dependent classes with the built-in IoC container. After registering
dependent class, it can be used anywhere in the application. You just
need to include it in the parameter of the constructor of a class
where you want to use it. The IoC container will inject it
automatically.

ASP.NET Core refers dependent class as a Service. So, whenever you


read "Service" then understand it as a class which is going to be
used in some other class.

ConfigureServices method includes IServiceCollection parameter to


register services to the IoC container. Learn more about it in the
next chapter.

Configure()
The Configure method is a place where you can configure application
request pipeline for your application using IApplicationBuilder
instance that is provided by the built-in IoC container.

ASP.NET Core introduced the middleware components to define a


request pipeline, which will be executed on every request. You
include only those middleware components which are required by
your application and thus increase the performance of your
application.

The following is a default Configure method.

public void Configure(IApplicationBuilder app, IHostingEnvironment


env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.Run(async (context) =>


{
await context.Response.WriteAsync("Hello World!");
});
}

As you can see, the Configure method includes three parameters


IApplicationBuilder, IHostingEnvironment, and ILoggerFactory by
default. These services are framework services injected by built-in
IoC container.

At run time, the ConfigureServices method is called before the


Configure method. This is so that you can register your custom
service with the IoC container which you may use in the Configure
method.

.NET Core Command-Line Interface


The .NET Core command-line interface (CLI) is a new cross-platform
tool for creating, restoring packages, building, running and
publishing .NET applications.

We created our first ASP.NET Core application using Visual Studio in


the previous chapter. Visual Studio internally uses this CLI to restore,
build and publish an application. Other higher level IDEs, editors and
tools can use CLI to support .NET Core applications.

The .NET Core CLI is installed with .NET Core SDK for selected
platforms. So we don't need to install it separately on the
development machine. We can verify whether the CLI is installed
properly by opening command prompt in Windows and writing dotnet
and pressing Enter. If it displays usage and help as shown below
then it means it is installed properly.
.NET Core Command-line Interface

Command Structure
The following is a command structure.
dotnet <command> <argument> <option>

All the commands start with driver named dotnet. The driver starts
the execution of the specified command. After dotnet, we can supply
command (also known as verb) to perform a specific action. Each
command can be followed by arguments and options. The following
are .NET Core 2.x CLI commands.

Basic Commands Description

new Creates a new project, configuration file, or solution based on the specified template.

restore Restores the dependencies and tools of a project.

build Builds a project and all of its dependencies.

Run Runs source code without any explicit compile or launch commands.

publish Packs the application and its dependencies into a folder for deployment to a hosting system.

test Executes unit tests.

vtest Runs tests from the specified files.


Basic Commands Description

pack Packs the code into a NuGet package.

clean Cleans the output of a project.

sln Modifies a .NET Core solution file.

help Display help on the specified command

store Stores the specified assemblies in the runtime package store.

Project Modification Commands Description

add package Adds a package reference to a project.

add reference Adds project-to-project (P2P) references.

remove package Removes package reference from the project.

remove reference Removes project reference

list reference Lists all project-to-project references

Advanced Commands Description

nuget delete Deletes or unlists a package from the server.

nuget locals Clears or lists local NuGet resources.

nuget push Pushes a package to the server and publishes it.

msbuild Builds a project and all of its dependencies.

dotnet install script Script used to install the .NET Core CLI tools and the shared runtime.

Let's create, restore, build, and run .NET Core console application
using command-line interface without using Visual Studio.
ADVERTISEMENT

Create a New Project


To create a new .NET Core project, we have to use new command
followed by template name argument. We can create console, class
library, web, mvc, webapi, razor, angular, react etc. projects using
CLI. Use console template to create a new .NET Core console
application.
The following creates new console project in the current directory
with the same name as current directory.
dotnet new console

The following command creates a new console project named


MyConsoleApp. The -n or --name option species the name of a
project.
dotnet new console -n MyConsoleApp

The following command creates a new console application named


MyConsoleApp to MyProjects directory. The -o or --output option is
used to specify an output directory where the project should be
generated.
dotnet new console -n MyConsoleApp -o C:\MyProjects

After creating a project, navigate to the project directories in


command prompt to apply project specific commands which is C:\
MyConsoleApp in our case.

Add Package Reference


We often need to add NuGet package reference for different
purposes. For example, apply the following command to add
Newtonsoft.json package to our console project.

C:\MyConsoleApp>dotnet add package Newtonsoft.json

This will add Newtonsoft.json package to our project. We can verify it


by opening .csproj file.

Restore Packages
To restore packages or to update existing packages, we can use
restore command as below.
C:\MyConsoleApp>dotnet restore

Build Project
To build a new or existing project, apply C:\MyConsoleApp>dotnet
build command.

Run project
To run our console project, apply dotnet run command as shown below.

As you can see above, it displays an output "Hello World!".

Getting Help
We can get help on any .NET Core CLI commands by typing -h or -
help at the end of the command we want to get help on. For
example, dotnet new -h will display help on the new command,
arguments and options we can use with it, as shown below.
Thus, we can use .NET Core command-line interface to create,
restore packages, build, run, and publish different types of .NET Core
applications.

ASP.NET Core - Dependency Injection


ASP.NET Core is designed from scratch to support Dependency
Injection. ASP.NET Core injects objects of dependency classes
through constructor or method by using built-in IoC container.

Built-in IoC Container


ASP.NET Core framework contains simple out-of-the-box IoC
container which does not have as many features as other third party
IoC containers. If you want more features such as auto-registration,
scanning, interceptors, or decorators then you may replace built-in
IoC container with a third party container.
The built-in container is represented
by IServiceProvider implementation that supports constructor injection
by default. The types (classes) managed by built-in IoC container are
called services.

There are basically two types of services in ASP.NET Core:

1. Framework Services: Services which are a part of ASP.NET Core framework


such as IApplicationBuilder, IHostingEnvironment, ILoggerFactory etc.
2. Application Services: The services (custom types or classes) which you as a
programmer create for your application.

In order to let the IoC container automatically inject our application


services, we first need to register them with IoC container.

Registering Application Service


Consider the following example of simple ILog interface and its
implementation class. We will see how to register it with built-in IoC
container and use it in our application.

public interface ILog


{
void info(string str);
}

class MyConsoleLogger : ILog


{
public void info(string str)
{
Console.WriteLine(str);
}
}

ASP.NET Core allows us to register our application services with IoC


container, in the ConfigureServices method of the Startup class.
The ConfigureServices method includes a parameter
of IServiceCollection type which is used to register application services.

Let's register above ILog with IoC container in ConfigureServices()


method as shown below.

Example: Register Service


Copy

public class Startup


{
public void ConfigureServices(IServiceCollection services)
{
services.Add(new ServiceDescriptor(typeof(ILog), new
MyConsoleLogger()));
}

// other code removed for clarity..


}

As you can see above, Add() method of IServiceCollection instance is


used to register a service with an IoC container.
The ServiceDescriptor is used to specify a service type and its
instance. We have specified ILog as service type and MyConsoleLogger as
its instance. This will register ILog service as a singleton by default.
Now, an IoC container will create a singleton object
of MyConsoleLogger class and inject it in the constructor of classes
wherever we include ILog as a constructor or method parameter
throughout the application.

Thus, we can register our custom application services with an IoC


container in ASP.NET Core application. There are other extension
methods available for quick and easy registration of services which
we will see later in this chapter.

Understanding Service Lifetime


Built-in IoC container manages the lifetime of a registered service
type. It automatically disposes a service instance based on the
specified lifetime.

The built-in IoC container supports three kinds of lifetimes:

1. Singleton: IoC container will create and share a single instance of a service
throughout the application's lifetime.
2. Transient: The IoC container will create a new instance of the specified
service type every time you ask for it.
3. Scoped: IoC container will create an instance of the specified service type
once per request and will be shared in a single request.
The following example shows how to register a service with different
lifetimes.

Example: Register a Service with Lifetime

Copy

public void ConfigureServices(IServiceCollection services)


{
services.Add(new ServiceDescriptor(typeof(ILog), new
MyConsoleLogger())); // singleton

services.Add(new ServiceDescriptor(typeof(ILog),
typeof(MyConsoleLogger), ServiceLifetime.Transient)); // Transient

services.Add(new ServiceDescriptor(typeof(ILog),
typeof(MyConsoleLogger), ServiceLifetime.Scoped)); // Scoped
}
ADVERTISEMENT

Extension Methods for Registration


ASP.NET Core framework includes extension methods for each types
of lifetime; AddSingleton(), AddTransient() and AddScoped() methods for
singleton, transient and scoped lifetime respectively.

The following example shows the ways of registering types (service)


using extension methods.

Example: Extension Methods

Copy

public void ConfigureServices(IServiceCollection services)


{
services.AddSingleton<ILog, MyConsoleLogger>();
services.AddSingleton(typeof(ILog), typeof(MyConsoleLogger));

services.AddTransient<ILog, MyConsoleLogger>();
services.AddTransient(typeof(ILog), typeof(MyConsoleLogger));

services.AddScoped<ILog, MyConsoleLogger>();
services.AddScoped(typeof(ILog), typeof(MyConsoleLogger));
}
Constructor Injection
Once we register a service, the IoC container automatically performs
constructor injection if a service type is included as a parameter in a
constructor.

For example, we can use ILog service type in any MVC controller.
Consider the following example.

Example: Using Service

Copy

public class HomeController : Controller


{
ILog _log;

public HomeController(ILog log)


{
_log = log;
}
public IActionResult Index()
{
_log.info("Executing /home/index");

return View();
}
}

In the above example, an IoC container will automatically pass an


instance of MyConsoleLogger to the constructor of HomeController. We don't
need to do anything else. An IoC container will create and dispose an
instance of ILog based on the registered lifetime.

Action Method Injection


Sometimes we may only need dependency service type in a single
action method. For this, use [FromServices] attribute with the
service type parameter in the method.

Example: Action Method Injection

Copy
using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller


{
public HomeController()
{
}

public IActionResult Index([FromServices] ILog log)


{
log.info("Index method executing");

return View();
}
}

Property Injection
Built-in IoC container does not support property injection. You will
have to use third party IoC container.

Get Services Manually


It is not required to include dependency services in the constructor.
We can access dependent services configured with built-in IoC
container manually using RequestServices property of HttpContext as
shown below.

Example: Get Service Instance Manually

Copy

public class HomeController : Controller


{
public HomeController()
{
}
public IActionResult Index()
{
var services = this.HttpContext.RequestServices;
var log = (ILog)services.GetService(typeof(ILog));

log.info("Index method executing");

return View();
}
}

It is recommended to use constructor injection instead of getting it


using RequestServices.

ASP.NET Core: Built-in IoC Container


ASP.NET Core framework includes built-in IoC container for
automatic dependency injection. The built-in IoC container is a
simple yet effective container. Let's understand how the built-in IoC
container works internally.

The followings are important interfaces and classes for built-in IoC
container:

Interfaces:

1. IServiceProvider
2. IServiceCollection

Classes:

1. ServiceProvider
2. ServiceCollection
3. ServiceDescription
4. ServiceCollectionServiceExtensions
5. ServiceCollectionContainerBuilderExtensions

The following diagram illustrates the relationship between these


classes:
bui
lt-in IoC Container

IServiceCollection
As you know, we can register application services with built-in IoC
container in the Configure method of Startup class by using
IServiceCollection. IServiceCollection interface is an empty interface.
It just inherits IList<servicedescriptor>. See the source code here.

The ServiceCollection class implements IServiceCollection interface.


See the ServiceCollection source code here.

So, the services you add in the IServiceCollection type instance, it


actually creates an instance of ServiceDescriptor and adds it to the
list.

IServiceProvider
IServiceProvider includes GetService method.
The ServiceProvider class implements IServiceProvider interface
which returns registered services with the container. We cannot
instantiate ServiceProvider class because its constructors are marked
with internal access modifier.
ServiceCollectionServiceExtensions
The ServiceCollectionServiceExtensions class includes extension
methods related to service registrations which can be used to add
services with lifetime. AddSingleton, AddTransient, AddScoped
extension methods defined in this class.

ServiceCollectionContainerBuilderExtensions
ServiceCollectionContainerBuilderExtensions class
includes BuildServiceProvider extension method which creates and
returns an instance of ServiceProvider.

There are three ways to get an instance of IServiceProvider:

Using IApplicationBuilder
We can get the services in Configure method using
IApplicationBuilder's ApplicationServices property as shown below.

public void Configure(IServiceProvider pro, IApplicationBuilder app,


IHostingEnvironment env)
{
var services = app.ApplicationServices;
var logger = services.GetService<ILog>() }

//other code removed for clarity


}

Using HttpContext
var services = HttpContext.RequestServices;
var log = (ILog)services.GetService(typeof(ILog));

Using IServiceCollection
public void ConfigureServices(IServiceCollection services)
{
var serviceProvider = services.BuildServiceProvider();

}
ASP.NET Core - Middleware
ASP.NET Core introduced a new concept called Middleware. A
middleware is nothing but a component (class) which is executed on
every request in ASP.NET Core application. In the classic ASP.NET,
HttpHandlers and HttpModules were part of request pipeline.
Middleware is similar to HttpHandlers and HttpModules where both
needs to be configured and executed in each request.

Typically, there will be multiple middleware in ASP.NET Core web


application. It can be either framework provided middleware, added
via NuGet or your own custom middleware. We can set the order of
middleware execution in the request pipeline. Each middleware adds
or modifies http request and optionally passes control to the next
middleware component. The following figure illustrates the execution
of middleware components.

AS
P.NET Core Middleware

Middlewares build the request pipeline. The following figure


illustrates the ASP.NET Core request processing.

ASP.NET Core Request Processing


Configure Middleware
We can configure middleware in the Configure method of the Startup
class using IApplicationBuilder instance. The following example adds
a single middleware using Run method which returns a string "Hello
World!" on each request.

public class Startup


{
public Startup()
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment
env, ILoggerFactory loggerFactory)
{
//configure middleware using IApplicationBuilder here..

app.Run(async (context) =>


{
await context.Response.WriteAsync("Hello World!");

});

// other code removed for clarity..


}
}

In the above example, Run() is an extension method


on IApplicationBuilder instance which adds a terminal middleware to
the application's request pipeline. The above configured middleware
returns a response with a string "Hello World!" for each request.

Understand Run Method


We used Run extension method to add middleware. The following is
the signature of the Run method:

Method Signature:
public static void Run(this IApplicationBuilder app, RequestDelegate
handler)
The Run method is an extension method on IApplicationBuilder and
accepts a parameter of RequestDelegate. The RequestDelegate is a
delegate method which handles the request. The following is a
RequestDelegate signature.

Method Signature:
public delegate Task RequestDelegate(HttpContext context);

As you can see above, the Run method accepts a method as a


parameter whose signature should match with RequestDelegate.
Therefore, the method should accept the HttpContext parameter and
return Task. So, you can either specify a lambda expression or specify
a function in the Run method. The lambda expression specified in the
Run method above is similar to the one in the example shown below.

public class Startup


{
public Startup()
{
}

public void Configure(IApplicationBuilder app, IHostingEnvironment


env)
{
app.Run(MyMiddleware);
}

private Task MyMiddleware(HttpContext context)


{
return context.Response.WriteAsync("Hello World! ");
}
}

The above MyMiddleware function is not asynchronous and so will block


the thread till the time it completes the execution. So, make it
asynchronous by using async and await to improve performance and
scalability.

// other code removed for clarity

public void Configure(IApplicationBuilder app, IHostingEnvironment


env)
{
app.Run(MyMiddleware);
}

private async Task MyMiddleware(HttpContext context)


{
await context.Response.WriteAsync("Hello World! ");
}

Thus, the above code snippet is same as the one below.

app.Run(async context => await context.Response.WriteAsync("Hello


World!") );

//or

app.Run(async (context) =>


{
await context.Response.WriteAsync("Hello World!");
});

So, in this way, we can configure middleware using Run method.


ADVERTISEMENT

Configure Multiple Middleware


Mostly there will be multiple middleware components in ASP.NET
Core application which will be executed sequentially. The Run method
adds a terminal middleware so it cannot call next middleware as it
would be the last middleware in a sequence. The following will always
execute the first Run method and will never reach the second Run
method.

public void Configure(IApplicationBuilder app, IHostingEnvironment


env)
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World From 1st
Middleware");
});

// the following will never be executed


app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World From 2nd
Middleware");
});
}

To configure multiple middleware, use Use() extension method. It is


similar to Run() method except that it includes next parameter to
invoke next middleware in the sequence. Consider the following
example.

Example: Use()

Copy

public void Configure(IApplicationBuilder app, IHostingEnvironment


env)
{
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Hello World From 1st
Middleware!");

await next();
});

app.Run(async (context) =>


{
await context.Response.WriteAsync("Hello World From 2nd
Middleware");
});
}

The above example will display Hello World From 1st Middleware!Hello
World From 2nd Middleware! in the browser.

Thus, we can use Use() method to configure multiple middlewares in


the order we like.

Add Built-in Middleware Via NuGet


ASP.NET Core is a modular framework. We can add server side
features we need in our application by installing different plug-ins via
NuGet. There are many middleware plug-ins available which can be
used in our application.

The followings are some built-in middleware:

Middleware Description

Authentication Adds authentication support.

CORS Configures Cross-Origin Resource Sharing.

Routing Adds routing capabilities for MVC or web form

Session Adds support for user session.

StaticFiles Adds support for serving static files and directory browsing.

Diagnostics Adds support for reporting and handling exceptions and errors.

Let's see how to use Diagnostics middleware.

Diagnostics Middleware
Let's install and use Diagnostics middleware. Diagnostics middleware
is used for reporting and handling exceptions and errors in ASP.NET
Core, and diagnosing Entity Framework Core migrations errors.

Open project.json and add Microsoft.AspNetCore.Diagnostics


dependency if it is not added. Wait for some time till Visual Studio
restores the packages.

This package includes following middleware and extension methods


for it.

Middleware Extension Method Description

DeveloperExceptionPageMiddleware UseDeveloperExceptionPage() Captures synchronous and asynchronous exceptions from


the pipeline and generates HTML error responses.

ExceptionHandlerMiddleware UseExceptionHandler() Catch exceptions, log them and re-execute in an alternate


pipeline.

StatusCodePagesMiddleware UseStatusCodePages() Check for responses with status codes between 400 and
599.
Middleware Extension Method Description

WelcomePageMiddleware UseWelcomePage() Display Welcome page for the root path.

We can call respective Use* extension methods to use the above


middleware in the configure method of Startup class.

Let's add welcomePage middleware which will display welcome page


for the root path.

Example: Add Diagnostics Middleware

Copy

public void Configure(IApplicationBuilder app, IHostingEnvironment


env)
{
app.UseWelcomePage();
//other code removed for clarity
}

The above example will display the following welcome page for each
request.

This way we can use different Use* extension methods to include


different middleware.

Add Custom Middleware in ASP.NET Core


Application
Here, you will learn how to create and add your own custom
middleware into the request pipeline of ASP.NET Core application.

The custom middleware component is like any other .NET class


with Invoke() method. However, in order to execute next middleware
in a sequence, it should have RequestDelegate type parameter in the
constructor.
Visual Studio includes template for creating standard middleware
class. For this, right click on the project or folder where you want to
create middleware class and select Add -> New Item. This will open
Add New Item popup. Search for word "middleware" in the top right
search box as shown below.

Add Custom Middleware

Select Middleware Class item and give it a name and click on Add
button. This will add a new class for the middleware with extension
method as shown below.

Example: Custom Middleware

Copy

// You may need to install the Microsoft.AspNetCore.Http.Abstractions


package into your project
public class MyMiddleware
{
private readonly RequestDelegate _next;

public MyMiddleware(RequestDelegate next)


{
_next = next;
}

public Task Invoke(HttpContext httpContext)


{

return _next(httpContext);
}
}

// Extension method used to add the middleware to the HTTP request


pipeline.
public static class MyMiddlewareExtensions
{
public static IApplicationBuilder UseMyMiddleware(this
IApplicationBuilder builder)
{
return builder.UseMiddleware<MyMiddleware>();
}
}

As you can see above, the Invoke() method is not asynchronous. So,
change it to asynchronous and write your custom logic before calling
next();

Example: Async Middleware

Copy

public class MyMiddleware


{
private readonly RequestDelegate _next;
private readonly ILogger _logger;

public MyMiddleware(RequestDelegate next, ILoggerFactory


logFactory)
{
_next = next;

_logger = logFactory.CreateLogger("MyMiddleware");
}

public async Task Invoke(HttpContext httpContext)


{
_logger.LogInformation("MyMiddleware executing..");

await _next(httpContext); // calling next middleware


}
}

// Extension method used to add the middleware to the HTTP request


pipeline.
public static class MyMiddlewareExtensions
{
public static IApplicationBuilder UseMyMiddleware(this
IApplicationBuilder builder)
{
return builder.UseMiddleware<MyMiddleware>();
}
}

Add Custom Middleware


Now, we need to add our custom middleware in the request pipeline
by using Use extension method as shown below.

Example: Add Middleware into Request Pipeline

Copy

public void Configure(IApplicationBuilder app, IHostingEnvironment


env)
{
app.UseMyMiddleware();

app.Run(async (context) =>


{
await context.Response.WriteAsync("Hello World!");
});
}

We can add middleware using app.UseMiddleware<MyMiddleware>() method of


IApplicationBuilder also.

Thus, we can add custom middleware in the ASP.NET Core


application.

Configure the Default File to be Served


on the Root Request
As we learned in the Set Default File
section, app.UseDefaultFiles() middleware serves the following files on
the root request.

1. Default.html
2. Default.htm
3. Index.html
4. Index.htm

Suppose, you want to set home.html as a default page which should


be displayed on the root access. To do that,
specify DefaultFilesOptions in the UseDefaultFiles method as shown below.

public class Startup


{
public void Configure(IApplicationBuilder app, IHostingEnvironment
env)
{
DefaultFilesOptions options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("home.html");
app.UseDefaultFiles(options);

app.UseStaticFiles();

app.Run(async (context) =>


{
await context.Response.WriteAsync("Hello World");
});
}
}

ASP.NET Core - Environment Variable


Typically, in professional application development, there are multiple
phases where an application is tested before publishing it to the real
users. These phases by convention are development, staging, and
production. We as developers might like to control the behavior of an
application based on the phases the application is in. Environment
variable indicates the runtime environment in which an application is
currently running.
ASP.NET Core uses an environment variable
called ASPNETCORE_ENVIRONMENT to indicate the runtime environment. The
value of this variable can be anything as per your need but typically
it can be Development, Staging, or Production. The value is case
insensitive in Windows and Mac OS but it is case sensitive on Linux.

In Visual Studio, we can set ASPNETCORE_ENVIRONMENT in the debug tab of


project properties. Open project properties by right clicking on the
project in the solution explorer and select Properties.

Open
Project Properties

This will open properties page. Click on Debug tab and you will see
Environment Variables as shown below.
Environment Variable

You may change the value as per your need. This value will be saved
in the launchSettings.json file as shown below.

launchsettings.json
You may also change the environment variable directly in
launchSettings.json.
ADVERTISEMENT

Access Environment Variable at Runtime


We can get the value of an environment variable in our code to
execute some additional code based on its value.
The IHostingEnvironment service includes EnvironmentName property
which contains the value of ASPNETCORE_ENVIRONMENT variable. ASP.NET
Core also includes extension methods to check the environment such
as IsDevelopment(), IsStating(), IsEnvironment() and IsProduction().

The IHostingEnvironment service is provided by ASP.NET hosting layer


and can be used anywhere in your application via Dependency
Injection. The following example shows how we can check the
environment variable in the Configure method of Startup class.

Example: Access Environment Variable

Copy

public void Configure(IApplicationBuilder app, IHostingEnvironment


env)
{
if (env.IsEnvironment("Development"))
{
// code to be executed in development environment

if (env.IsDevelopment())
{
// code to be executed in development environment

if (env.IsStaging())
{
// code to be executed in staging environment

if (env.IsProduction())
{
// code to be executed in production environment

}
}

ASP.NET Core - Exception Handling


Exception handling is one of the most important features of any
application. Fortunately, ASP.NET Core includes a middleware that
makes exception handling easy. In this chapter, we will learn about
exception handling in ASP.NET Core application.

By default, ASP.NET Core returns a simple status code for any


exception that occurs in an application. Consider the following
example of Configure method which throws an error.

public class Startup


{
public void Configure(IApplicationBuilder app, IHostingEnvironment
env)
{
app.Run(context => { throw new Exception("error"); });
}
}

The above code will display the following result.


Install Microsoft.AspNetCore.Diagnostics
Package
To handle exceptions and display user friendly messages, we need to
install Microsoft.AspNetCore.Diagnostics NuGet package and add
middleware in the Configure() method. If you are using Visual Studio
templates to create ASP.NET Core application then this package
might be already installed. If not then you can
add Microsoft.AspNetCore.Diagnostics package via NuGet manager.

The Microsoft.AspNetCore.Diagnostics package includes following


extension methods to handle exceptions in different scenario:

1. UseDeveloperExceptionPage
2. UseExceptionHandler

UseDeveloperExceptionPage
The UseDeveloperExceptionPage extension method adds middleware
into the request pipeline which displays developer friendly exception
detail page. This helps developers in tracing errors that occur during
development phase.

As this middleware displays sensitive information, it is advisable to


add it only in development environment.

public class Startup


{
public void Configure(IApplicationBuilder app, IHostingEnvironment
env)
{
if (env.IsDevelopment() || env.IsStaging())
{
app.UseDeveloperExceptionPage();
}

app.Run(context => { throw new Exception("error"); });


}
}

The above code will display the following result.

Exc
eption Handling
As you can see above, the developer exception page includes 4 tabs:
Stack, Query, Cookies, and Headers. Stack tab displays information
of stack trace, which indicates where exactly an error occurred.
Query tab displays information about query string. Cookies tab
displays information about cookies set by the request and Headers
tab displays information about headers.
ADVERTISEMENT

UseExceptionHandler
In MVC Core application, we might want some other controller to
handle all exceptions and display custom user friendly error
messages. The UseExceptionHandler extension method allows us to
configure custom error handling route. This is useful when an
application runs under production environment.

Example: Exception Handler in MVC

Copy

public void Configure(IApplicationBuilder app, IHostingEnvironment


env)
{

if (env.IsDevelopment() || env.IsStaging())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

//code removed for clarity


}

In the above example, the UseExceptionHandler("/Home/Error") sets


the error handler path. If an error occurred in the MVC application
then it will redirect the request to /home/error, which will execute the
Error action method of HomeController.

Create a simple Error action method in HomeController class as shown


below.
HomeController:

Copy

public class HomeController : Controller


{
public HomeController()
{
}

public IActionResult Error()


{
return View();
}

// other code removed for the clarity

The following is the content of Error.cshtml.

Error.cshtml

Copy

@{
ViewData["Title"] = "Error";
}

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your
request.</h2>

<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display
more detailed information about the error that occurred.
</p>
<p>
<strong>Development environment should not be enabled in deployed
applications</strong>, as it can result in sensitive information from
exceptions being displayed to end users. For local debugging,
development environment can be enabled by setting the
<strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to
<strong>Development</strong>, and restarting the application.
</p>
Now, when an error occurs, it displays the page shown below.

Exc
eption Handling

Thus, we can configure middleware to handle exceptions in ASP.NET


Core application.

Note:

Visual Studio automatically creates Error.cshtml under Home folder when you
create ASP.NET Core project with MVC template.

ASP.NET Core - Serving Static Files


Here, we will learn how to serve static files such as html, JavaScript,
CSS, or image files on HTTP request without any server-side
processing.

ASP.NET Core application cannot serve static files by default. We


must include Microsoft.AspNetCore.StaticFiles middleware in the request
pipeline.
Install StaticFiles Middleware
The Microsoft.AspNetCore.StaticFiles middleware package is
already included in the meta package Microsoft.AspNetCore.All , so we
don't need to install it separately in ASP.NET Core 2.x application.

To install StaticFiles middleware in ASP.NET Core 1.x application,


open NuGet package manager by right clicking on project in the
solution explorer and select Manage NuGet Packages... Search for
staticfiles in the search box in the browse tab. This will
display Microsoft.AspNetCore.StaticFiles middleware as shown
below.

Ins
tall StaticFiles Middleware

Click on the Install button on the right pane to install it. Once
installed, the Microsoft.AspNetCore.StaticFiles is automatically included in
the dependencies section of the project.json.
StaticFiles
Dependency in project.json

Using StaticFiles Middleware


By default, all the static files of a web application should be located
in the web root folder wwwroot. To understand this, let's create a
simple default.html in the wwwroot folder with the following content.

Default.html

Now, to serve the above Default.html static file, we must add


StaticFiles middleware in the Configure() method of Startup file as
shown below.

public class Startup


{
public Startup()
{
}

public void Configure(IApplicationBuilder app, IHostingEnvironment


env)
{
app.UseStaticFiles();

app.Run(async (context) =>


{
await context.Response.WriteAsync("Hello World");
});
}
}

As you can see above, the app.UseStaticFiles() method adds StaticFiles


middleware into the request pipeline. The UseStaticFiles is an extension
method included in the StaticFiles middleware so that we can easily
configure it.

Now, open the browser and send http


request http://localhost:<port>/default.html which will display
default.html as a response as shown below.
Ser
ving HTML File

This way we can serve any other file stored in wwwroot folder or sub-
folder. For example, consider the following test.js file in the wwwroot
folder.

test.js
Now, we can access this file by sending
http://localhost:<port>/test.js request.

Ser
ving JS File

Suppose, you want to serve files from the outside of web root folder
(wwwroot). For example, you include images in the following Images
folder as shown below.
Serving Static Files

Now, specify StaticFileOptions parameter in the UseStaticFiles method to


serve images from the Images folder as shown below.

public void Configure(IApplicationBuilder app, IHostingEnvironment


env)
{
app.UseStaticFiles(); // For the wwwroot folder

app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory
(), @"Images")),
RequestPath = new PathString("/app-
images")
});
}
As you can see, we used FileProvider option to specify Images folder
from which static files will be served. The RequestPath option
specifies the relative path in the URL which maps to the static folder.

Now, a request to http://localhost/app-images/MyImage.png will


serve the MyImage.png file.
ADVERTISEMENT

Set Default File


As we have seen above, default.html or test.js was served on the
specific request for it. However, what if we want to serve default
html file on the root request?

Currently, when you send http://localhost:<port> request, it will be


handled by run method and display the following result.

To serve default.html on the root request http://localhost:<port>,


call UseDefaultFiles() method before UseStaticFiles() in
the Configure method as shown below.
public void Configure(IApplicationBuilder app, IHostingEnvironment
env)
{
app.UseDefaultFiles();
app.UseStaticFiles();

app.Run(async (context) =>


{
await context.Response.WriteAsync("Hello World");
});
}

The UseDefaultFiles configures the DefaultFiles middleware which is a


part of StaticFiles middleware. This will automatically serve html file
named default.html, default.htm, index.html or index.htm on the
http request http://localhost:<port>. The above example will display
default.html file on http://localhost:<port> as shown below.

Ser
ving Static Files

Note:

Order of middleware is very important. app.UseDefaultFiles() should be added


before app.UseStaticFiles() in the request pipeline.
FileServer
The FileServer middleware combines the functionalities of
UseDefaultFiles and UseStaticFiles middlware. So, instead of using
both the middlware, just use UseFileServer in the Configure method.

UseFileServer = UseDefaultFiles + UseStaticFiles

Example: UseFileServer

Copy

public void Configure(IApplicationBuilder app, IHostingEnvironment


env)
{
app.UseFileServer();

app.Run(async (context) =>


{
await context.Response.WriteAsync("Hello World");
});
}

Thus, we can serve static files on http requests.

Serve static files from different folder


than wwwroot folder in ASP.NET Core
You can configure middleware to serve static files from other folders
along with default web root folder wwwroot.

For example, we will server admin.html from the following admin


folder and also test.html from wwwroot folder.
Now, configure the StaticFiles middleware in the Configure() method
of Startup class as shown below.

Example: Configure StaticFiles Middleware

Copy

public class Startup


{
// This method gets called by the runtime. Use this method to
configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment
env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles();

app.UseStaticFiles(new StaticFileOptions() {
FileProvider = new
PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),
"Content")),
RequestPath = new PathString("/Admin")
});

app.Run(async (context) =>


{
await context.Response.WriteAsync("Hello World!");
});
}
}

As you can see, app.UseStaticFiles() enables default web root folder


wwwroot to serve the static files.

app.UseStaticFiles(new StaticFileOptions() {
FileProvider = new
PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),
"admin")),
RequestPath = new PathString("/admin")
});

The above code configures Content admin folder to serve static files
on the request path /admin. So now, we will be able to execute HTTP
request http://localhost:1234/admin/admin.html to display static
admin.html page.

Fundamentals of Logging in .NET Core


.NET Core SDK is a light weight SDK which includes a bare minimum
set of features required to build an application. We can install NuGet
packages for other features we require for our application. For this,
Microsoft provides .NET APIs as .NET Extensions.

.NET Extensions is an open-source, cross-platform set of APIs for


commonly used programming patterns and utilities, such as
dependency injection, logging, and app configuration. Most APIs in
this project are meant to work on many .NET platforms, such as .NET
Core, .NET Framework, Xamarin, and other. While commonly used in
ASP.NET Core applications, these APIs are not coupled to the
ASP.NET Core application model. They can be used in console apps,
WinForms and WPF, etc. You can find the documentation and the
source code of extensions at https://github.com/aspnet/Extensions .

All the extensions are included under


the Microsoft.Extensions namespace. You can find all built-in and
third party extensions at nuget.org/packages .

The Logging API is included in


the Microsoft.Extensions.Logging package. The Logging API does not
work as standalone. It works with one or more logging providers that
store or display logs to a particular medium such as Console, Debug,
TraceListeners etc.

So, there are two important building blocks for implementing logging
in a .NET Core based application:

1. Logging API
2. Logging Providers

The following figure illustrates logging in .NET Core:

.NET Frameworks

As you can see in the above figure, the logging API


in Microsoft.Extensions.Logging works on the .NET Core based
applications whether it is ASP.NET Core or EF Core. You just need to
use the logging API with one or more logging providers to implement
logging in any .NET Core based application.

Logging API
As mentioned before, Microsoft provides logging API as an extension
in the wrapper Microsoft.Extensions.Logging which comes as a NuGet
package.

Microsoft.Extensions.Logging includesthe necessary classes and


interfaces for logging. The most important are the ILogger,
ILoggerFactory, ILoggerProvider interfaces and the LoggerFactory
class.

The following figure shows the relationship between logging classes.


Logging API

Let's have an overview of each of the above class.

ILoggerFactory
The ILoggerFactory is the factory interface for creating an
appropriate ILogger type instance and also for adding
the ILoggerProvider instance.

public interface ILoggerFactory : IDisposable


{
ILogger CreateLogger(string categoryName);
void AddProvider(ILoggerProvider provider);
}

The Logging API includes the built-in LoggerFactory class that


implements the ILoggerFactory interface. We can use it to add an
instance of type ILoggerProvider and to retrieve the ILogger instance
for the specified category. Visit ILoggerFactory and LoggerFactory for
more information.

ILoggerProvider
The ILoggerProvider manages and creates an appropriate logger,
specified by the logging category.

public interface ILoggerProvider : IDisposable


{
ILogger CreateLogger(string categoryName);
}
We can create our own logging provider by implementing
the ILoggerProvider interface. Visit ILoggerProvider for more
information.

ILogger
The ILogger interface includes methods for logging to the underlying
storage. There are many extension methods which make logging
easy. Visit ILogger for more information.

public interface ILogger


{
void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
Exception exception, Func<TState, Exception, string> formatter);
bool IsEnabled(LogLevel logLevel);
IDisposable BeginScope<TState>(TState state);
}

Logging Providers
A logging provider displays or stores logs to a particular medium
such as a console, a debugging event, an event log, a trace listener,
and others. Microsoft provides various logging providers as NuGet
packages.

The following table lists important logging providers.

Logging Provider's NuGet Package Output Target

Microsoft.Extensions.Logging.Console Console

Microsoft.Extensions.Logging.AzureAppServices Azure App Services 'Diagnostics logs' and 'Log stream' features

Microsoft.Extensions.Logging.Debug Debugger Monitor

Microsoft.Extensions.Logging.EventLog Windows Event Log

Microsoft.Extensions.Logging.EventSource EventSource/EventListener

Microsoft.Extensions.Logging.TraceSource Trace Listener

Microsoft has also collaborated with various logging framework teams


(including third parties like NLog, Serilog, Loggr, Log4Net, and
others) to extend the list of providers compatible
with Microsoft.Extensions.Logging. The following are some thrid-party
logging providers:

Logging Provider Description

elmah.io Provider for the Elmah.Io service

Loggr Provider for the Logger service

NLog Provider for the NLog library

Serilog Provider for the Serilog library

Let's take an example using


the Microsoft.Extensions.Logging.Console package which displays logs
on the Console.
ADVERTISEMENT

Console Logging Provider


Let's see how to display logs on the console using the NuGet package
for a console provider.

The Microsoft.Extensions.Logging.Console package includes logging


classes which send log output to the console.

The following figure illustrates how the logging API works with the
console logging provider.
Log
ging API with Console Logging Provider

As you can see in the above figure,


the ConsoleLogger implements ILogger, while
the ConsoleLoggingProvider implements ILoggingProvider.
The ConsoleLoggerExtensions class includes extension
method AddConsole(), which adds a console logger to
the LoggerFactory.

Now, let's see how to display logs on the Console in the .NET Core
console application.

First of all, create a new console application using the Console App
(.NET Core) template in Visual Studio 2017 (or later).

Now, you need to install a NuGet package


of Microsoft.Extensions.Logging. You can install it either using the
NuGet Package Manager or executing the following command in the
Package Manager Console.

PM> Install-Package Microsoft.Extensions.Logging

Now, you need to install a logging provider of your choice. Here, we


will send logs on the Console, so, install
the Microsoft.Extensions.Logging.Console package either using NPM or
execute the following command in the Package Manager Console in
Visual Studio.
PM> Install-Package Microsoft.Extensions.Logging.Console

After successfully installing the above two packages, you can now
implement logging in your .NET Core console application, as shown
below.

Example: Logging in .NET Core Console App

Copy

namespace DotnetCoreConsoleApp
{
class Program
{
static void Main(string[] args)
{
ILoggerFactory loggerFactory = new LoggerFactory(
new[] { new ConsoleLoggerProvider((_, __)
=> true, true) }
);
//or
//ILoggerFactory loggerFactory = new
LoggerFactory().AddConsole();

ILogger logger = loggerFactory.CreateLogger<Program>();


logger.LogInformation( "This is log message.");
}
}
}
Output:

info: DotnetCoreConsoleApp.Program[0]

This is log message.

In the above example, we created an object of


the LoggerFactory class and assigned it to the ILoggerFactory type
variable, as shown below.

ILoggerFactory loggerFactory = new LoggerFactory(


new[] { new ConsoleLoggerProvider ((_, __) => true, true) }
);
The LoggerFactory can contain one or more logging providers, which
can be used to log to multiple mediums concurrently. The constructor
of the LoggerFactory accepts an array of different logger provider
objects as new[] { }. We want to display logs on the console, so we
need to create an object of the console logger
provider ConsoleLoggerProvider.

There are four constructors of the ConsoleLoggerProvider. Use the one


that allows lambda expression (Func<>) for log filtration and
includeScope Boolean. Here, we don't want to filter any information
so the lambda expression would always return true (_, __) => true,
as shown below.

new ConsoleLoggerProvider((_, __) => true, true)

Then, we can use this object of the LoggerFactory to create a logger


using which we can actually log information, errors, warnings, traces,
debugs etc. loggerFactory.CreateLogger<Program>() creates a logger
specific to the Program class so that the logger will display a message
with context info, e.g. DotnetCoreConsoleApp.Program[0].

Most logging providers include an extension method


of ILoggerFactory, which is a shortcut to add a provider to the logger
factory. For example, to add a console logger provider to
the LoggerFactory, just call the LoggerFactory.AddConsole() extension
method with the same parameters as ConsoleLoggerProvider, as
shown below.

public ILoggerFactory loggerFactory = new


LoggerFactory().AddConsole();

This is more readable and maintainable than creating a logger


provider manually. The above logger factory will display the same
output as above.

Log Levels
Log levels indicate the importance or severity of log messages. Built-
in log providers include extension methods to indicate log levels.

The following table lists log levels in .NET Core.


Log Level Severity Extension Method Description

Trace 0 LogTrace() Logs messages only for tracing purposes for the developers.

Debug 1 LogDebug() Logs messages for short-term debugging purposes.

Information 2 LogInformation() Logs messages for the flow of the application.

Warning 3 LogWarning() Logs messages for abnormal or unexpected events in the application flow.

Error 4 LogError() Logs error messages.

Critical 5 LogCritical() Logs failures messages that require immediate attention.

We can use extension methods to indicate the level of the log


messages as shown below.

namespace DotnetCoreConsoleApp
{
class Program
{
static void Main(string[] args)
{
ILoggerFactory loggerFactory = new
LoggerFactory().AddConsole((_, __) => true);
ILogger logger = loggerFactory.CreateLogger<Program>();

logger.LogInformation( "Logging information.");


logger.LogCritical( "Logging critical information.");
logger.LogDebug("Logging debug information.");
logger.LogError("Logging error information.");
logger.LogTrace("Logging trace");
logger.LogWarning( "Logging warning.");
}
}
}

The above example will display the following output:


Logging in ASP.NET Core
ASP.NET Core uses the same logging mechanism as .NET Core
logging. So, it is highly recommended to go through the previous
chapter Logging in .NET Core before reading this.

Here, we will implement logging in the ASP.NET Core 2.x MVC


application.

As explained in the previous chapter, the logging API


in Microsoft.Extensions.Logging namespace works with one or more
built-in or third party logging providers. So, in an ASP.NET Core MVC
application, we will also have to install the NuGet
package Microsoft.Extensions.Logging and one or more logging
providers of our choice.

Create an ASP.NET Core MVC application in Visual Studio 2017 (or


later). When you create the ASP.NET Core MVC web application in
Visual Studio 2017 (or later), it automatically includes the NuGet
package for Microsoft.Extensions.Logging and the following logging
providers under the Microsoft.AspNetCore.App NuGet package. So, we
don't have to install it manually.

1. Microsoft.Extensions.Logging.Console
2. Microsoft.Extensions.Logging.Debug
3. Microsoft.Extensions.Logging.EventSource
4. Microsoft.Extensions.Logging.TraceSource
Add Logging Providers
As mentioned in the previous chapter, we need to add providers
in LoggerFactory. In the ASP.NET Core MVC application, the call to
the WebHost.CreateDefaultBuilder(args) method in the Program.cs
internally adds the Console, Debug, and EventSource logging
providers.

Example: Program.cs

Copy

public class Program


{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args)


=>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}

Look at the source code of the WebHost.CreateDefaultBuilder() method


on GitHub and you will find the following code:

.ConfigureLogging((hostingContext, logging) =>


{
logging.AddConfiguration(hostingContext.Configuration.GetSecti
on("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
}).

Thus, if you want to use these providers, no need to add them


manually. If you want to use other providers or any default provider,
then you need to remove all the existing providers and add the
provider of your choice. To configure logging providers, call
the ConfigureLogging() extension method of IWebHostBuilder, as shown
below.
Example: Program.cs

Copy

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logBuilder =>
{
logBuilder.ClearProviders(); // removes all providers from
LoggerFactory
logBuilder.AddConsole();
logBuilder.AddTraceSource("Information, ActivityTracing"); //
Add Trace listener provider
})
.UseStartup<Startup>();

In the above example, the ConfigureLogging() method takes action to


delegate Action<ILogBuilder> to configure logging providers. To add
logging providers of your choice, remove all the default providers
using ClearProviers() and then call the extension method of a
provider to add it, such as AddTraceSource() which will add the trace
listener provider, and the AddConsole() method which will add the
Console logging provider.

You can also configure the logging provider using ILoggerFactory in


the Configure() method of the Startup class. Let's see an example on
how to store logs in a text file.

Store Logs in a Text File


To store logs in a file, install the NuGet
package Serilog.Extensions.Logging.File . Serillog includes an
extension method for ILoggerFactory but not for ILogBuilder (in v
1.1.0). So, go to the Startup.cs file and add
the ILoggerFactory parameter in the Configure() method. Then, call
the AddFile() extension method to add Serillog file provider, as
shown below. ASP.NET Core dependency injection will automatically
pass an instance of the LoggerFactory for this parameter.

Example: Startup.cs

Copy
public void Configure(IApplicationBuilder app, IHostingEnvironment
env, ILoggerFactory loggerFactory)
{
// other code remove for clarity
loggerFactory.AddFile("Logs/mylog-{Date}.txt");
}

This will store all the logs in the mylog-<date>.txt file, under the
Logs folder in your application.
ADVERTISEMENT

Create Logs in the Controller


We can use ILogger or ILoggerFactory anywhere in an application
using ASP.NET Core DI (Dependency Injection). Consider the
following example of HomeController:

Example: Logging in MVC Controller

Copy

namespace AspDotNetCoreMvcApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger _logger;

public HomeController(ILogger<HomeController> logger){


_logger = logger;
}

public IActionResult Index()


{
_logger.LogInformation("Log message in the Index()
method");

return View();
}

public IActionResult About()


{
_logger.LogInformation("Log message in the About()
method");

return View();
}
}
}

In the above example, the ILogger<HomeController> parameter is


included in the constructor. ASP.NET Core DI will pass
the ILogger instance, which can be used to log in
the Index() and About() action methods.

Passing HomeController as generic type for


the ILogger<HomeController>, will be used as a category. For example,
specifying ILogger<HomeController< will display a fully qualified
name AspDotNetCoreMvcApp.Controllers.HomeController in the logs, as
shown below.

info: AspDoteNetCoreMvcApp.Controllers.HomeController[0]

Log message in the Index() method

Let's understand the above log message. Here, we logged


information using the LogInformation() method, so it starts with
"info:" followed by the fully qualified name of the class where a log is
created: AspDoteNetCoreMvcApp.Controllers.HomeController[0] . [0] is
the event id. You can specify this event id to identify a record, e.g.
Id, page number or other important information which uniquely
identifies a log. We didn't specify any event id, so it will be 0. The
next line is an actual log message: "Log message in the Index()
method".

The same can be achieved by passing ILoggerFactory in the


constructor.

public class HomeController : Controller


{
private readonly ILogger _logger;

public HomeController(ILoggerFactory logFactory)


{
_logger = logFactory.CreateLogger<HomeController>();
}
public IActionResult Index()
{
_logger.LogInformation("Log message in the Index() method");

return View();
}

public IActionResult About()


{
_logger.LogInformation("Log message in the About() method");

return View();
}
}

Now, run the above application from command prompt by navigating


to /<app root folder>/bin/debug/netcoreapp2.1/ , run the dotnet <app
name>.dll command and then open http://localhost:5000 in the
browser. It will display the same logs on the Console as above.

Logs:
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Route matched with {action = "Index", controller = "Home"}. Executing acti
on AspDoteNetCoreMvcApp.Controllers.HomeController.Index (AspDotNetCoreMvcApp)
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method AspDoteNetCoreMvcApp.Controllers.HomeController.In
dex (AspDotNetCoreMvcApp) - Validation state: Valid
info: AspDoteNetCoreMvcApp.Controllers.HomeController[0]
Log message in the Index() method
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action method AspDoteNetCoreMvcApp.Controllers.HomeController.Ind
ex (AspDotNetCoreMvcApp), returned result Microsoft.AspNetCore.Mvc.ViewResult in
0.8505ms.
info: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[1]
Executing ViewResult, running view Index.
info: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[4]
Executed ViewResult - view Index executed in 231.2839ms.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action AspDoteNetCoreMvcApp.Controllers.HomeController.Index (Asp
DotNetCoreMvcApp) in 288.6931ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 946.274ms 200 text/html; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/images/banner1.svg
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/images/banner2.svg
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 5.6471ms 404
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 6.5811ms 404
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/css/site.min.css
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 0.2811ms 404
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/js/site.min.js
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/images/banner3.svg
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 0.178ms 404
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 0.2342ms 404
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/css/site.min.css
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 0.1173ms 404
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/js/site.min.js
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 0.2539ms 404
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/favicon.ico
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 0.3253ms 404

Thus, we can implement logging in ASP.NET Core MVC application.

.NET Core Application Types


We can create two types of applications in .NET Core.

1. Portable Application
2. Self-contained application

Portable Application
Portable applications are applications which expect .NET Core
runtime on the deployment machines. It cannot be run on a machine
which does not have .NET Core runtime installed.

.NET Core
Portable Application

Self-contained Application
Self-contained applications are applications which include .NET Core
runtime when we publish it. It can run on a machine which does not
have .NET Core runtime installed.
.NET Core Self-contained Application

Configure Application Type


We can configure ASP.NET Core application as portable or self-
contained application using type property
of Microsoft.NETCore.App dependency in project.json. The
"type":"platform" indicates that this application expects .NET Core on
the machine. This makes it a portable application.

For the self-contained application, remove type-platform from the


dependency. This makes it a self-contained application which
means .NET Core will be included when you build and publish an
application.

Code Sharing in .NET Core


With .NET Core, we can currently develop applications with three
different .NET frameworks for different platforms. The traditional or
standard .NET Framework is for Windows, Mono framework for iOS,
OSx and Android and .NET Core for Windows, Mac and Linux.

.NET Frameworks

These frameworks use different framework class libraries. It means


code written in one framework cannot be used with other
frameworks. For example, a console application developed with .NET
Framework cannot run on .NET Core or vice-versa. Thus, code-
sharing is not allowed.

It would be nice to write code once and share with other applications
with different .NET frameworks. Isn't it?

Co
de Sharing

To solve this problem of code sharing, we can use the following three
approaches:
1. Create Portable Class Library
2. Target Multiple Frameworks ASP.NET Core app
3. Target .NET Standard

Creating portable class library to share code with other .NET


frameworks is not a new thing in .NET. Learn about it here.

Learn about how to target multiple frameworks in ASP.NET Core


application for code sharing in the next chapter.

Target Multiple Frameworks in .NET Core


2.x App
As mentioned in the previous chapter, creating a .NET Core
application which targets multiple frameworks is one of the
approaches for code sharing.

We can create .NET Core application and configure multiple target


frameworks for it so that it can run with all the configured target
frameworks. To demonstrate this, let's create .NET Core 2.0 console
application which can run with .NET Core as well as traditional .NET
framework in Visual Studio 2017.

The first step is to create a new project in Visual Studio 2017 by


clicking on File -> New Project.. This will open New Project popup as
shown below.
Create .NET Core 2.x Console Application

In the New Project popup, select Console Application (.NET Core),


provide the appropriate name and click OK. This will create new
console project as shown below.
Console Application

Now, we can configure multiple frameworks by editing .csproj file.


So, right click on the project in solution explorer and select Edit
<project-name>.csproj as shown below.
Edi
t .csproj

The .csproj will look like below.

.csproj:

Copy

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>

</Project>
As you can see above, <TargetFramework> is netcoreapp2.0. It means
currently this application can run on .NET Core 2.0 framework. We
can include multiple monikers for multiple frameworks here, in order
to target multiple frameworks.

To target multiple frameworks, change <TargetFramework> to


plural <TargetFrameworks> and include monikers for different
frameworks you want to target separated by ;.

Here, we will support two more frameworks .NET Framework 4.0 &
4.6. So include net40 and net46 monikers respectively as shown
below. Look at TFMs for all supported target frameworks here.

.csproj:

Copy

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp2.0;net45;net46</TargetFrameworks>
</PropertyGroup>

</Project>
ADVERTISEMENT

As soon as you save the above .csproj file, Visual Studio will load and
include the references for .NET 4.5 and .NET 4.6
into Dependencies section as shown below.
Multi Frameworks Dependencies

Now, open program.cs and let's add framework specific code using
preprocessor conditions #if and #elif as shown below.

Program.cs

Copy

using System;

namespace MultiFrameworkConsole
{
public class Program
{
public static void Main(string[] args)
{

#if NET40
Console.WriteLine("Target framework: .NET Framework 4.0");
#elif NET45
Console.WriteLine("Target framework: .NET Framework 4.5");
#else
Console.WriteLine("Target framework: .NET Core 2.0");
#endif
Console.ReadKey();
}
}
}

As you can see above, to write framework specific code, use symbol
with condition for .NET framework moniker and replace the dot with
an underscore and change lowercase letters to uppercase.

To run the application for specific framework, click on the run


dropdown and select a targeted framework as shown below.

Multi
Frameworks Dependencies

Now, run the application and you will see the following output.
Framework Specific References
Sometimes you may need to include specific references for a
particular framework. For example, .NET Core 2.0 meta package
already includes System.Net reference which is not included in .NET
4.0 and 4.5. So, we need to include it in .csproj file using conditional
reference as shown below.

.csproj:

Copy

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp2.0;net45;net46</TargetFrameworks>
</PropertyGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'net40' ">


<Reference Include="System.Net" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net45' ">
<Reference Include="System.Net" />
</ItemGroup>

</Project>
Now, System.Net reference will be added to .NET 4.0 & 4.5 and
System.Net specific code will be executed for all frameworks.

ASP.NET MVC Tutorials


ASP.NET is a free web framework for building websites and web
applications on .NET Framework using HTML, CSS, and JavaScript.

ASP.NET MVC 5 is a web framework based on Model-View-Controller


(MVC) architecture. Developers can build dynamic web applications
using ASP.NET MVC framework that enables a clean separation of
concerns, fast development, and TDD friendly.

These tutorials are designed for beginners and professionals who


want to learn ASP.NET MVC 5.

Prerequisites
Basic knowledge of .NET Framework 4.5, C#, and Visual Studio is
required.

ASP.NET MVC Architecture


Here, you will learn an overview of MVC architecture.

The MVC architectural pattern has existed for a long time in software
engineering. All most all the languages use MVC with slight variation,
but conceptually it remains the same.

Let's understand the MVC architecture supported in ASP.NET.


MVC stands for Model, View, and Controller. MVC separates an
application into three components - Model, View, and Controller.

Model: Model represents the shape of the data. A class in C# is used


to describe a model. Model objects store data retrieved from the
database.

Model represents the data .

View: View in MVC is a user interface. View display model data to


the user and also enables them to modify them. View in ASP.NET
MVC is HTML, CSS, and some special syntax (Razor syntax) that
makes it easy to communicate with the model and the controller.

View is the User Interface.

Controller: The controller handles the user request. Typically, the


user uses the view and raises an HTTP request, which will be handled
by the controller. The controller processes the request and returns
the appropriate view as a response.

Controller is the request handler.

The following figure illustrates the interaction between Model, View,


and Controller.

MVC Architecture
The following figure illustrates the flow of the user's request in
ASP.NET MVC.

Request
Flow in MVC Architecture

As per the above figure, when a user enters a URL in the browser, it
goes to the webserver and routed to a controller. A controller
executes related view and models for that request and create the
response and sends it back to the browser.

Points to Remember

1. MVC stands for Model, View and Controller.


2. Model represents the data
3. View is the User Interface.
4. Controller is the request handler.

ASP.NET MVC Version History


Microsoft had introduced ASP.NET MVC in .NET 3.5, since then lots of
new features have been added.

The following table list brief history of ASP.NET MVC.

MVC Version Visual Studio .NET Framework Released Date Features


MVC 1.0 VS2008 .Net 3.5 13-Mar-2009  MVC architecture with webform engine
 Routing
 HTML Helpers
 Ajax Helpers
 Auto binding
MVC Version Visual Studio .NET Framework Released Date Features
MVC 2.0 VS 2008, .Net 3.5/4.0 10-Mar-2010  Area
 Asynchronous controller
 Html helper methods with lambda expression
 DataAnnotations attributes
 Client side validation
 Custom template
 Scaffolding

MVC 3.0 VS 2010 .Net 4.0 13-Jan-2011  Unobtrusive javascript validation


 Razor view engine
 Global filters
 Remote validation
 Dependency resolver for IoC
 ViewBag

MVC 4.0 VS 2010 SP1, .NET 4.0/4.5 15-Aug-2012  Mobile project template
VS 2012  Bundling and minification
 Support for Windows Azure SDK

MVC 5.0 VS 2013 .NET 4.5 17-oct-2013  Authentication filters


 Bootstrap support
 New scaffolding items
 ASP.Net Identity

MVC 5.2 - Current VS 2013 .NET 4.5 28-Aug-2014  Attribute based routing
 bug fixes and minor features update

Create ASP.NET MVC Application


In this section, we will create a new MVC web application using Visual
Studio and understand the basic building blocks of the ASP.NET MVC
Application.

We are going to use ASP.NET MVC v5.2, and Visual Studio 2017
community edition, and .NET Framework 4.6 to create our first MVC
application.

Download the latest version of Visual Studio


from visualstudio.microsoft.com/downloads .

Open Visual Studio 2017 and select File menu -> New -> Project,
as shown below.
Create a New Project in Visual Studio

From the New Project dialog as shown below, expand Visual C#


node and select Web in the left pane, and then select ASP.NET Web
Application (.NET Framework) in the middle pane. Enter the
name of your project MyMVCApplication. (You can give an appropriate
name for your application). Also, you can change the location of the
MVC application by clicking on Browse.. button. Finally, click OK.

From the New ASP.NET Web Application dialog, select MVC (if not
selected already) as shown below.
Select MVC Project Template

You can also change the authentication by clicking on Change


Authentication button. You can select appropriate authentication
mode for your application, as shown below.

Sel
ect Authenctication Type
Here, we are keeping the default authentication for our application
which is No Authentication. Click OK to continue.

Wait for some time till Visual Studio creates a simple MVC project
using the default template, as shown below.

MVC Project in Visual Studio

Now, press F5 to run the project in debug mode or Ctrl + F5 to run


the project without debugging. It will open the home page in the
browser, as shown below.
AS
P.NET MVC Application

MVC 5 project includes JavaScript and CSS files of bootstrap 3.0 by


default. So you can create responsive web pages. This responsive UI
will change its look and feel based on the screen size of the different
devices. For example, the top menu bar will be changed in the mobile
devices, as shown below.
Responsive MVC Application

In this way, you can create your ASP.NET MVC 5 application using
Visual Studio 2017.

ASP.NET MVC Folder Structure


Here, you will learn about the ASP.NET MVC project structure. Visual
Studio creates the following folder structure of the ASP.NET MVC
application by default.
MVC Folder Structure

Let's see significance of each folder.

App_Data
The App_Data folder can contain application data files like
LocalDB, .mdf files, XML files, and other data related files. IIS will
never serve files from App_Data folder.

App_Start
The App_Start folder can contain class files that will be executed
when the application starts. Typically, these would be config files like
AuthConfig.cs, BundleConfig.cs, FilterConfig.cs, RouteConfig.cs etc.
MVC 5 includes BundleConfig.cs, FilterConfig.cs and RouteConfig.cs
by default. We will see the significance of these files later.
App_Start Folder

Content
The Content folder contains static files like CSS files, images, and
icons files. MVC 5 application includes bootstrap.css,
bootstrap.min.css, and Site.css by default.

Content Folder
Controllers
The Controllers folder contains class files for the controllers.
A Controller handles users' request and returns a response. MVC
requires the name of all controller files to end with "Controller". You
will learn about the controller in the next section.

Controller Folder
ADVERTISEMENT

fonts
The Fonts folder contains custom font files for your application.
Fonts folder

Models
The Models folder contains model class files. Typically model class
includes public properties, which will be used by the application to
hold and manipulate application data.

Scripts
The Scripts folder contains JavaScript or VBScript files for the
application. MVC 5 includes javascript files for bootstrap, jquery
1.10, and modernizer by default.
Scripts Folder

Views
The Views folder contains HTML files for the application. Typically
view file is a .cshtml file where you write HTML and C# or VB.NET
code.

The Views folder includes a separate folder for each controller. For
example, all the .cshtml files, which will be rendered by
HomeController will be in View > Home folder.

The Shared folder under the View folder contains all the views shared
among different controllers e.g., layout files.
View Folder

Additionally, MVC project also includes the following configuration


files:

Global.asax
Global.asax file allows you to write code that runs in response to
application-level events, such as Application_BeginRequest,
application_start, application_error, session_start, session_end, etc.
Packages.config
Packages.config file is managed by NuGet to track what packages
and versions you have installed in the application.

Web.config
Web.config file contains application-level configurations.

Routing in MVC
In the ASP.NET Web Forms application, every URL must match with a
specific .aspx file. For example, a URL
http://domain/studentsinfo.aspx must match with the file
studentsinfo.aspx that contains code and markup for rendering a
response to the browser.

Routing is not specific to the MVC framework. It can be used with ASP.NET
Webform application or MVC application.

ASP.NET introduced Routing to eliminate the needs of mapping each


URL with a physical file. Routing enables us to define a URL pattern
that maps to the request handler. This request handler can be a file
or class. In ASP.NET Webform application, request handler is .aspx
file, and in MVC, it is the Controller class and Action method. For
example, http://domain/students can be mapped to
http://domain/studentsinfo.aspx in ASP.NET Webforms, and the
same URL can be mapped to Student Controller and Index action
method in MVC.

Route
Route defines the URL pattern and handler information. All the
configured routes of an application stored in RouteTable and will be
used by the Routing engine to determine appropriate handler class or
file for an incoming request.
The following figure illustrates the Routing process.

Routing in MVC

Configure a Route
Every MVC application must configure (register) at least one route
configured by the MVC framework by default. You can register a
route in RouteConfig class, which is in RouteConfig.cs under App_Start folder.
The following figure illustrates how to configure a route in
the RouteConfig class .
Configure Routes in MVC

As you can see in the above figure, the route is configured using
the MapRoute() extension method of RouteCollection, where name is
"Default", url pattern is "{controller}/{action}/{id}" and defaults
parameter for controller, action method and id parameter. Defaults
specify which controller, action method, or value of id parameter
should be used if they do not exist in the incoming request URL.

In the same way, you can configure other routes using


the MapRoute() method of the RouteCollection class. This RouteCollection is
actually a property of the RouteTable class.

URL Pattern
The URL pattern is considered only after the domain name part in the
URL. For example, the URL
pattern "{controller}/{action}/{id}" would look like
localhost:1234/{controller}/{action}/{id}. Anything after
"localhost:1234/" would be considered as a controller name. The
same way, anything after the controller name would be considered as
action name and then the value of id parameter.
Routing in MVC

If the URL doesn't contain anything after the domain name, then the
default controller and action method will handle the request. For
example, http://localhost:1234 would be handled by the HomeController and
the Index() method as configured in the default parameter.

The following table shows which Controller, Action method, and Id


parameter would handle different URLs considering the above default
route.

URL Controller Action Id

http://localhost/home HomeController Index null

http://localhost/home/index/123 HomeController Index 123

http://localhost/home/about HomeController About null

http://localhost/home/contact HomeController Contact null

http://localhost/student StudentController Index null

http://localhost/student/edit/123 StudentController Edit 123


ADVERTISEMENT

Multiple Routes
You can also configure a custom route using the MapRoute extension
method. You need to provide at least two parameters in MapRoute,
route name, and URL pattern. The Defaults parameter is optional.

You can register multiple custom routes with different names.


Consider the following example where we register "Student" route.

Example: Custom Routes


Copy

public class RouteConfig


{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Student",
url: "students/{id}",
defaults: new { controller = "Student", action = "Index"}
);

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id
= UrlParameter.Optional }
);
}
}

As shown in the above code, the URL pattern for the Student route
is students/{id}, which specifies that any URL that starts
with domainName/students, must be handled by the StudentController. Notice
that we haven't specified {action} in the URL pattern because we want
every URL that starts with students should always use
the Index() action of the StudentController class. We have specified the
default controller and action to handle any URL request, which starts
from domainname/students.

MVC framework evaluates each route in sequence. It starts with the


first configured route, and if incoming URL doesn't satisfy the URL
pattern of the route, then it will evaluate the second route and so on.
In the above example, routing engine will evaluate the Student route
first and if incoming URL doesn't start with /students then only it will
consider the second route which is the default route.

The following table shows how different URLs will be mapped to


the Student route:
URL Controller Action Id

http://localhost/student/123 StudentController Index 123

http://localhost/student/index/123 StudentController Index 123

http://localhost/student?Id=123 StudentController Index 123

Route Constraints
You can also apply restrictions on the value of the parameter by
configuring route constraints. For example, the following route
applies a limitation on the id parameter that the id's value must be
numeric.

Example: Route Constraints

Copy

routes.MapRoute(
name: "Student",
url: "student/{id}/{name}/{standardId}",
defaults: new { controller = "Student", action = "Index", id =
UrlParameter.Optional, name = UrlParameter.Optional, standardId =
UrlParameter.Optional },
constraints: new { id = @"\d+" }
);

So if you give non-numeric value for id parameter, then that request


will be handled by another route or, if there are no matching routes,
then "The resource could not be found" error will be thrown.

Register Routes
Now, after configuring all the routes in the RouteConfig class, you need
to register it in the Application_Start() event in the Global.asax so that it
includes all your routes into the RouteTable.

Example: Route Registration

Copy

public class MvcApplication : System.Web.HttpApplication


{
protected void Application_Start()
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}

The following figure illustrate Route registration process.

Register Route

Thus, routing plays important role in MVC framework.

Points to Remember :

1. Routing plays important role in the MVC framework. Routing maps URL to
physical file or class (controller class in MVC).
2. Route contains URL pattern and handler information. URL pattern starts
after the domain name.
3. Routes can be configured in RouteConfig class. Multiple custom routes can
also be configured.
4. Route constraints apply restrictions on the value of parameters.
5. Route must be registered in Application_Start event in Global.ascx.cs file.

ontrollers in ASP.NET MVC


In this section, you will learn about the Controller in ASP.NET MVC.

The Controller in MVC architecture handles any incoming URL


request. The Controller is a class, derived from the base
class System.Web.Mvc.Controller . Controller class contains public methods
called Action methods. Controller and its action method handles
incoming browser requests, retrieves necessary model data and
returns appropriate responses.

In ASP.NET MVC, every controller class name must end with a word
"Controller". For example, the home page controller name must
be HomeController, and for the student page, it must be
the StudentController. Also, every controller class must be located in
the Controller folder of the MVC folder structure.

Adding a New Controller


Now, let's add a new empty controller in our MVC application in
Visual Studio.

MVC will throw "The resource cannot be found" error when you do not append
"Controller" to the controller class name.

In the previous section, we learned how to create our first MVC


application, which created a default HomeController. Here, we will create
new StudentController class.

In the Visual Studio, right click on the Controller folder ->


select Add -> click on Controller..
Ad
d New Controller

This opens Add Scaffold dialog, as shown below.

Note:

Scaffolding is an automatic code generation framework for ASP.NET web


applications. Scaffolding reduces the time taken to develop a controller, view, etc.
in the MVC framework. You can develop a customized scaffolding template using T4
templates as per your architecture and coding standards.
Ad
ding Controller

Add Scaffold dialog contains different templates to create a


new controller. We will learn about other templates later. For now,
select "MVC 5 Controller - Empty" and click Add. It will open the Add
Controller dialog, as shown below

Ad
ding Controller

In the Add Controller dialog, enter the name of the controller.


Remember, the controller name must end with Controller.
Write StudentController and click Add.
Ad
ding Controller

This will create the StudentController class with the Index() method
in StudentController.cs file under the Controllers folder, as shown below.

Example: Controller

Copy

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
return View();
}
}
}

As you can see above, the StudentController class is derived from


the Controller class. Every controller in MVC must be derived from this
abstract Controller class. This base Controller class contains helper
methods that can be used for various purposes.

Now, we will return a dummy string from the Index action method of
above the StudentController. Changing the return type of Index method
from ActionResult to string and returning dummy string is shown
below. You will learn about the ActionResult in the next section.

Example: Controller
Copy

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
// GET: Student
public string Index()
{
return "This is Index action method of
StudentController";
}
}
}

We have already seen in the routing section that the URL


request http://localhost/student or http://localhost/student/index is handled
by the Index() method of the StudentController class, as shown above. So
let's invoke it from the browser and you will see the following page in
the browser.

Con
troller

Points to Remember :
1. The Controller handles incoming URL requests. MVC routing sends requests
to the appropriate controller and action method based on URL and
configured Routes.
2. All the public methods in the Controller class are called Action methods.
3. The Controller class must be derived from System.Web.Mvc.Controller class.
4. The Controller class name must end with "Controller".
5. A new controller can be created using different scaffolding templates. You
can create a custom scaffolding template also.

Action method
In this section, you will learn about the action method of the
controller class.

All the public methods of the Controller class are called Action methods.
They are like any other normal methods with the following
restrictions:

1. Action method must be public. It cannot be private or protected


2. Action method cannot be overloaded
3. Action method cannot be a static method.

The following illustrates the Index() action method in


the StudentController class.

Action Method

As you can see in the above figure, the Index() method is public, and
it returns the ActionResult using the View() method. The View() method is
defined in the Controller base class, which returns the
appropriate ActionResult.
Default Action Method
Every controller can have a default action method as per the
configured route in the RouteConfig class. By default, the Index() method
is a default action method for any controller, as per configured
default root, as shown below.

Default Route

Copy

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{name}",
defaults: new { controller = "Home",
action = "Index",
id = UrlParameter.Optional
});

However, you can change the default action name as per your
requirement in the RouteConfig class.

ActionResult
MVC framework includes various Result classes, which can be returned
from an action method. The result classes represent different types
of responses, such as HTML, file, string, JSON, javascript, etc. The
following table lists all the result classes available in ASP.NET MVC.

Result Class Description

ViewResult Represents HTML and markup.

EmptyResult Represents No response.

ContentResult Represents string literal.

FileContentResult/ FilePathResult/ FileStreamResult Represents the content of a file.

JavaScriptResult Represent a JavaScript script.

JsonResult Represent JSON that can be used in AJAX.

RedirectResult Represents a redirection to a new URL.


Result Class Description

RedirectToRouteResult Represent another action of same or other controller.

PartialViewResult Returns HTML from Partial view.

HttpUnauthorizedResult Returns HTTP 403 status.


ADVERTISEMENT

The ActionResult class is a base class of all the above result classes, so
it can be the return type of action method that returns any result
listed above. However, you can specify the appropriate result class
as a return type of action method.

The Index() method of the StudentController in the above figure uses


the View() method to return a ViewResult (which is derived from
the ActionResult class). The base Controller class includes
the View() method along with other methods that return a particular
type of result, as shown in the below table.

Result Class Description Base Controller Method

ViewResult Represents HTML and markup. View()

EmptyResult Represents No response.

ContentResult Represents string literal. Content()

FileContentResult, Represents the content of a file. File()


FilePathResult,
FileStreamResult

JavaScriptResult Represents a JavaScript script. JavaScript()

JsonResult Represents JSON that can be used in AJAX. Json()

RedirectResult Represents a redirection to a new URL. Redirect()

RedirectToRouteResult Represents redirection to another route. RedirectToRoute()

PartialViewResult Represents the partial view result. PartialView()

HttpUnauthorizedResult Represents HTTP 403 response.

As you can see in the above table, the View() method returns
the ViewResult, the Content() method returns a string, the File() method
returns the content of a file, and so on. Use different methods
mentioned in the above table to return a different type of result from
an action method.

Action Method Parameters


Every action methods can have input parameters as normal methods.
It can be primitive data type or complex type parameters, as shown
below.

Example: Action Method Parameters

Copy

[HttpPost]
public ActionResult Edit(Student std)
{
// update student to the database

return RedirectToAction("Index");
}

[HttpDelete]
public ActionResult Delete(int id)
{
// delete student from the database whose id matches with
specified id

return RedirectToAction("Index");
}

Please note that action method paramter can be Nullable Type.

By default, the values for action method parameters are retrieved


from the request's data collection. The data collection includes
name/values pairs for form data or query string values or cookie
values. Model binding in ASP.NET MVC automatically maps the URL
query string or form data collection to the action method parameters
if both names match. Visit model binding section for more
information on it.

Points to Remember :

1. All the public methods in the Controller class are called Action methods.
2. The Action method has the following restrictions.
- Action method must be public. It cannot be private or protected.
- Action method cannot be overloaded.
- Action method cannot be a static method.
3. ActionResult is a base class of all the result type which returns from Action
method.
4. The base Controller class contains methods that returns appropriate result
type e.g. View(), Content(), File(), JavaScript() etc.
5. The Action method can include Nullable type parameters.

ction Selectors
Action selector is the attribute that can be applied to the action
methods. It helps the routing engine to select the correct action
method to handle a particular request. MVC 5 includes the following
action selector attributes:

1. ActionName
2. NonAction
3. ActionVerbs

ActionName
The ActionName attribute allows us to specify a different action name
than the method name, as shown below.

Example: Specify a different action name


Copy
public class StudentController : Controller
{
public StudentController()
{
}

[ActionName("Find")]
public ActionResult GetById(int id)
{
// get student from the database
return View();
}
}

In the above example, we have applied ActioName("find") attribute to


the GetById() action method. So now, the action method name
is Find instead of the GetById. So now, it will be invoked
on http://localhost/student/find/1 request instead
of http://localhost/student/getbyid/1 request.

NonAction
Use the NonAction attribute when you want public method in a
controller but do not want to treat it as an action method.

In the following example, the Index() method is an action method, but


the GetStudent() is not an action method.

Example: NonAction
Copy
public class StudentController : Controller
{
public string Index()
{
return "This is Index action method of StudentController";
}

[NonAction]
public Student GetStudent(int id)
{
return studentList.Where(s => s.StudentId ==
id).FirstOrDefault();
}
}

ActionVerbs: HttpGet, HttpPost, HttpPut


The ActionVerbs selector is to handle different type of Http requests.
The MVC framework includes HttpGet, HttpPost, HttpPut, HttpDelete,
HttpOptions, and HttpPatch action verbs. You can apply one or more
action verbs to an action method to handle different HTTP requests.
If you don't apply any action verbs to an action method, then it will
handle HttpGet request by default.
The following table lists the usage of HTTP methods:

Http method Usage

GET To retrieve the information from the server. Parameters will be appended in the query string.

POST To create a new resource.

PUT To update an existing resource.

HEAD Identical to GET except that server do not return the message body.

OPTIONS It represents a request for information about the communication options supported by the web server.

DELETE To delete an existing resource.

PATCH To full or partial update the resource.

Visit W3.org for more information on Http Methods.

The following example shows how to handle different types of HTTP


requests in the Controller using ActionVerbs:

Example: Handle HTTP Requests in the Controller

Copy

public class StudentController : Controller


{
public ActionResult Index() // handles GET requests by default
{
return View();
}

[HttpPost]
public ActionResult PostAction() // handles POST requests by
default
{
return View("Index");
}

[HttpPut]
public ActionResult PutAction() // handles PUT requests by default
{
return View("Index");
}
[HttpDelete]
public ActionResult DeleteAction() // handles DELETE requests by
default
{
return View("Index");
}

[HttpHead]
public ActionResult HeadAction() // handles HEAD requests by
default
{
return View("Index");
}

[HttpOptions]
public ActionResult OptionsAction() // handles OPTION requests by
default
{
return View("Index");
}

[HttpPatch]
public ActionResult PatchAction() // handles PATCH requests by
default
{
return View("Index");
}
}

You can also apply multiple action verbs using


the AcceptVerbs attribute, as shown below.

Example: AcceptVerbs

Copy

[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]
public ActionResult GetAndPostAction()
{
return RedirectToAction("Index");
}

Model in ASP.NET MVC


In this section, you will learn about the model class in ASP.NET MVC
framework.

The model classes represents domain-specific data and business logic


in the MVC application. It represents the shape of the data as public
properties and business logic as methods.

In the ASP.NET MVC Application, all the Model classes must be


created in the Model folder.

Adding a Model Class


Let's create the model class that should have the required properties
for the Student entity.

In the MVC application in Visual Studio, and right-click on


the Model folder, select Add -> and click on Class... It will open
the Add New Item dialog box.

In the Add New Item dialog box, enter the class name Student and
click Add.

Cre
ate Model Class
This will add a new Student class in model folder. We want this model
class to store id, name, and age of the students. So, we will have to
add public properties for Id, Name, and Age, as shown below.

Example: Model class

Copy

public class Student


{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}

The model class can be used in the view to populate the data, as well
as sending data to the controller.

Create a View in ASP.NET MVC


In this section, you will learn how to create a view and use the model
class in it in the ASP.NET MVC application.

A view is used to display data using the model class object.


The Views folder contains all the view files in the ASP.NET MVC
application.

A controller can have one or more action methods, and each action
method can return a different view. In short, a controller can render
one or more views. So, for easy maintenance, the MVC framework
requires a separate sub-folder for each controller with the same
name as a controller, under the Views folder.

For example, all the views rendered from the HomeController will resides
in the Views > Home folder. In the same way, views
for StudentController will resides in Views > Student folder, as shown
below.
View folders for Controllers

Note:

The Shared folder contains views, layout views, and partial views, which will be
shared among multiple controllers.

Razor View Engine


Microsoft introduced the razor view engine to compile a view with a
mix of HTML tags and server-side code. The special syntax for razor
view maximizes the speed of writing code by minimizing the number
of characters and keystrokes required when writing a view.

The razor view uses @ character to include the server-side code


instead of the traditional <% %> of ASP. You can use C# or Visual
Basic syntax to write server-side code inside the razor view.

ASP.NET MVC supports the following types of razor view files:

File extension Description

.cshtml C# Razor view. Supports C# code with html tags.


File extension Description

.vbhtml Visual Basic Razor view. Supports Visual Basic code with html tags.

.aspx ASP.Net web form

.ascx ASP.NET web control

Learn Razor syntax in the next section.

Creating a View
You can create a view for an action method directly from it by right
clicking inside an action method and select Add View...

The following creates a view from the Index() action method of


the StudentContoller, as shown below.

Create a View from Action Method

This will open the Add View dialogue box, shown below. It's good
practice to keep the view name the same as the action method name
so that you don't have to explicitly specify the view name in the
action method while returning the view.
Ad
d a View

Select the scaffolding template. Template dropdown will show default


templates available for Create, Delete, Details, Edit, List, or Empty
view. Select "List" template because we want to show the list of
students in the view.
ADVERTISEMENT

Now, select Student from the model class dropdown. The model class
dropdown automatically displays the name of all the classes in
the Model folder. We have already created the Student model class in
the previous section, so it would be included in the dropdown.
Ad
d a View

Check "Use a layout page" checkbox and select the


default _Layout.cshtml page for this view and then click Add button.

This will create the Index view under View -> Student folder, as
shown below:
View

The following code snippet shows an Index.cshtml created above.

Views\Student\Index.cshtml:

Copy

@model IEnumerable<MVC_BasicTutorials.Models.Student>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.StudentName)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>

@foreach (var item in Model) {


<tr>
<td>
@Html.DisplayFor(modelItem => item.StudentName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new
{ id=item.StudentId }) |
@Html.ActionLink("Details", "Details", new
{ id=item.StudentId }) |
@Html.ActionLink("Delete", "Delete", new { id =
item.StudentId })
</td>
</tr>
}

</table>

As you can see in the above Index view, it contains both HTML and
razor codes. Inline razor expression starts with @ symbol. @Html is a
helper class to generate HTML controls. You will learn razor syntax
and HTML helpers in the coming sections.
Index.cs
html

The above Index view would look as below when we run the
application.
Ind
ex View

Note:

Every view in the ASP.NET MVC is derived from WebViewPage class included
in System.Web.Mvc namespace.

We need to pass a model object to a view in order to display the data


on the view. Learn how to integrate a model, view, and controller in
the next chapter.

Integrate Controller, View and Model


We have already created a Controller, a model and a view in the
previous sections. Here, we will integrate them to run the application
and see the result.
The following code snippet shows the StudentController,
the Student model, and the Index.cshtml view created in the previous
sections.

Example: StudentController

Copy

public class StudentController : Controller


{
// GET: Student
public ActionResult Index()
{
return View();
}
}
Example: Student Model class

Copy

public class Student


{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
Example: Index.cshtml View

Copy

@model IEnumerable<MVC_BasicTutorials.Models.Student>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.StudentName)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>

@foreach (var item in Model) {


<tr>
<td>
@Html.DisplayFor(modelItem => item.StudentName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new
{ id=item.StudentId }) |
@Html.ActionLink("Details", "Details", new
{ id=item.StudentId }) |
@Html.ActionLink("Delete", "Delete", new { id =
item.StudentId })
</td>
</tr>
}

</table>

Now, to run it successfully, we need to pass a model object from an


action method to a view. As you can see in the above Index.cshtml, it
uses IEnumerable<Student> as a model type. So we need to pass it
from the Index() action method of the StudentController class, as
shown below.

Example: Passing Model from Controller

Copy

public class StudentController : Controller


{
static IList<Student> studentList = new List<Student>{
new Student() { StudentId = 1, StudentName = "John",
Age = 18 } ,
new Student() { StudentId = 2, StudentName = "Steve",
Age = 21 } ,
new Student() { StudentId = 3, StudentName = "Bill",
Age = 25 } ,
new Student() { StudentId = 4, StudentName = "Ram" ,
Age = 20 } ,
new Student() { StudentId = 5, StudentName = "Ron" ,
Age = 31 } ,
new Student() { StudentId = 4, StudentName = "Chris" ,
Age = 17 } ,
new Student() { StudentId = 4, StudentName = "Rob" ,
Age = 19 }
};
// GET: Student
public ActionResult Index()
{
//fetch students from the DB using Entity Framework here

return View(studentList);
}
}
Try it

As you can see in the above code, we have created a list of student
objects for an example purpose (in real-life application, you can fetch
it from the database). We then pass this list object as a parameter in
the View() method. The View() method is defined in the base
Controller class, which automatically binds a model object to a view.

Now, you can run the MVC project by pressing F5 and navigate
to http://localhost/Student. You will see the following view in the
browser.
jQuery Tutorial
Welcome to jQuery tutorials section. jQuery is a fast, small and
feature-rich JavaScript library included in a single .js file. Achieving
the same functionality with JavaScript will take a longer time and
hence it increases the development productivity.

The jQuery tutorials will help you learn jQuery starting from the
basics to advanced level. These tutorials are broken down into
sections where each section contains a number of related topics that
are packed with easy to understand explanations, real-world
examples, tips, notes and useful references.
Each tutorial includes practical examples. You can edit and see the
result real time with Code Editor. Click on 'Try it' button at the
bottom of each example to edit and see the actual result in the
browser.

These tutorials are designed for beginners and professionals who


want to learn jQuery step-by-step.

jQuery Reference
The jQuery reference section will give you detailed information about
jQuery methods with examples.

Prerequisites
Basic knowledge of JavaScript, HTML, CSS and web application is
required.

What is jQuery
jQuery is a fast, small and feature-rich JavaScript library included in
a single .js file.

jQuery makes a web developer's life easy. It provides many built-in


functions using which you can accomplish various tasks easily and
quickly.

jQuery Important Features


 DOM Selection: jQuery provides Selectors to retrieve DOM element based on
different criteria like tag name, id, css class name, attribute name, value, nth
child in hierarchy etc.
 DOM Manipulation: You can manipulate DOM elements using various built-in
jQuery functions. For example, adding or removing elements, modifying html
content, css class etc.
 Special Effects: You can apply special effects to DOM elements like show or
hide elements, fade-in or fade-out of visibility, sliding effect, animation etc.
 Events: jQuery library includes functions which are equivalent to DOM events
like click, dblclick, mouseenter, mouseleave, blur, keyup, keydown etc. These
functions automatically handle cross-browser issues.
 Ajax: jQuery also includes easy to use AJAX functions to load data from
servers without reloading whole page.
 Cross-browser support: jQuery library automatically handles cross-browser
issues, so the user does not have to worry about it. jQuery supports IE 6.0+,
FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+.

Advantages of jQuery
 Easy to learn: jQuery is easy to learn because it supports same JavaScript
style coding.
 Write less do more: jQuery provides a rich set of features that increase
developers' productivity by writing less and readable code.
 Excellent API Documentation: jQuery provides excellent online API
documentation.
 Cross-browser support: jQuery provides excellent cross-browser support
without writing extra code.
 Unobtrusive: jQuery is unobtrusive which allows separation of concerns by
separating html and jQuery code.

Learn how to download and install jQuery library in the next section.

jQuery Development Tools


As with other languages, jQuery development requires an editor to
write a jQuery code and jQuery library.

Editor
You can use any JavaScript editor to write jQuery code including
following.

 Notepad
 Visual Studio
 Eclipse
 Aptana Studio
 Ultra edit

An editor which supports IntelliSense for JavaScript and jQuery


functions will increase a developer's productivity.
jQuery Library
To download jQuery library, go to jquery.com.

Download jQuery Library

As shown above, click on Download jQuery link or Download menu.


This will open download page as shown below.
Download jQuery Latest Version

Here, you can download the latest versions of jQuery, at this point it
is v3.3. As you can see in the above figure, you can download
compressed or uncompressed versions of jQuery library. Compressed
version should be used in production environment whereas
uncompressed version should be used in development. Compressed
version minimizes the library by eliminating extra white space, line
feed and shortening the variable and function names. So,
compressed version is not readable. Uncompressed library is a
readable file which is useful while debugging.

After downloading an appropriate version of jQuery library, you can


use it by taking a reference of it in your web page. Remember,
jQuery library is eventually a JavaScript file. So you can include it
like a normal JavaScript file using script tag as below.

Example: Refrence jQuery in an HTML page


<!DOCTYPE html>

<html>
<head>
<script src="~/Scripts/jquery-3.3.1.js"></script>
</head>
<body>
</body>
</html>
ADVERTISEMENT

Include jQuery Library from CDN


You can also reference jQuery library from public CDN (content
delivery network) such as Google, Microsoft, CDNJS, jsDelivr etc.

Reference jQuery from CDN


<!DOCTYPE html>

<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=
"
crossorigin="anonymous">
</script>
</head>
<body>
</body>
</html>

There might be times when these CDN goes down for some reason.
Therefore, you need to have a fall back mechanism which downloads
jQuery library from your web server if CDN is down.

The following example shows how to include jQuery library reference


from CDN with fall back.

Example: Use CDN with Fallback


<!DOCTYPE html>

<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>

<script>
// Fallback to loading jQuery from a local path if the CDN is
unavailable
(window.jQuery || document.write( '<script src="~/scripts/jquery-
3.3.1.min.js"></script>'));
</script>
</head>
<body>
</body>
</html>

As you can see in the above code example, if jQuery library is


successfully loaded then it adds global function jQuery() to window
object. If window.jQuery is undefined or null that means jQuery
library is not loaded and so you have to download library from local
server path.

So, in this way, you can download and take a reference of jQuery
library in your web page.

jQuery API Documentation


jQuery provides online API documentation. Click on API
Documentation on jquery.com or goto api.jquery.com. You will see a
documentation page as shown below.
j
Query Documentation

As you can see above, categories of jQuery features are listed on the
left side. Right-hand section shows functions related to the currently
selected category. Click on a function to get detailed information with
example.

After setting up the development environment, let's look at an


overview of jQuery syntax and how to get started in the next section.

Points to Remember :

1. Use JavaScript editor and jQuery library to setup jQuery development


environment.
2. Use any text editor to write jQuery script e.g. Notepad, Visual Studio,
Eclipse, Aptana studio etc.
3. Download the appropriate version of jQuery from jQuery.com
4. Include jQuery library using <script> tag. You can also include jQuery
library from public CDN with fall back mechanism e.g code.jquery.com.
Start Using jQuery
After setting up the environment and including reference of jQuery
library in your web page, it's time to use jQuery.

jQuery() Function
When you open your web page in a browser and load jQuery library
successfully, it adds a global function named jQuery(). The global
scope means scope of the window, so the global jQuery() function
can be called like window.jQuery() or jQuery() anywhere in your web
page. $ is an alias of jQuery function, so you can also use $() as a
short form of jQuery().

The following figure shows window.jQuery, window.$, jQuery and $


function in chrome developer tools.
jQu
ery, $ funtion

As you can see above, jQuery, window.jQuery, $ and window.$ are


the same.
window.jQuery = window.$ = jQuery = $

The jQuery() (aka $) function takes two parameters, selector and


context as you can see in the above figure.

A selector parameter can be CSS style selector expression for


matching a set of elements in a document. For example, if you want
to do something with all the div elements then use $ function to
match all the div elements as shown below.

Example: Selector Parameter


jQuery('div')
//Or

window.jQuery('div')

//Or

$('div')

//Or

window.$('div')

Here, you just pass the tag name of the elements you want to find.
jQuery (aka $) function will return an array of elements specified as
a selector. You will learn more about selectors in the next section.

The second parameter in jQuery() function is a context. A context


parameter can be anything, it can be reference of another DOM
element or it can be another jQuery selector. The jQuery will start
searching for the elements from the element specified in a context.
The jQuery selector may performs faster if you provide context
parameter. However, context parameter is optional.
ADVERTISEMENT

Write jQuery Code


Typically, jQuery interacts with the DOM elements and performs
some operation on them. Therefore, we need to detect when the
DOM (Document Object Model ) is loaded fully, so that the jQuery
code starts interacting with DOM without any error.

For example, we want to write "Hello World!" to div tag in our web
page. The first step is to check when the DOM is loaded fully so that
we can find the div element and write "Hello World" to it. If we try to
write it before DOM loads, jQuery may not find the div element
because it might not be constructed at that time (if you write jQuery
script in the <head> tag).

jQuery API includes built-in function ready(), which detects whether


a particular element is ready (loaded) or not. Here, we need to check
whether a document object is loaded or not using ready() function
because document loads entire DOM hierarchy. When the document
loads successfully we can be sure that all DOM elements have also
loaded successfully.

In order to check whether a document object is loaded or not, you


need to find a document object using jQuery selector function as
shown below. (The document object is a global object in your
browser, so you can also write window.document.)

Example: Find Document Object using jQuery Selector


$(document)

//Or

$(window.document)

//Or

jQuery(document)

//Or

window.jQuery(document)

The above code will find the global document object. Now, you need
to find whether it is loaded or not (in other words, ready or not)
using ready function as shown below.
$(document).ready();

Ready function takes a callback function as a parameter. This


callback function will be called once document is ready.

Example: jQuery ready()


$(document).ready(function() {

// DOM is loaded by now...

// Write jQuery code here...

});
Now, you can start interacting with DOM using jQuery safely in the
callback function.

The below figure illustrates the steps:

Steps to Check Document Loading

This is the first thing you need to write before writing any jQuery
code. You always need to check whether a document is ready or not
in order to interact with the DOM safely.

Difference between window.onload and $


(document).ready

$(document).ready() doesn't wait for images to be loaded. It gets called as soon


as DOM hierarchy is constructed fully.

The $(document).ready() function determines when the full DOM


hierarchy is loaded whereas window.onload event is raised when
entire window is loaded including DOM, images, css and other
required resources. The DOM loads before entire window loads.

Example: window.onload() vs $(document).ready()


<!DOCTYPE html>

<html>
<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery
.min.js">
</script>
<script>
window.onload = function () {
alert('window loaded');
};

$(document).ready(function () {
alert('document loaded');
});
</script>
</head>
<body>
<h1>Demo: window.onload() vs $(document).ready()</h1>
</body>
</html>
Try it

When you open the above html file in a browser, first alert 'document
loaded' is displayed and then second alert 'windows loaded' is
displayed. Thus, DOM loads first followed by the entire window.

Points to Remember :

1. The jQuery library adds a global function named jQuery after jQuery library
successfully loaded.
2. $ is a short form of jQuery function. $() = jQuery() = window.$() =
window.jQuery()
3. $()/jQuery() is a selector function that selects DOM elements. Most of the
time you will need to start with $() function.
4. It is advisable to use jQuery after DOM is loaded fully. Use jQuery ready()
function to make sure that DOM is loaded fully.
5. window.onload() & $(document).ready() is different. window.onload() is
firesd when the whole html document is loaded with images and other
resources, whereas jQuery ready() function is fired when DOM hierarchy is
loaded without other resources.
jQuery Selectors
In this section, you will learn about jQuery selectors and how to find
DOM element(s) using selectors.

The jQuery selector enables you to find DOM elements in your web
page. Most of the times you will start with selector function $() in the
jQuery.

Syntax:
$(selector expression, context)

jQuery(selector expression, context)

The selector expression parameter specifies a pattern to match the


elements. The jQuery uses CSS selector patterns as well as its own
pattern to match the elements.

The context parameter is optional. It specifies elements in a DOM


hierarchy from where jQuery starts searching for matching elements.

Let's see commonly used selectors in jQuery.

Select Elements by Name


The most common selector pattern is element name. Specifing an
element name as string e.g. $('p') will return an array of all the <p>
elements in a webpage.

The following figure shows which DOM elements will be returned from
$('p') & $'(div').
jQuery
Selectors Demo

As you can see in the above figure, $('div') will return all the <div>
elements including its child elements.

Example: Select Elements by Name


$('p').append('This is paragraph.'); // appends text to all p elements

$('div').append('This is div.); // appends text to all div elements

<div>
<p></p>
<p></p>
</div>

<p></p>

<div></div>
Try it

Select Elements by Id

jQuery append() method inserts text at the end in the element.

You can get a particular element by using id selector pattern. Specify


an id of an element for which you want to get the reference, starting
with # symbol.
The following figure shows which DOM elements will be returned from
$('#myDiv1') & $'(#prg2').

jQuery Id Selector
Demo

Example: Select Element by #Id


$('#impPrg').append('This element\'s id is "impPrg"');

$('#myDiv2').append('This element\'s id is "myDiv2"');

<div id="myDiv1">
<p></p>
</div>

<p id="impPrg"></p>

<div id="myDiv2">
</div>
Try it
ADVERTISEMENT

Select Elements by Attribute


jQuery also allows you to find an element based on attributes set on
it. Specifing an attribute name in square brackets in $ function e.g. $
('[class]') will return all the elements that have class attribute
irrespective of value.

In the following example, jQuery returns all the elements that have
class or contenteditable attribute irrespective of any value.
j
Query Attribute Selector

Example: Select Elements by Attribute


$('[class]').append('This element has class attribute');

<div id="myDiv1">
<p></p>
</div>

<p id="impPrg" class="boldPrg"></p>

<div id="myDiv2" class="yellowDiv">


</div>
Try it

You can also specify a specific value of an attribute in attribute


selector. For example, $('[class="myCls"]') will return all the
elements which have class attribute with myCls as a value.
jQuery Selector by Attribute Value

Example: Select Element by Attribute Value


$('[class="yellowDiv"]').append('This element includes
class="yellowDiv" attribute');

<div id="myDiv1">
<p></p>
</div>

<p id="impPrg" class="boldPrg">This is paragraph.</p>

<div id="myDiv2" class="yellowDiv">


</div>
Try it

jQuery Selector Patterns


jQuery provides number of ways to select a specific DOM element(s).
The following table lists the most important selector patterns.

Category Selector Description

Find element $('div') Find all <div> elements

$('p, div, code') Find <p>,<div> and <code> elements

Find descendant $('div p') Find all <p> elements which are descendants of <div>
elements
Category Selector Description

$('div > p') Find <p> which is child of <div>

$(*) Find all elements

Find by Id $('#myDiv') Find element whose id is myDiv

$('div#myDiv') Find <div> element whose Id is myDiv

$('#myDiv1, #myDiv2') Find multiple elements by id separated by comma.

Find by CSS class $('.myCSSClass') Find all the elements with class=myCSSClass.

$('.myCSSClass1, .myCSSClass2 ') Finds all elements whose class attribute is set
to myCSSClass1 or myCSSClass2

$('div.myCSSClass') Finds all <div> elements with class=myCSSClass

Find child element $('p:first-child') Find all <p> elements, which is the first child of its parent
element. (parent element can be anything)

$("p:last-child") Selects all <p> elements which is the last child of its parent
element. (parent element can be anything)

$("p:nth-child(5)") Selects all <p> elements which is the 5th child of its parent
element. (parent element can be anything)

$("p:nth-last-child(2)") Selects all <p> elements which is the 2nd last child of its parent
element. (parent element can be anything)

$("p:only-child") Selects all <p> elements which is the only child of its parent
element. (parent element can be anything)

Find by attribute $('[class]') Find all the elements with the class attribute(whatever the value).

$('div[class]') Find all the <div> elements that have a class attribute(whatever
the value).

Find by containing $('div[class=myCls]') Find all the <div> elements whose class attributes are equal
value of attribute to myCls.

$('div[class|=myCls]') Find all the <div> elements whose class attributes are either equal
to myCls or starting with myCls string followed by a hyphen (-).

$('div[class *="myCls"]') Selects <div> elements whose class attributes contain myCls.

$('div[class~=myCls]') Selects div elements whose class attributes contain myCls,


delimited by spaces.

$("div[class $= 'myCls']") Selects <div> elements whose class attribute value ends
Category Selector Description

with myCls. The comparison is case sensitive.

$("div[class != 'myCls']") Selects <div> elements which do not have class attribute or value
does not equal to myCls.

$("div[class ^= 'myCls']") Selects <div> elements whose class attribute value starts with
myCls.

$("div:contains('tutorialsteacher')" Selects all <div> elements that contains the text 'tutorialsteacher'

Find by input type $(":input") Selects all input elements.

:button $(":button") Selects all input elements where type="button".

:radio $(":radio") Selects all input types where type="radio"

:text $(":text") Selects all input elements where type="text" .

":checkbox" $(":checkbox") Selects all checkbox elements.

:submit $(":submit") Selects all input elements where type="submit".

:password $(":password") Selects all input elements where type="password".

:reset $(":reset") Selects all input elements where type="reset".

:image $(':image') Selects all input elements where type="image".

:file $(':file') Selects all input elements where type="file".

:enabled $(':enabled') Selects all enabled input elements.

:disabled $(':disabled') Selects all disabled input elements.

:selected $(':selected') Selects all selected input elements.

:checked $(':checked') Selects all checked input elements.

:hidden $(':hidden') Selects all hidden elements.

:visible $(':visible') Selects all visible elements.

:odd $('tr:odd') Selects all odd rows. (1,3,5,7..)

:even $('tr:even') Selects all even rows.(0,2,4,6..)

Visit selector reference to know more selector patterns.


jQuery Methods
You learned about jQuery selectors in the previous section. The
jQuery selector finds particular DOM element(s) and wraps them with
jQuery object. For example, document.getElementById() in the
JavaScript will return DOM object whereas $('#id') will return jQuery
object. The following figure illustrates the difference.

jQuery Methods

As you can see in the above figure, document.getElementById


function returns div element whereas jQuery selector returns jQuery
object which is a wrapper around div element. So now, you can call
jQuery methods of jQuery object which is returned by jQuery
selector.

jQuery provides various methods for different tasks e.g. manipulate


DOM, events, ajax etc. The following table lists different categories of
methods.

Category Description Imp Methods

DOM Manipulation These methods manipulate DOM elements in some manner e.g. changing after(),
attribute, style attribute, adding and removing elements etc. append(),
attr(),
before(),
more..

Traversing These methods help in navigating from DOM element to another element in a children(),
parent child hierarchy e.g. finding ancestors, descendants or sibling element of a closest(),
Category Description Imp Methods

specified element. each(),


first(),
next(),
filter(),
parent(),
siblings(),
more..

CSS These methods get and set css related properties of elements. addClass(),
css(),
hasClass(),
removeClass(),
toggleClass()
more..

Attributes These methods get and set DOM attributes of elements. attr(),
html(),
removeAttr(),
prop(),
val(),
more..

Events These methods are used to handle DOM or JavaScript events. bind(),
blur(),
change(),
click(),
dblclick(),
focus(),
keyup(),
keydown(),
more..

Effects These methods are used to add animation to elements. animate(),


fadeIn(),
fadeOut(),
hide(),
show(),
stop(),
more..

Dimensions These methods are used to get and set the CSS dimensions for the various height(),
properties. width(),
innerHeight(),
innerWidth(),
more..
Category Description Imp Methods

Forms These methods and event handlers handle forms and their various elements. blur(),
change(),
val(),
submit(),
more..

Ajax These methods allow Ajax functionalities with jQuery e.g. get(),
getJson(),
post(),
load(),
more..

Core These methods are core methods in jQuery API. jQuery(),


holdReady(),
when(),
more..

Data These methods allow us to associate arbitrary data with specific DOM elements. data(),
removeData(),
queue(),
dequeue(),
clearQueue(),
more..

Miscellaneous These methods are useful in various tasks e.g. traversing elements, converting to each(),
array etc. index(),
get(),
toArray(),
more..

Utilities Utility methods are helpful in getting information on various things e.g. browser, inArray(),
function, array, window etc. isArray(),
isFunction(),
isNumeric(),
isWindow(),
isXmlDoc(),
more..

The following example shows how to use some of the jQuery


methods to manipulate DOM elements.

Example: jQuery Methods


<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script type="text/javascript" src="~/Scripts/jquery-
3.3.1.js"></script>
<script type="">
$(document).ready(function () {

$('p').wrap('<div class="myCls">'); @* wrap all p with div


*@
$('#myDiv').hide(); @* hides div whose id is myDiv *@
$('span').attr( @*sets style and width attribute on all
span *@
{
'style': 'border:solid',
'width': '100%'
});
$('p').append('This is p.'); @* append text to <p> *@

$('span').before('<p>This is another p</p>'); @* insert


<p> before span *@

});
</script>
</head>

<body>
<div id="myDiv"></div>
<p></p>
<span></span>
</body>
</html>

DOM Manipulation Methods in jQuery


jQuery provides various methods to add, edit or delete DOM
element(s) in the HTML page.

The following table lists some important methods to add/remove new


DOM elements.
Method Description

append() Inserts content to the end of element(s) which is specified by a selector.

before() Inserts content (new or existing DOM elements) before an element(s) which is specified by a selector.

after() Inserts content (new or existing DOM elements) after an element(s) which is specified by a selector.

prepend() Insert content at the beginning of an element(s) specified by a selector.

remove() Removes element(s) from DOM which is specified by selector.

replaceAll() Replace target element(s) with specified element.

wrap() Wrap an HTML structure around each element which is specified by selector.

The following figure shows how the DOM manipulation methods add
new elements.

DOM Manipulation Methods

Let's have a quick overview of important DOM manipulation methods.

jQuery after() Method


The jQuery after() method inserts content (new or existing DOM
elements) after target element(s) which is specified by a selector.

Syntax:
$('selector expression').after('content');

First of all, specify a selector to get the reference of target


element(s) after which you want to add the content and then call
after() method. Pass the content string as a parameter. Content
string can be any valid HTML element.

Example: jQuery after() Method


$('#div1').after('<div style="background-color:yellow"> New div
</div>');

<div id="div1">div 1
</div>

<div id="div2">div 2
</div>

Result:

<div id="div1">div 1
</div>

<div style="background-color:yellow"> New div </div>

<div id="div2">div 2
</div>

jQuery before() Method


The jQuery before() method inserts content (new or existing DOM
elements) before target element(s) which is specified by a selector.

Syntax:
$('selector expression').before('content');

Specify a selector to get the reference of target element(s) before


which you want to add the content and then call before() method.
Pass the content string that can be any valid HTML element as
parameter.

Example: jQuery before() Method


$('#div1').before('<div style="background-color:yellow"> New div
</div>');

<div id="div1">div 1
</div>
<div id="div2">div 2
</div>

Result:

<div style="background-color:yellow"> New div </div>


<div id="div1">div 1
</div>

<div id="div2">div 2
</div>
ADVERTISEMENT

jQuery append() Method


The jQuery append() method inserts content to the end of target
element(s) which is specified by a selector.

Syntax:
$('selector expression').append('content');

First specify a selector expression to get the reference of an


element(s) to which you want to append content, then call append()
method and pass content string as a parameter.

Example: jQuery append() Method


$('p').append('World!');

<p>Hello </p>

Result:

<p>Hello World!</p>

jQuery prepend() Method


The jQuery prepend() method inserts content at the beginning of an
element(s) specified by a selector.

Syntax:
$('selector expression').prepend('content');

First specify a selector expression to get the reference of an


element(s) to which you want to prepend the content, then call
prepend() method and pass content string as a parameter.

Example: jQuery prepend() Method


$('div').prepend('<p>This is prepended paragraph</p>');

<div>
<label>This is div.</label>
</div>

Result:

<div>
<p>This is prepended paragraph</p>
<label>This is div.</label>
</div>

jQuery remove() Method


The jQuery remove() method removes element(s) as specified by a
selector.

Syntax:
$('selector expression').remove();

First specify a selector expression to get the reference of an


element(s) which you want to remove from the document and then
call remove() method.

Example: jQuery remove() Method


$('label').remove();

<div>This is div.
<label>This is label.</label>
</div>

Result:

<div>
This is div.
</div>

jQuery replaceAll() Method


The jQuery replaceAll() method replaces all target elements with
specified element(s).

Syntax:
$('content string').replaceAll('selector expression');

Here, syntax is different. First specify a content string as


replacement element(s) and then call replaceAll() method with
selector expression to specify a target element(s).

Example: jQuery replaceAll() Method


$('<span>This is span</span>').replaceAll('p');

<div>
<p>This is paragraph.</p>
</div>

<p>This is another paragraph.</p>

Result:

<div>
<span>This is span</span>
</div>
<span>This is span</span>

jQuery wrap() Method


The jQuery wrap() method wrap each target element with specified
content element.

Syntax:
$('selector expression').wrap('content string');

Specify a selector to get target elements and then call wrap method
and pass content string to wrap the target element(s).
Example: jQuery wrap() Method
$('span').wrap('<p></p>');

<div>
<span>This is span.</span>
</div>
<span>This is span.</span>

Result:

<div>
<p> <span>This is span.</span></p>
</div>
<p><span>This is span.</span></p>

Manipulate HTML Attributes using jQuery


The following table lists jQuery methods to get or set value of attribute, property, text
or html.

jQuery Method Description

attr() Get or set the value of specified attribute of the target element(s).

prop() Get or set the value of specified property of the target element(s).

html() Get or set html content to the specified target element(s).

text() Get or set text for the specified target element(s).

val() Get or set value property of the specified target element.

The following figure shows various jQuery methods to access DOM element's
attributes, properties and values.
jQuery Methods to Access Values

Let's have a quick overview of important methods to access element's attributes.

jQuery attr() Method


jQuery attr() method is used to get or set the value of specified attribute of DOM
element.

Syntax:
$('selector expression').attr('name','value');

First of all, specify a selector to get the reference of an element and call attr() method
with attribute name parameter. To set the value of an attribute, pass value parameter
along with name parameter.

Example: jQuery attr() Method


$('p').attr('style'); // returns "font-size:16px;font-weight:bold"
$('div').attr('class','yellowDiv'); // adds class='divCls' to each
div element

<div>
This is div.
</div>
<p style="font-size:16px;font-weight:bold">
This is paragraph.
</p>
<div>
This is div.
</div>
<p>
This is paragraph.
</p>

In the above example, $('p').attr('style') gets style attribute of first <p> element in
a html page. It does not return style attributes of all the <p> elements.

jQuery prop() Method


The jQuery prop() method gets or sets the value of specified property to the DOM
element(s).

Syntax:
$('selector expression').prop('name','value');

First of all, specify a selector to get the reference of an element(s) and call prop()
method. Supply "name" parameter to get the value of that property. To set the value of
a property, specify a value parameter along with name parameter.

Example: jQuery prop() Method


var style = $('p').prop('style');
style.fontWeight; // returns "bold"

$('div').prop('class','yellowDiv'); // add class="yellowDiv" to all


div elements

<div>
This is div.
</div>
<p style="font-size:16px;font-weight:bold">
This is paragraph.
</p>
<div>
This is div.
</div>
<p>
This is paragraph.
</p>

In the above example, $('p').prop('style') returns an object. You can get different
style properties by using object.propertyName convention e.g. style.fontWeight. Do
not include '-' as a property name.
ADVERTISEMENT

jQuery html() Method


The jQuery html() method gets or sets html content to the specified DOM element(s).

Syntax:
$('selector expression').html('content');

First of all, specify a selector to get the reference of an element and call html() method
without passing any parameter to get the inner html content. To set the html content,
specify html content string as a parameter.

Example: jQuery html() Method


$('#myDiv').html(); //returns innerHtml of #myDiv

//add <p>This is paragraph.</p> to #emptyDiv


$('#emptyDiv').html('<p>This is paragraph.</p>');

<div id="myDiv" class="yellowDiv">


<p style="font-size:16px;font-weight:bold">
This is paragraph.
</p>
</div>
<div id="emptyDiv">
</div>

jQuery text() Method


The jQuery text() method gets or sets the text content to the specified DOM element(s).
Syntax:
$('selector expression').text('content');

First of all, specify a selector to get the reference of an element and call text() method
to get the textual content of an element. To set the text content, pass content string as a
parameter.

Example: jQuery text() Method


$('#myDiv').text(); //returns "This is paragraph."
$('p').text(); //returns "This is paragraph."

//removes all the content from #emptyDiv and inserts "This is some
text." to it
$('#emptyDiv').text('This is some text.');

<div id="myDiv" class="divCls">


<p style="font-size:16px;font-weight:bold">
This is paragraph.
</p>
</div>
<div id="emptyDiv">
</div>

Please note that text() method only returns text content inside the element and not the
innerHtml.

jQuery val() Method


The jQuery val() method gets or sets value property to the specified DOM element(s).

Syntax:
$('selector expression').val('value');

First of all, specify a selector to get the reference of an element and call val() method
to get the value of value property. To set the text content, pass content string as a
parameter.

Example: jQuery val() Method


$('input:Submit').val(); //returns "Save"
//set value of input text to "Steve"
$('input:text').val('Steve');

$('input:text').val(); //returns "Steve"

<div>
<label>Name:</label><input type="text" />
</div>

<div>
<input type="Submit" value="Save" />
</div>

In the above example, val() method returns value of "value" property. If element does
not support value property then val() method returns null.

Visit Manipulation methods reference to know all the jQuery methods to manipulate
attributes.

Points to Remember :

1. jQuery attribute methods allows you to manipulate attributes and properties of elements.
2. Use the selector to get the reference of an element(s) and then call jQuery attribute methods
to edit it.
3. Important DOM manipulation methods: attr(), prop(), html(), text(), val() etc.

Manipulate DOM Element's Dimensions


using jQuery
The jQuery library includes various methods to manipulate DOM
element's dimensions like height, width, offset, position etc.

The following table lists all the jQuery methods to get or set DOM
element's dimensions.

jQuery Method Description

height() Get or set height of the specified element(s).

innerHeight() Get or set inner height (padding + element's height) of the specified element(s).
jQuery Method Description

outerHeight() Get or set outer height (border + padding + element's height) of the specified element(s).

offset() Get or set left and top coordinates of the specified element(s).

position() Get the current coordinates of the specified element(s).

width() Get or set the width of the specified element(s).

innerWidth() Get or set the inner width (padding + element's width) of the specified element(s).

outerWidth() Get or set outer width (border + padding + element's width) of the specified element(s).

The following figure shows various dimensions of an element.

DOM Element's Dimensions


jQuery height() Method
The jQuery height()method gets or sets height of the specified DOM
element(s).

Syntax:
$('selector expression').height(value);

Specify a selector to get the reference of an element and call


height() method to get the height in pixel. To set the height of
specified elements, specify height as integer parameter in height()
method.

Example: jQuery height() Method


$('#myDiv').height(); //returns height of #myDiv in pixels
$('p').height(); //returns height in pixel

//set height of all div elements


$('div').height(100);

<div id="myDiv" >


This is div.
</div>

<p>
This is paragraph.
</p>

ADVERTISEMENT

jQuery width() Method


The jQuery width() method gets or sets width of the specified DOM
element(s).

Syntax:
$('selector expression').width(value);
Specify a selector to get the reference of an element and call width()
method to get the width in pixel. Specify width as integer parameter
to set the width.

Example: jQuery width() Method


$('#myDiv').width(); //returns width of #myDiv in pixels
$('p').width(); //returns width of p in pixel

//set width of all div elements


$('div').width(100);

<div id="myDiv" >


This is div.
</div>

<p>
This is paragraph.
</p>

jQuery offset() Method


The jQuery offset() method gets or sets coordinates of the specified
element(s).

Syntax:
$('selector expression').offset(options);

Specify a selector to get the reference of an element and call offset()


method to get the jQuery object which has left and top property.
Specify JSON object with left and top property with the coordinates
where you want to move the element.

Example: jQuery offset() Method


var ofs = $('#myDiv').offset();
alert('left:' + ofs.left + ', top: ' + ofs.top);

$('p').offset({ left:100, top:200});

<div id="myDiv" >


This is div.
</div>

<p>
This is paragraph.
</p>

Points to Remember :

1. jQuery dimension methods allows you to manipulate dimensions of


DOM elements.
2. Use the selector to get the reference of an element(s) and then call
jQuery dimension methods to edit it.
3. Important DOM manipulation methods: height(), width(), offset(),
position() etc.

Traversing DOM Elements using jQuery


The jQuery library includes various methods to traverse DOM
elements in a DOM hierarchy.

The following table lists jQuery methods for traversing DOM


elements.

jQuery Methods Description

children() Get all the child elements of the specified element(s)

each() Iterate over specified elements and execute specified call back function for each element.

find() Get all the specified child elements of each specified element(s).

first() Get the first occurrence of the specified element.

next() Get the immediately following sibling of the specified element.

parent() Get the parent of the specified element(s).

prev() Get the immediately preceding sibling of the specified element.

siblings() Get the siblings of each specified element(s)


The following figure shows how the jQuery traversing methods get
DOM elements.

Traversing DOM Elements

Let's look at some of the important jQuery traversing methods.

jQuery each() Method


The jQuery each() method iterates over each specified element
(specified using selector) and executes callback function for each
element.

Syntax:
$('selector expression').each(callback function);

To begin, specify a selector to get the reference of elements and call


each() method with callback function, which will be executed for each
element.
Example: jQuery each() method
$('p').each(function (index) {
alert('index' + index + ', text: ' + $(this).text());
});

<div>
<p>This is First paragraph.</p>
</div>
<div id="myDiv">
<p>
This is second paragraph.
</p>
<div id="inrDiv">
<p>This is third paragraph.</p>
</div>
<div>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
</div>
</div>
<div>
<p>This is fourth paragraph.</p>
</div>

Result:

Index:0, text: This is first paragraph.


Index:1, text: This is second paragraph.
Index:2, text: This is third paragraph.
Index:3, text: This is fourth paragraph.

jQuery children() Method


The jQuery children() method get the child element of each element
specified using selector expression.

Syntax:
$('selector expression').children();
Elements returned from children() method can be iterated using each() method.

First, specify a selector to get the reference of an element(s) and call


children() method to get all the child elements.

Example: jQuery children() method


$('#myDiv').children().each(function (index) {
alert('Index: ' + index + ', html: ' + $(this).html());
});

<div>
<p>This is First paragraph.</p>
</div>
<div id="myDiv">
<p>
This is second paragraph.
</p>
<div id="inrDiv">
<p>This is third paragraph.</p>
</div>
<div>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
</div>
</div>
<div>
<p>This is fourth paragraph.</p>
</div>

Result:
Index:0, html: <p>
This is second paragraph.
</p>
Index:1, html: <div id="inrDiv">
<p>This is third paragraph.</p>
</div>
Index:2, html: <div>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
</div>
ADVERTISEMENT

jQuery find() Method


The jQuery find() method returns all the matching child elements of
specified element(s).

Syntax:
$('selector expression').find('selector expression to find child
elements');

Specify a selector to get the reference of an element(s) whose child


elements you want to find and then call find() method with selector
expression to get all the matching child elements. You can iterate
child elements using each method.

Example: jQuery find() method


$('#myDiv').find('p').each(function(index){
alert('index' + index + ', text: ' + $(this).text());
});

<div>
<p>This is First paragraph.</p>
</div>
<div id="myDiv">
<p>
This is second paragraph.
</p>
<div id="inrDiv">
<p>This is third paragraph.</p>
</div>
<div>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
</div>
</div>
<div>
<p>This is fourth paragraph.</p>
</div>

Result:
Index:0, text: This is second paragraph.
Index:1, text: This is third paragraph.

jQuery next() Method


The jQuery next() method gets the immediately following sibling of
the specified element.

Syntax:
$('selector expression').next();

Specify a selector to get the reference of an element of which you


want to get next element and then call next() method.

Example: jQuery next() method


alert('Next element to #myDiv: ' + $('#myDiv').next().html());

alert('Next element to #inrDiv: ' + $('#inrDiv').next().html());

<div>
<p>This is First paragraph.</p>
</div>
<div id="myDiv">
<p>
This is second paragraph.
</p>
<div id="inrDiv">
<p>This is third paragraph.</p>
</div>
<div>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
</div>
</div>
<div>
<p>This is fourth paragraph.</p>
</div>

Result:
Next element to #myDiv: <div>
<p>This is fourth paragraph.</p>
</div>

Next element to #inrDiv: <ul>


<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>

jQuery parent() Method


The jQuery parent() method gets the immediate parent element of
the specified element.

Syntax:
$('selector expression').parent();

Specify a selector to get the reference of an element of which you


want to get the parent element and then call parent() method.

Example: jQuery parent() method


alert('Parent element of #inrDiv: ' + $('#inrDiv').parent().html());

<div>
<p>This is First paragraph.</p>
</div>
<div id="myDiv">
<p>
This is second paragraph.
</p>
<div id="inrDiv">
<p>This is third paragraph.</p>
</div>
<div>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
</div>
</div>
<div>
<p>This is fourth paragraph.</p>
</div>

Result:
Parent element of #inrDiv: <p>
This is second paragraph.
</p>
<div id="inrDiv">
<p>This is third paragraph.</p>
</div>
<div>
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
</div>

jQuery siblings() Method


The jQuery siblings()method gets all siblings of the specified DOM
element(s).

Syntax:
$('selector expression').siblings();

Specify a selector to get the reference of an element of which you


want to get the siblings and call siblings() method.

Tips: you can iterate sibling elements using each() method.

Example: jQuery siblings() method


$('#myDiv').siblings().css({"color": "green", "border": "2px solid
green"});

<div>
<p>This is First paragraph.</p>
</div>
<div id="myDiv">
<p>
This is myDiv.
</div>
<div>
<p>This is second paragraph.</p>
</div>

Points to Remember :

1. The jQuery traversing methods allow you to iterate DOM elements in a DOM
hierarchy.
2. Use the selector to get the reference of an element(s) and then call jQuery
traversing methods to edit it.
3. Important DOM manipulation methods: each(), children(), find(), first(),
parent(), next(), previous(), siblings() etc.

CSS Manipulation using jQuery


The jQuery library includes various methods to manipulate style
properties and CSS class of DOM element(s).

The following table lists jQuery methods for styling and css
manipulation.

jQuery Methods Description

css() Get or set style properties to the specified element(s).

addClass() Add one or more class to the specified element(s).

hasClass() Determine whether any of the specified elements are assigned the given CSS class.

removeClass() Remove a single class, multiple classes, or all classes from the specified element(s).

toggleClass() Toggles between adding/removing classes to the specified elements

The following figure shows how jQuery methods changes style and
css class of the DOM elements.
jQuery Methods for Style & CSS Manipulation

Let's have an overview of important jQuery methods for style and css
manipulation.

jQuery css() Method


The jQuery css() method gets or sets style properties to the specified
element(s).

Syntax:
$('selector expression').css('style property name','value');

$('selector expression').css({
'style property name':'value',
});

Specify a selector to get the reference of an elements to which you


want to set the style property and then call css() method with style
property name and value parameter. You can also set multiple style
properties by passing JSON object with 'style property name':'value'.

Example: jQuery css() Method


$('#myDiv').css('background-color','yellow');
$('p').css({'background-color': 'red','width':'400px'});

$('#myDiv').css('background-color'); // returns rgb(255,255,0) for


yellow color

<div id="myDiv">
<p>This is first paragraph.</p>
</div>
<div>
<p>This is second paragraph.</p>
</div>
<div >
<p>This is third paragraph.</p>
</div>

In the above example, we set background-color of #myDiv and font


styles to all <p> elements. The same way, we can get value of any
style properties using css() method by specifying property name as
first parameter.
ADVERTISEMENT

jQuery addClass() method


The jQuery addClass() method adds single or multiple css class to
the specified element(s).

Syntax:
$('selector expression').addClass('css class name');

First specify a selector to get the reference of an elements to which


you want to set the css property and then call addClass() method
with one or multiple class names as a string parameter. Multiple class
names must be separated by space.

Example: jQuery addClass() Method


$('#myDiv').addClass('yellowDiv');
$('p').addClass('impPrg');

<div id="myDiv">
<p>
This is first paragraph.
</p>
</div>
<div>
<p>This is second paragraph.</p>
</div>
<div >
<p>This is third paragraph.</p>
</div>

In the above example, we set css class of individual <div> element


(#myDiv) as well as multiple <p> elements using addClass()
method.

jQuery toggleClass() Method


The jQuery toggleClass() method toggles between adding/removing
classes to the specified elements.

Syntax:
$('selector expression').toggleClass('css class name');

Specify a selector to get the reference of an elements to which you


want to toggle css classes and then call toggleClass() method with
css class name as a string parameter.

Example: jQuery toggleClass() Method


$('#myDiv').toggleClass('redDiv');

<div id="myDiv" class="yellowDiv">


</div>

In the above example, css class yellowDiv will be first added into div
element and then removed. Thus, css class will be added or removed
consecutively.

Visit Manipulation methods reference to know all the CSS


manipulation methods in jQuery.

Points to Remember :

1. The jQuery CSS methods allow you to manipulate CSS class or style
properties of DOM elements.
2. Use the selector to get the reference of an element(s) and then call jQuery
css methods to edit it.
3. Important DOM manipulation methods: css(), addClass(), hasClass(),
removeClass(), toggleClass() etc.

jQuery Animation
jQuery includes methods which give special effects to the elements
on hiding, showing, changing style properties, and fade-in or fade-
out operation. These special effect methods can be useful in building
an interactive user interface.

The following table lists jQuery methods for adding special effects to
the DOM elements.

jQuery Methods for Special Effects Description

animate() Perform custom animation using element's style properties.

queue() Show or manipulate the queue of functions to be executed on the specified element.

stop() Stop currently running animations on the specified element(s).

fadeIn() Display specified element(s) by fading them to opaque.

fadeOut() Hides specified element(s) by fading them to transparent.

fadeTo() Adjust the opacity of the specified element(s)

fadeToggle() Display or hide the specified element(s) by animating their opacity.

hide() Hide specified element(s).

show() Display specified element(s).

toggle() Display hidden element(s) or hide visible element(s).

slideUp() Hide specified element(s) with sliding up motion.

slideDown() Display specified element(s) with sliding down motion.

slideToggle() Display or hide specified element(s) with sliding motion.

Let's look at some important methods for special effects.


jQuery animate() Method
The jQuery animate() method performs custom animation using
element's style properties. The animate() method changes existing
style properties to the specified properties with motion.

Specify a selector to get the reference of an element to which you


want to add animation effect and then call animate() method with
JSON object for style properties, speed of animation and other
options.

Syntax:
$('selector expression').animate({ stylePropertyName : 'value'},
duration,
easing,
callback);

$('selector expression').animate({ propertyName : 'value'},


{ options });

Apply Animation
In the following example, we are changing height and width of the
element with animation.

Example: jQuery animate() Method


$('#myDiv').animate({
height: '200px',
width: '200px'
});

<div id="myDiv" class="redDiv">


</div>

Set Animation Duration


You can apply animation duration in miliseconds as a second
parameter of animate() method.
Example: Set Duration
$('#myDiv').animate({
height: '200px',
width: '200px'
},
5000);

<div id="myDiv" class="redDiv">


</div>

ADVERTISEMENT

Apply Easing Method


Specify a string parameter indicating which easing function to use for
the transition. The jQuery library provides two easing function: linear
and swing.

Example: Apply Easing Method


$('#myDiv').animate({
height: '200px',
width: '200px'
},
5000, 'swing');

<div id="myDiv" class="redDiv">


</div>

Callback Function on Animation Complete


Specify a callback function to execute when animation is complete.

Example: Specify Callback Function


$('#myDiv').animate({
height: '200px',
width: '200px'
},
5000,
function () {
$('#msgDiv').append('Animation completed');
});
});

<div id="myDiv" class="redDiv">


</div>

<div id="msgDiv"></div>

Specify Animation Options


You can specify various options as JSON object. The options include
duration, easing, queue, step, progress, complete, start, done and
always. Visit api.jquery.com for more information.

Example: Specify Options


$('#myDiv').animate({
height: '200px',
width: '200px'
},
{ // options parameter
duration: 5000,
complete: function () {
$(this).animate({
height: '100px',
width: '100px'
}, 5000,
function () {
$('#msgDiv').text('Animation
completed..');
});
},
start: function () {
$('#msgDiv').append('starting
animation..');
}
});

<div id="msgDiv"></div>

<div id="myDiv" class="redDiv">


</div>
jQuery queue() Method
The jQuery queue() method shows or manipulates the queue of
special effect functions to be executed on the specified element.

Syntax:
$('selector expression').queue();
Example: jQuery queue() Method
$('#myDiv').toggle(500);
$('#myDiv').fadeOut(500);
$('#myDiv').fadeIn(500);
$('#myDiv').slideDown(500);
$('#msgDiv').append('Animation functions: ' + $
('#myDiv').queue().length);

<div id="msgDiv"></div>

<div id="myDiv" class="redDiv">


</div>

ADVERTISEMENT

jQuery fadeIn() Method


The jQuery fadeIn() method displays specified element(s) by fading
them to opaque.

Syntax:
$('selector expression').fadeIn(speed, easing, callback);
Example: jQuery fadeIn() Method
$('#myDiv').fadeIn(5000, function () {
$('#msgDiv').append('fadeIn() completed.')
});

<div id="myDiv" class="redDiv">


</div>

<div id="msgDiv"></div>
jQuery fadeOut() Method
The jQuery fadeOut() method hides specified element(s) by fading
them to transparent.

Syntax:
$('selector expression').fadeOut(speed, easing, callback);
Example: jQuery fadeOut() Method
$('#div1').fadeOut(5000, function () {
$('#msgDiv').append('fadeOut() completed.')
});

<div id="msgDiv"></div>

<div id="myDiv" class="redDiv">


</div>

jQuery hide() and show() Method


The jQuery hide() method hides and show() method displays the
specified element. You can specify speed, easing and callback
function which will be executed when hide/show completes.

Syntax:
$('selector expression').hide(speed, easing, callback);
$('selector expression').show(speed, easing, callback);
Example: jQuery hide() & show() Methods
$('#div1').hide(500, function () {
$('#msgDiv').append('Red div is hidden.')
});

$('#div2').hide(500, function () {
$('#msgDiv').append('Yellow div is hidden.')
});

<div id="div1" class="redDiv">


</div>

<div id="div2" class="yellowDiv">


</div>

jQuery toggle() Method


The jQuery toggle() method hides or displays specified element(s).

Syntax:
$('selector expression').toggle(speed, easing, callback)
Example: jQuery toggle() Method
$('#myDiv').toggle(500, function () {
$('#msgDiv').append('fadeOut completed.')
});

<div id="myDiv" class="redDiv">


</div>

Points to Remember :

1. The jQuery special effect methods allow you to add animations on DOM
elements.
2. Use the selector to get the reference of an element(s) and then call jQuery
effect methods to edit it.
3. Important DOM manipulation methods: animate(), queue(), fadeIn(),
fadeOut(), hide(), show(), toggle(), slideUp(), slideDown() etc.

jQuery Events
You will learn about jQuery events in this section.

In most web applications, the user does some action to perform an


operation. For example, user clicks on save button to save the edited
data in a web page. Here, clicking on the button is a user's action,
which triggers click event and click event handler (function) saves
data.
Event

jQuery Event Methods


The jQuery library provides methods to handle DOM events. Most
jQuery methods correspond to native DOM events.

The following table lists all jQuery methods and corresponding DOM
events.

Category jQuery Method DOM Event

Form events blur onblur

change onchange

focus onfocus

focusin onfocusin

select onselect

submit onsubmit

Keyboard events keydown onkeydown

keypress onkeypress

keyup onkeyup

focusout

Mouse events click onclick

dblclick ondblclick

focusout

hover

mousedown onmousedown
Category jQuery Method DOM Event

mouseenter onmouseenter

mouseleave onmouseleave

mousemove onmousemove

mouseout onmouseout

mouseover onmouseover

mouseup onmouseup

Toggle

Browser events Error onerror()

Resize onresize

Scroll onscroll

Document loading Load onload

Ready

Unload onunload

Event Handling
To handle DOM events using jQuery methods, first get the reference
of DOM element(s) using jQuery selector and invoke appropriate
jQuery event method.

The following example shows how to handle button click event.

Example:Handle Button Click Event


$('#saveBtn').click(function () {
alert('Save button clicked');
});

<input type="button" value="Save" id="saveBtn" />

In the above example, we first use id selector to get a reference of


'Save' button and then call click method. We have specified handler
function as a callback function, which will be called whenever click
event of Save button is triggered.

Event Object
jQuery passes an event object to every event handler function. The
event object includes important properties and methods for cross-
browser consistency e.g. target, pageX, pageY, relatedTarget etc.

Example: jQuery Event Object


$('#saveBtn').click(function (eventObj) {
alert('X =' + eventObj.pageX + ', Y =' + eventObj.pageY);
});

<input type="button" value="Save" id="saveBtn" />

this Keyword in Event Handler


this keyword in an event handler represents a DOM element which
raised an event.

Example: this in Event Handler


$(':button').click(function (eventObj) {
alert(this.value + ' ' + this.type + ' clicked');
});

<input type="button" value="Save" id="saveBtn" />


<input type="button" value="Delete" id="delBtn" />
<input type="button" value="Clear" id="clearBtn" />

ADVERTISEMENT

Hover Events
jQuery provides various methods for mouse hover events e.g.
mouseenter, mouseleave, mousemove, mouseover, mouseout and
mouseup.

Example: Hover Events


$('#myDiv').mouseenter(function (data) {
$(this).css('background-color','green');
});

$('#myDiv').mouseleave(function (data) {
$(this).css('background-color','red');
});

<div id="myDiv" style="width:100px;height:100px">


</div>

You can use hover() method instead of handling mouseenter and


mouseleave events separately.

Example: hover() Method


$('#myDiv').hover(function () {
$(this).css('background-color','green');
},
function () {
$(this).css('background-color','red');
});

<div id="myDiv" style="width:100px;height:100px">


</div>

Event Binding using on()


jQuery allows you to attach an event handler for one or more events
to the selected elements using on method.

Internally all of the shorthand methods uses on() method. The on()
method gives you more flexibility in event binding.

Syntax:
on(types, selector, data, fn )

 Types = One or more space-separated event types and optional namespaces


 Selector = selector string
 Data = data to be passed to the handler in event.data when an event is
triggered.
 Fn = A function to execute when the event is triggered.
Example: Event Binding using on
$('#saveBtn').on('click',function () {
alert('Save Button clicked');
});

<input type="button" value="Save" id="saveBtn" />

You can use selector to filter the descendants of the selected


elements that trigger the event.

Example: Event Binding using on


$('#myDiv').on('click',':button', function () {
alert('Button clicked');
});

<div id="myDiv" >


<input type="button" value="Save" id="saveBtn" />

<input type="button" value="Add" id="addBtn" />


</div>

<input type="button" value="Delete" id="delBtn" />

In the above example, we specify ':button' selector. So click event


triggered by buttons in <div> tag whose id is myDiv, will only be
handled.

Binding Multiple Events


You can also specify multiple event types separated by space.

Example: Multiple Events Binding


$( 'myDiv' ).on('mouseenter mouseleave', function() {
$(this).text('The mouse entered or left from the div' );
});

<div id="myDiv" style="width:100px;height:100px">


</div>
Specify Named Function as Event Handler
You can create separate functions and specify that as a handler. This
is useful if you want to use the same handler for different events or
events on different elements.

Example:Binding Named Function to Event


var mouseHandler = function() {
alert( "The mouse entered" );
};

$('#myDiv').on('mouseenter', mouseHandler);

<div id="myDiv" style="width:100px;height:100px">


</div>

jQuery on() method is replacement of live() and delegate() method.

Event Bubbling
The following example demonstrates event bubbling in jQuery.

Example:Event Bubbling
$('div').click(function (event) {
alert( event.target.tagName + ' clicked');
});

<div>
<p>
<span>This is span.</span>
</p>
</div>

As you can see in the above example, we have handled click event of
<div> element in jQuery. So if you click on div, it will display alert
message 'DIV clicked'. However, if you click on span, still it will
popup alert message SPAN clicked even though we have not handled
click event of <span>. This is called event bubbling. Event bubbles
up to the document level in DOM hierarchy till it finds it.

The following figure illustrates event bubbling.

jQuery Event Bubbling

Points to Remember :

1. The jQuery event methods allow you to attach event handler or fire native
DOM events.
2. Use the selector to get the reference of an element(s) and then call jQuery
event methods to fire it or attach an event handler.
3. Important DOM manipulation methods: click(), dblClick(), change(),
submit(), keyup(), keydown(), mouseenter(), mouseleave(), hover() etc.

jQuery AJAX Introduction


AJAX stands for "Asynchronous JavaScript and XML". JavaScript
includes features of sending asynchronous http request
using XMLHttpRequest object. Ajax is about using this ability of JavaScript
to send asynchronous http request and get the xml data as a
response (also in other formats) and update the part of a web page
(using JavaScript) without reloading or refreshing entire web page.

The following figure illustrates the Ajax functionality.

Ajax

The jQuery library includes various methods to send Ajax requests.


These methods internally use XMLHttpRequest object of JavaScript.
The following table lists all the Ajax methods of jQuery.

jQuery Ajax Methods Description

ajax() Sends asynchronous http request to the server.

get() Sends http GET request to load the data from the server.

Post() Sends http POST request to submit or load the data to the server.

getJSON() Sends http GET request to load JSON encoded data from the server.

getScript() Sends http GET request to load the JavaScript file from the server and then executes it.

load() Sends http request to load the html or text content from the server and add them to DOM element(s).

The jQuery library also includes following events which will be fired
based on the state of the Ajax request.

jQuery Ajax Events Description

ajaxComplete() Register a handler function to be called when Ajax requests complete.

ajaxError() Register a handler function to be called when Ajax requests complete with an error.

ajaxSend() Register a handler function to be called before Ajax request is sent.


jQuery Ajax Events Description

ajaxStart() Register a handler function to be called when the first Ajax request begins.

ajaxStop() Register a handler function to be called when all the Ajax requests have completed.

ajaxSuccess() Register a handler function to be called when Ajax request completes successfully.

Advantages of jQuery Ajax


1. Cross-browser support
2. Simple methods to use
3. Ability to send GET and POST requests
4. Ability to Load JSON, XML, HTML or Scripts

jQuery ajax() Method


The jQuery ajax() method provides core functionality of Ajax in
jQuery. It sends asynchronous HTTP requests to the server.

Syntax:
$.ajax(url);

$.ajax(url,[options]);

Parameter description:

 url: A string URL to which you want to submit or retrieve the data
 options: Configuration options for Ajax request. An options parameter can be
specified using JSON format. This parameter is optional.

The following table list all the options available for configuring Ajax
request.

Options Description

accepts The content type sent in the request header that tells the server what kind of response it will accept in return.

async By default, all requests are sent asynchronously. Set it false to make it synchronous.

beforeSend A callback function to be executed before Ajax request is sent.


Options Description

cache A boolean indicating browser cache. Default is true.

complete A callback function to be executed when request finishes.

contentType A string containing a type of content when sending MIME content to the server.Default is "application/x-www-
form-urlencoded; charset=UTF-8"

crossDomain A boolean value indicating whether a request is a cross-domain.

data A data to be sent to the server. It can be JSON object, string or array.

dataType The type of data that you're expecting back from the server.

error A callback function to be executed when the request fails.

global A Boolean indicating whether to trigger a global Ajax request handler or not. Default is true.

headers An object of additional header key/value pairs to send along with request.

ifModified Allow the request to be successful only if the response has changed since the last request. This is done by
checking the Last-Modified header. Default value is false.

isLocal Allow the current environment to be recognized as local.

jsonp Override the callback function name in a JSONP request. This value will be used instead of 'callback' in the
'callback=?' part of the query string in the url.

jsonpCallback String containing the callback function name for a JSONP request.

mimeType String containing a mime type to override the XMLHttpRequest mime type.

password A password to be used with XMLHttpRequest in response to an HTTP access authentication request.

processData A Boolean indicating whether data assigned to data option will be converted to a query string. Default is true.

statusCode A JSON object containing numeric HTTP codes and functions to be called when the response has the
corresponding code.

success A callback function to be executed when Ajax request succeeds.

timeout A number value in milliseconds for the request timeout.

type A type of http request e.g. POST, PUT and GET. Default is GET.

url A string containing the URL to which the request is sent.

username A username to be used with XMLHttpRequest in response to an HTTP access authentication request.

xhr A callback for creating the XMLHttpRequest object.


Options Description

xhrFields An object of fieldName-fieldValue pairs to set on the native XMLHttpRequest object.

Let's see how to send http requests using $.ajax() (or jQuery.ajax())
method.

Send Ajax Request


The ajax() methods performs asynchronous http request and gets
the data from the server. The following example shows how to send
a simple Ajax request.

Example: jQuery Ajax Request


$.ajax('/jquery/getdata', // request url
{
success: function (data, status, xhr) {// success callback
function
$('p').append(data);
}
});

<p></p>

In the above example, first parameter '/getData' of ajax() method is


a url from which we want to retrieve the data.

By default ajax() method performs http GET request if option parameter does
not include method option.

The second parameter is options parameter in JSON format where we


have specified callback function that will be executed when request
succeeds. You can configure other options as mentioned in the above
table.

The following example shows how to get the JSON data using ajax()
method.
Example: Get JSON Data
$.ajax('/jquery/getjsondata',
{
dataType: 'json', // type of response data
timeout: 500, // timeout milliseconds
success: function (data,status,xhr) { // success callback
function
$('p').append(data.firstName + ' ' + data.middleName + ' ' +
data.lastName);
},
error: function (jqXhr, textStatus, errorMessage) { // error
callback
$('p').append('Error: ' + errorMessage);
}
});

<p></p>

ADVERTISEMENT

In the above example, first parameter is a request url which will


return JSON data. In the options parameter, we have specified
dataType and timeout options. The dataType option specifies the
type of response data, in this case it is JSON. The timeout parameter
specifies request timeout in milliseconds. We have also specified
callback functions for error and success.

The ajax() method returns an object of jQuery XMLHttpRequest. The


following example shows how to use jQuery XMLHttpRequest object.

Example: ajax() Method


var ajaxReq = $.ajax('GetJsonData', {
dataType: 'json',
timeout: 500
});

ajaxReq.success(function (data, status, jqXhr) {


$('p').append(data.firstName + ' ' + data.middleName + ' ' +
data.lastName);
})

ajaxReq.error(function (jqXhr, textStatus, errorMessage) {


$('p').append('Error: ' + errorMessage);
})

<p></p>

Send Http POST request using ajax()


The ajax() method can send all type of http requests. The following
example sends http POST request to the server.

Example: Send POST Request


$.ajax('/jquery/submitData', {
type: 'POST', // http method
data: { myData: 'This is my data.' }, // data to submit
success: function (data, status, xhr) {
$('p').append('status: ' + status + ', data: ' + data);
},
error: function (jqXhr, textStatus, errorMessage) {
$('p').append('Error' + errorMessage);
}
});
<p></p>

In the above example, first parameter is a url which is used to


submit the data. In the options parameter, we have specified a type
option as a POST, so ajax() method will send http POST request.
Also, we have specified data option as a JSON object containing data
which will be submitted to the server.

So this way you can send GET, POST or PUT request using ajax()
method.

Visit jQuery documentation to know more about ajax() method.

Points to Remember :

1. $.ajax() method allows you to send asynchronous http requests to submit


or retrieve data from the server without reloading the whole page.
2. $.ajax() can be used to send http GET, POST, PUT, DELETE etc. request. It
can retrieve any type of response from the server.
3. Syntax: $.ajax(url,[options])
4. Use option parameter to customize ajax request as per your need.

jQuery get() Method


The jQuery get() method sends asynchronous http GET request to
the server and retrieves the data.

Syntax:
$.get(url, [data],[callback]);

Parameters Description:

 url: request url from which you want to retrieve the data
 data: data to be sent to the server with the request as a query string
 callback: function to be executed when request succeeds

The following example shows how to retrieve data from a text file.

Example: jQuery get() Method


$.get('/data.txt', // url
function (data, textStatus, jqXHR) { // success callback
alert('status: ' + textStatus + ', data:' + data);
});

In the above example, first parameter is a url from which we want to


retrieve the data. Here, we want to retrieve data from a txt file
located at mydomain.com/data.txt. Please note that you don't need
to give base address.

Internally, jQuery get() method calls ajax() method only.


Visit james.padolsey.com/jquery and search for get() method to see the source code.

The second parameter is a callback function that will be executed


when this GET request succeeds. This callback function includes three
parameters data, textStatus and jQuery wrapper of XMLHttpRequest
object. Data contains response data, textStatus contains status of
request and jqXHR is a jQuery XMLHttpRequest object which you can
use for further process.
The following example shows how to retrieve JSON data using get()
method.

Example: Retrieve JSON Data using get()


$.get('/jquery/getjsondata', {name:'Steve'}, function (data,
textStatus, jqXHR) {
$('p').append(data.firstName);
});

<p></p>

In the above example, first parameter is a url from which we want to


retrieve JSON data. This url can be a web service or any other url
that returns data in JSON format.

The second parameter is data to be sent to the server as a query


string. We have specified name parameter with value 'Steve' in the
JSON format. So now, the request url would look like
http://mydomain.com/jquery/getjsondata?name=Steve

The third parameter is a callback function that will be executed when


this GET request succeeds.

jQuery getJSON() Method


The jQuery getJSON() method sends asynchronous http GET request
to the server and retrieves the data in JSON format by setting
accepts header to application/json, text/javascript. This is same as
get() method, the only difference is that getJSON() method
specifically retrieves JSON data whereas get() method retrieves any
type of data. It is like shortcut method to retrieve JSON data.

Syntax:
$.getJSON(url,[data],[callback]);

Parameter Description:

 url: request url from which you want to retrieve the data
 data: JSON data to be sent to the server as a query string
 callback: function to be executed when request succeeds
The following example shows how to retrieve JSON data using
getJSON() method.

Example: jQuery getJSON() Method


$.getJSON('/jquery/getjsondata', {name:'Steve'}, function (data,
textStatus, jqXHR){
$('p').append(data.firstName);
});

<p></p>

In the above example, first parameter is a url from which we want to


get JSON data. This can be a web service or any other url that
returns JSON data.

The second parameter is data to pass as query string with the GET
request. So now, the request url would look like
http://mydomain.com/jquery/getjsondata?name=Steve

Internally, jQuery getJSON() method calls get() method and set dataType to
JSON. Visit james.padolsey.com/jquery and search for get() method to see the source
code.

The third parameter is a callback function which will be executed


when request succeeds. The data parameter will be in the JSON
format because getJson() method automatically converts server
response into a JSON object.

You can attach fail and done callback methods to getJson() method
as shown below.

Example: getJSON() Method


$.getJSON('/jquery/getjsondata', { name:'Steve'}, function(data,
textStatus, jqXHR){
alert(data.firstName);
})
.done(function () { alert('Request done!'); })
.fail(function (jqxhr,settings,ex) { alert('failed, '+
ex); });
ADVERTISEMENT

jQuery getScript() Method


The jQuery getScript() method sends http GET request to the server,
retrieves the JavaScript file and then executes it. Internally, jQuery
getScript() method calls get() method and sets dataType to script.

Syntax:
$.getScript(url, [callback]);

Parameter Description:

 url: request url from which you want to download JavaScript file
 callback: function to be executed when request succeeds

The following example shows how to download script file using


getScript() method.

Example: jQuery getScript() Method


$.getScript('/Scripts/myJavaScriptFile.js',
function(script,status,jqxhr){
alert(status);
});

In the above example, first parameter is a url from which we want to


download script file. Here, we download myJavaScriptFile.js file for
demo purpose.

The second parameter is a callback function which will be executed


when request succeeds.

Thus, you can use different get methods to retrieve different types of
resources using http get request.

Points to Remember :

1. $.get(), $.getJSON() method allows you to send asynchronous http GET


request to retrieve the data from the server without reloading whole page.
2. $.get() can be used to retrieve any type of response from the server.
3. $.getJSON() method is a short form method to retrieve JSON response from
the server.
4. $.getScript() sends asynchronous http GET request to retrieve the script
files from the server and execute it.
5. Syntax:
$.get(url,[data],[callback])
$.getJSON(url,[data],[callback])
$.getScript(url,[callback])

jQuery post() Method


The jQuery post() method sends asynchronous http POST request to
the server to submit the data to the server and get the response.

Syntax:
$.post(url,[data],[callback],[type]);

Parameter Description:

 url: request url from which you want to submit & retrieve the data.
 data: json data to be sent to the server with request as a form data.
 callback: function to be executed when request succeeds.
 type: data type of the response content.

Let's see how to submit data and get the response using post()
method. Consider the following example.

Example: jQuery post() Method


$.post('/jquery/submitData', // url
{ myData: 'This is my data.' }, // data to be submit
function(data, status, jqXHR) {// success callback
$('p').append('status: ' + status + ', data: ' +
data);
})

<p></p>

In the above example, first parameter is a url to which we want to


send http POST request and submit the data.
Internally, post() method calls ajax() method with method option to POST.
Visit james.padolsey.com/jquery and search for post() method to see the jQuery source
code.

The second parameter is a data to submit in JSON format, where key


is the name of a parameter and value is the value of parameter.

The third parameter is a success callback function that will be called


when request succeeds. The callback function can have three
parameters; data, status and jqXHR. The data parameter is a
response coming from the server.

The following example shows how to submit and retrieve JSON data
using post() method.

Example: submit JSON Data using post() Method


$.post('/submitJSONData', // url
{ myData: 'This is my data.' }, // data to be submit
function(data, status, xhr) { // success callback function
alert('status: ' + status + ', data: ' +
data.responseData);
},
'json'); // response data format

In the above example, please notice that last parameter is a type of


response data. We will get JSON data as a server response. So post()
method will automatically parse response into JSON object. Rest of
the parameters are same as first example.

You can also attach fail and done callback methods to post() method
as shown below.

Example: jQuery post() Method


$.post('/jquery/submitData',
{ myData: 'This is my data.' },
function(data, status, xhr) {

$('p').append('status: ' + status + ', data: ' + data);

}).done(function() { alert('Request done!'); })


.fail(function(jqxhr, settings, ex) { alert('failed, ' +
ex); });
<p></p>

Points to Remember :

1. $.post() method allows you to send asynchronous http POST request


to submit and retrieve the data from the server without reloading
whole page.
2. Syntax:
$.post(url,[data],[callback],[type])
3. Specify type parameter for the type of response data e.g. specify
'JSON' if server return JSON data.
4. Internally post() method calls ajax() method only by passing
method='POST' as option.

jQuery load() Method


The jQuery load() method allows HTML or text content to be loaded
from a server and added into a DOM element.

Syntax:
$.load(url,[data],[callback]);

Parameters Description:

 url: request url from which you want to retrieve the content
 data: JSON data to be sent with request to the server.
 callback: function to be executed when request succeeds

The following example shows how to load html content from the
server and add it to div element.

Example: Load HTML Content


$('#msgDiv').load('/demo.html');

<div id="msgDiv"></div>

In the above example, we have specified html file to load from the
server and add its content to the div element.
Note : If no element is matched by the selector then Ajax request will not be
sent.

The load() method allows us to specify a portion of the response


document to be inserted into DOM element. This can be
achieved using url parameter, by specifying selector with url
separated by one or multiple space characters as shown in the
following example.

Example: jQuery load() Method


$('#msgDiv').load('/demo.html #myHtmlContent');

<div id="msgDiv"></div>

In the above example, content of the element whose id is


myHtmlContent, will be added into msgDiv element. The following is
a demo.html.

demo.html content:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<h1>This is demo html page.</h1>
<div id="myHtmlContent">This is my html content.</div>
</body>
</html>

The load() method also allows us to specify data to be sent to the


server and fetch the data.

Example: Set Data in load()


$('#msgDiv').load('getData', // url
{ name: 'bill' }, // data
function(data, status, jqXGR) { // callback
function
alert('data loaded')
});

<div id="msgDiv"></div>
In the above example, first parameter is a url from which we want to
fetch the resources. The second parameter is data to be sent to the
server. The third parameter is a callback function to execute when
request succeeds.

Points to Remember :

1. $.load() method allows HTML or text content to be loaded from a


server and added into a DOM element.
2. Syntax:
$.post(url,[data],[callback])
3. Specify selector with url to specify a portion of the response
document to be inserted into DOM element.
$('#msgDiv').load('/demo.html #myHtmlContent');

jQuery: Selector Reference


Selector Pattern Example Description

Element $('div') Selects all <div> elements

:first $('div:first') Selects first <div> element in a DOM hierarchy.

:last $('div:last') Selects last <div> element in a DOM hierarchy.

Multiple elements $('p, div, code') Selects <p>,<div> and <code> elements

parent descendant $('div p') Selects all <p> elements which is descendant of <div>

parent child $('div > p') Selects <p> element which is child of <div>

* $(*) Selects all elements

#Id $("#myDiv") Selects element whose id is myDiv

element#id $("div#myDiv") Selects <div> element whose Id is myDiv

Multiple Ids $("#myDiv1, #myDiv2") Selects multiple elements whose id is myDiv1 or myDiv2.

.class $(".myCSSClass") Selects all the elements with class=myCSSClass.

.class .class $(".myCSSClass1, .myCSSClass2 ") Finds all elements whose class attribute is set
to myCSSClass1 or myCSSClass2

element.class $("div.myCSSClass") Finds all <div> elements with class=myCSSClass


Selector Pattern Example Description

:first-child $("p:first-child") Selects all <p> elements which is the first child of its parent
element. (parent element can be anything)

:last-child $("p:last-child") Selects all <p> elements which is the last child of its parent
element. (parent element can be anything)

:nth-child(n) $("p:nth-child(5)") Selects all <p> elements which is the 5th child of its parent
element. (parent element can be anything)

:nth-last-child(n) $("p:nth-last-child(2)") Selects all <p> elements which is the 2nd last child of its parent
element. (parent element can be anything)

:only-child $("p:only-child") Selects all <p> elements which is the only child of its parent
element. (parent element can be anything)

[attribute] $('[class]') Selects all the elements with the class attribute(whatever the
value).

[element[attribute] $("div[class]") Selects all the <div> elements that have


a class attribute(whatever the value).

element[attribute = $("div[class='myCls']") Selects all the <div> elements whose class attributes are equal
value] to myCls.

element[attribute |= $("div[class|= 'myCls']") Selects all the <div> elements whose class attributes are either
value] equal to myCls or starting with myCls string followed by a
hyphen (-).

element[attribute *= $("div[class *= 'myCls']") Selects <div> elements whose class attributes contains myCls.
"value"]

element[attribute ~= $("div[class ~= 'myCls']") Selects div elements whose class attributes contains myCls,
"value"] delimited by spaces.

element[attribute $= $("div[class $= 'myCls']") Selects <div> elements whose class attribute value ends
"value"] with myCls. The comparison is case sensitive.

element[attribute != $("div[class != 'myCls']") Selects <div> elements which do not have class attribute or
"value"] value does not equal to myCls.

element[attribute ^= $("div[class ^= 'myCls']") Selects <div> elements whose class attribute value starts with
"value"] myCls.

:contains("value") $("div:contains('tutorialsteacher')" Selects all <div> elements that contains the


text 'tutorialsteacher'

:input $(":input") Selects all input elements.

:button $(":button") Selects all input elements where type="button".


Selector Pattern Example Description

:radio $(":radio") Selects all input types where type="radio"

:text $(":text") Selects all input elements where type="text" .

":checkbox" $(":checkbox") Selects all checkbox elements.

:submit $(":submit") Selects all input elements where type="submit".

:password $(":password") Selects all input elements where type="password".

:reset $(":reset") Selects all input elements where type="reset".

:image $(':image') Selects all input elements where type="image".

:file $(':file') Selects all input elements where type="file".

:enabled $(':enabled') Selects all enabled input elements.

:disabled $(':disabled') Selects all disabled input elements.

:selected $(':selected') Selects all selected input elements.

:checked $(':checked') Selects all checked input elements.

:hidden $(':hidden') Selects all hidden elements.

:visible $(':visible') Selects all visible elements.

:odd $('tr:odd') Selects all odd rows. (1,3,5,7..)

:even $('tr:even') Selects all even rows.(0,2,4,6..)

jQuery: DOM Manipulation Methods


Method Description

append Inserts DOM elements at the end of selected element(s).

appendTo Perform same task as append() method. The only difference is syntax. Here, first specify DOM elements as
a string which you want to insert and then call appendTo() method with selector expression to select the
elements where you want to append the specified DOM elements.

before Inserts content (new or existing DOM elements) before specified element(s) by a selector.
Method Description

after Inserts content (new or existing DOM elements) after selected element(s) by a selector.

detach Removes the specified element(s).

empty Removes all child element(s) of selected element(s).

html Get or Set html content to the selected element(s).

insertAfter Insert DOM element(s) after selected element(s). Perform same task as after() method, the only
difference is syntax.

insertBefore Insert DOM element(s) before selected element(s). Perform same task as before() method, the only
difference is syntax.

prepend Insert content at the beginning of the selected element(s).

prependTo Insert content at the beginning of the selected element(s). Perform same task as prepend() method, the
only difference is syntax.

prop Get or Set the value of specified property of selected element(s).

remove Removes selected element(s) from the DOM.

removeAttr Removes specified attribute from selected element(s).

removeProp Removes specified property from selected element(s).

replaceAll Replace all target element(s) with specified element.

replaceWith Replace all target element(s) with specified element and return the set of elements which was removed.

text Get or set text content of the selected element(s).

wrap Wrap an HTML structure around each selected element(s).

unwrap Remove the parents of selected element(s).

val Get or set the value of selected element(s)

wrapAll Combine all the selected element(s) and wrap them with specified HTML.

wrapInner Wrap an inner html of selected element(s) with specified HTML.

CSS Methods
CSS Methods Description

css Get or set style properties to the selected element(s).

addClass Add one or more CSS class to the selected element(s).


CSS Methods Description

hasClass Determine whether any of the selected elements are assigned the given CSS class.

removeClass Remove a single class, multiple classes, or all classes from the selected element(s).

toggleClass Toggles between adding/removing classes to the selected elements

Dimensions Methods
Dimensions Methods Description

height Get or set height of the selected element(s).

innerHeight Get or set inner height (padding + element's height) of the selected element(s).

outerHeight Get or set outer height (border + padding + element's height) of the selected element(s).

offset Get or set left and top coordinates of the selected element(s).

position Get the current coordinates of the selected element(s).

width Get or set the width of the selected element(s).

innerWidth() Get or set the inner width (padding + element's width) of the selected element(s).

outerWidth Get or set outer width (border + padding + element's width) of the selected element(s).

scrollLeft Get or set the current horizontal position of the scrollable content of selected element.

scrollTop Get or set the current vertical position of the scrollable content of selected element.

jQuery: DOM Traversing Methods


Method Description

add() Creates a single jQuery object for all added elements, so that it will be easy to manipulate them at
the same time.

addBack() Creates a single jQuery object for the set of selected elements by selector.

children() Get all the child elements of the selected element(s).

closest() Traversing up through its ancestors in the DOM tree untill it finds first matched element(s) specified
by a selector.
Method Description

contents() Gets children of all the selected element(s), including text and comment nodes.

each() Iterate over specified elements and execute specified call back function for each element.

end() End the most recent filtering operation in the current chain and return the set of matched elements
to its previous state.

eq() Returns element(s) at the specified index from the selected element (return from selector).

filter() Reduce the set of matched elements to those that match the selector or pass the function's test.

find() Get all the specified child elements of each selected element(s).

first() Get the first occurrence of the specified element.

has() Reduce the set of matched elements to those that have a descendant that matches the selector or
DOM element.

is() Check the current matched set of elements against a selector, element, or jQuery object and return
true if at least one of these elements matches the given arguments.

last() Returns last element that matched specified selector.

map() Pass each element in the current matched set through a function, producing a new jQuery object
containing the return values.

next() Get the immediately following sibling of�the selected element(s).

nextAll() Get the immediately following sibling of�the selected element(s).

nextUntil() Gets all next sibling elements between two given arguments

not() Selects elements that do not match the specified selector in not() method.

offsetParent() Selects the closest ancestor element whose left and top co-ordinates are closest to matched
elements by selector.

parent() Get the parent of the specified element(s).

parents() Selects all ancestor elements of the matched element(s) by a selector.

parentsUntil() Selects all the ancestor elements of the matched element(s), up to but not including the element
specified in parentsUntil().

prev() Selects the immediately preceding sibling of the specified element.

prevAll() Selects all preceding siblings of each matched element, optionally filtered by a selector.

prevUntil() Selects all preceding siblings of each matched element up to but not including matched elements by
Method Description

selector parameter.

siblings() Get the siblings of each�specified element(s), optionally filtered by a selector.

slice() Selects elements by further filtering elements by specifying a selector parameter.

jQuery: Effect Methods


Method Description

animate() Perform custom animation using element's style properties.

Example: $('#myDiv').animate({ height: '200px', width:


'200px'});

clearQueue() Remove all the animations from the queue that have not been run.

Example: $('#myDiv').clearQueue();

delay() Set a timer to delay execution of animations in the queue.

Example: $('#myDiv').delay(5000);

dequeue() Execute the next animation in the queue for the selected element.

Example: $('#myDiv').dequeue();

queue() Show or manipulate the queue of functions to be executed on the selected element.

Example: $('#myDiv').queue().length

fadeIn() Display selected element(s) by fading them to opaque.

Example: $('#myDiv').fadeIn(5000);

fadeOut() Hides selected element(s) by fading them to transparent.

Example: $('#myDiv').fadeOut(5000);

fadeTo() Adjust the opacity of the selected element(s)

Example: $('#myDiv').fadeTo(500);
Method Description

fadeToggle() Display or hide the selected element(s) by animating their opacity.

Example: $('#myDiv').fadeToggle(5000);

finish() Stop currently running animation and clear the queue for selected element(s)

Example: $('#myDiv').finish();

jQuery.fx.interval The rate at which animation fires.

Example: $.fx.interval = 2000

jQuery.fx.off Disable all the animations globally.

Example: $.fx.off;

hide() Hide selected element(s).

Example: $('#myDiv').hide(5000);

show() Display selected element(s).

Example: $('#myDiv').show(5000);

stop() Stop currently running animations on the selected element(s).

Example: $('#myDiv').stop()

toggle() Display hidden element(s) or hide visible element(s).

Example: $('#myDiv').toggle(5000);

slideUp() Hide selected element(s) with sliding up motion.

Example: $('#myDiv').slideUp(5000);

slideDown() Display selected element(s) with sliding down motion.

Example: $('#myDiv').slideDown(5000);

slideToggle() Display or hide selected element(s) with sliding motion.

Example: $('#myDiv').slideToggle(5000);
jQuery: Events Methods
Category Method Description

Form events blur Attaches or fires JavaScript "blur" event (when cursor go out from the input
element).

change Attach or fire JavaScript "change" event.

focus Attach or fire JavaScript "focus" event.

focusin Attach event handler for "focusin" event.

select Attach or fire JavaScript "select" event.

submit Attach or fire JavaScript "submit" event.

Keyboard events keydown Attach or fire JavaScript "keydown" event.

keypress Attach or fire JavaScript "keypress" event.

keyup Attach or fire JavaScript "keyup" event.

focusout Attach or fire JavaScript "focusout" event.

Mouse events click Attach or fire JavaScript "click" event.

dblclick Attach or fire JavaScript "dblclick" event.

hover Attach one or two event handlers to be executed when mouse pointer
enters or leaves selected element(s).

mousedown Attach or fire JavaScript "mousedown" event.

mouseenter Attach or fire event when mouse pointer enters in selected element(s).

mouseleave Attach or fire event when mouse pointer moves away from the selected
element(s).

mousemove Attach or fire JavaScript "mousemove" event.

mouseout Attach or fire JavaScript "mouseout" event.

mouseover Attach or fire JavaScript "mouseover" event.

mouseup Attach or fire JavaScript "mouseup" event.

toggle Attach two or more handlers to the matched elements, to be executed on


alternate clicks.
Category Method Description

Browser events error Attach or fire JavaScript "error" event.

resize Attach or fire JavaScript "resize" event.

scroll Attach or fire JavaScript "scroll" event.

Document loading Load Attach or fire JavaScript "load" event.

ready Specify a function to be executed when DOM is loaded completely.

unload Attach or fire JavaScript "unload" event.

You might also like