Professional Documents
Culture Documents
New C#
New C#
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.
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;
- 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.
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#:
C# 1.0 .NET Framework 1.0/1.1 Visual Studio .NET 2002 Basic features
Version .NET Framework Visual Studio Important Features
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# 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
Using declarations
Static local functions
Disposable ref structs
Nullable reference types
more..
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.
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.
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.
C# Console Program
namespace CSharpTutorials
{
class Program
{
static void Main(string[] args)
{
string message = "Hello World!!";
Console.WriteLine(message);
}
C# Code 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
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
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.).
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
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
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
@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.
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);
}
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:
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;
You can also apply some additional logic in get and set, as in the
below example.
Example: Property in C#
private int _myPropertyVar;
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.
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 (.).
Example: Namespace
namespace CSharpTutorials
{
class MyClass
{
}
}
Example: Namespace
namespace CSharpTutorials.Examples
{
class MyClassExample
{
}
}
C# Variables
In C#, a variable contains a data value of the specific data type.
Syntax
<data type> <variable name> = <value>;
Example: C# Variable
int num = 100;
Example: C# Variables
int num = 100;
float rate = 10.2f;
decimal amount = 100.50M;
char code = 'C';
bool isValid = true;
string name = "Steve";
Example: C# Variable
int num = 100;
num = 200;
Console.WriteLine(num); //output: 200
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.
In C#, variables must be declared with the data type. These are
called explicitly typed variables.
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.
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.
2,147,483,647
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)
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.
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;
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.
byte short, ushort, int, uint, long, ulong, float, double, 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.
Numbers in C#
Numbers, in general, can be divided into two types: Integer type and
floating-point types.
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.
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.
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.
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.
Console.WriteLine(Int64.MaxValue);//9223372036854775807
Console.WriteLine(Int64.MinValue);//-9223372036854775808
Console.WriteLine(UInt64.MaxValue);//18446744073709551615
Console.WriteLine(UInt64.MinValue);//0
Try it
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.
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.
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.
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.
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.
Please note that you must use a backslash to allow " in a string. @ is
only for special characters in C#.
String Concatenation
Multiple strings can be concatenated with + operator.
string agent = "Mr." + firstName + " " + lastName + ", Code: " + code;
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.
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.
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);
Console.WriteLine(newDate);//1/1/2016 1:20:55 AM
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);
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;
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.
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.
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.
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.
Console.WriteLine(point.x); //output: 0
Console.WriteLine(point.y); //output: 0
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.
public int x
{
get{
return _x;
}
set{
_x = value;
CoordinatesChanged(_x);
}
}
public int y
{
get{
return _y;
}
set{
_y = value;
CoordinatesChanged(_y);
}
}
point.CoordinatesChanged += StructEventHandler;
point.x = 10;
point.y = 20;
}
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.
Access an Enum
An enum can be accessed using the dot syntax: enum.member
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.
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.
Example: StringBuilder
using System.Text; // include at the top
Example: StringBuilder
StringBuilder sb = new StringBuilder(50); //string will be appended
later
//or
StringBuilder sb = new StringBuilder("Hello World!", 50);
You can iterate the using for loop to get or set a character at the
specified index.
Output:
Hello World!
Hello C#.
Example: AppendFormat()
StringBuilder sbAmout = new StringBuilder("Your total amount is ");
sbAmout.AppendFormat("{0:C} ", 25);
Example: Insert()
StringBuilder sb = new StringBuilder("Hello World!");
sb.Insert(5," C#");
Example: Remove()
StringBuilder sb = new StringBuilder("Hello World!",50);
sb.Remove(6, 7);
Example: Replace()
StringBuilder sb = new StringBuilder("Hello World!");
sb.Replace("World", "C#");
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
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.
Output:
1-John
2-Steve
3-Bill
4-Ram
5-Ron
An
onymous Type Intellisense Support in Visual Studio
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.
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.
Console.WriteLine(MyDynamicVar.GetType());
Output:
System.Int32
Example: dynamic
static void Main(string[] args)
{
dynamic MyDynamicVar = 100;
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:
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.
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.
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.
// 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.
Invalid
use of Nullable Type
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>.
?? Operator
Use the '??' operator to assign a nullable type to a non-nullable type.
int j = i ?? 0;
Console.WriteLine(j);
Output:
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
if(mycls.i == null)
Console.WriteLine("Null");
}
}
Output:
Null
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:
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
Points to Remember :
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.
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':
bool
byte
char
decimal
double
enum
float
int
long
sbyte
short
struct
uint
ulong
ushort
Console.WriteLine(x);
}
Console.WriteLine(i);
ChangeValue(i);
Console.WriteLine(i);
}
Output:
100
200
100
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.
String
Arrays (even if their elements are value types)
Class
Delegate
ChangeReferenceType(std1);
Console.WriteLine(std1.StudentName);
}
Output:
Steve
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.
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.
The following interface declares some basic functionalities for the file
operations.
Example: C# Interface
interface IFile
{
void ReadFile();
void WriteFile(string text);
}
Implementing an Interface
A class or a Struct can implement one or more interfaces using colon
(:).
Syntax: <Class or Struct Name> : <Interface Name>
Note:
Interface members must be implemented with the public modifier;
otherwise, the compiler will give compile-time errors.
file2.ReadFile();
file2.WriteFile("content");
}
}
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);
}
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
}
}
interface IBinaryFile
{
void OpenBinaryFile();
void ReadFile();
}
void IBinaryFile.OpenBinaryFile()
{
Console.WriteLine("Opening Binary File");
}
void IBinaryFile.ReadFile()
{
Console.WriteLine("Reading Binary File");
}
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
}
}
Points to Remember :
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.
Example: + Operator
int x = 5 + 5;
int y = 10 + x;
int z = x + y;
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).
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.
+ 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
/ 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
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.
< 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.
! 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
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 Equality
x || y Conditional OR
x ?? y Null-coalescing operator
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.
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");
}
}
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
}
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.
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
}
}
}
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
C# - Ternary Operator ?:
Syntax:
condition ? statement 1 : statement 2
var result = x > y ? "x is greater than y" : "x is less than y";
Console.WriteLine(result);
output:
x is greater than y
var result = x > y ? "x is greater than y" : "x is less than y";
Console.WriteLine(result);
output:
x is less than y
if (x > y)
Console.WriteLine("x is greater than y");
else
Console.WriteLine("x is less than y");
output:
x is greater than y
Example: Nested ?:
int x = 10, y = 100;
Console.WriteLine(result);
Example: Nested ?:
var x = 2, y = 10;
C# - 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.
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
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.
switch (x % 2)
{
case 0:
Console.WriteLine($"{x} is an even value");
break;
case 1:
Console.WriteLine($"{x} is an odd Value");
break;
}
Output:
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.
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
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;
}
return false;
}
Output:
Odd value
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;
}
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 :
C# for Loop
Syntax:
for (initializer; condition; iterator)
{
//code block
}
The for loop contains the following three optional sections, separated
by a semicolon:
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
The below figure illustrates the execution steps of the for loop.
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.
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.
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.
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
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.
Output:
Value of i: 0, J: 0
Value of i: 1, J: 1
Value of i: 2, J: 2
Output:
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.
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;
}
while (i > 0)
{
Console.WriteLine("i = {0}", i);
i++;
}
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.
do
{
Console.WriteLine("i = {0}", i);
i++;
Output:
i = 0
i = 1
i = 2
i = 3
i = 4
do
{
Console.WriteLine("i = {0}", i);
i++;
if (i > 5)
break;
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.
do
{
Console.WriteLine("Value of i: {0}", i);
int j = i;
i++;
do
{
Console.WriteLine("Value of j: {0}", j);
j++;
} while (j < 2);
Output:
i = 0
j = 0
j = 1
i = 1
j = 1
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;
}
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; }
}
EmployeeMethods.cs
public partial class Employee
{
partial void GenerateEmployeeId()
{
this.EmpId = random();
}
}
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.
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.
Above, the Calculator class is a static. All the members of it are also
static.
Static Fields
Static fields in a non-static class can be defined using
the static keyword.
class Program
{
static void Main(string[] args)
{
StopWatch sw1 = new StopWatch();
StopWatch sw2 = new StopWatch();
Console.WriteLine(StopWatch.NoOfInstances); //2
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.
// 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() { }
}
DisplayInfo called
DisplayInfo called
The following example shows that the static constructor gets called
when you create an instance for the first time.
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.
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
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.
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.
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.
nums.Max(); // returns 16
nums.Min(); // returns 6
nums.Sum(); // returns 55
nums.Average(); // returns 55
UpdateArray(nums);
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.
// or
int[,] arr2d = {
{1, 2},
{3, 4},
{5, 6}
};
Two-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.
You can also initialize a jagged array upon declaration like the below.
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.
new int[4]{4, 5, 6, 7}
};
If you add one more bracket then it will be array of array of arry.
Console.WriteLine(intJaggedArray[0][0][0]); // 1
Console.WriteLine(intJaggedArray[0][1][1]); // 5
Console.WriteLine(intJaggedArray[1][0][2]); // 9
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.
Prerequisites
Basic knowledge of C#, HTML, Visual Studio, and Object Oriented
Programming is required.
You can view, download, or contribute to the source code using the
following GitHub repositories:
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.
.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
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
.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.
2.1.805
ADVERTISEMENT
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 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
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
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
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.
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
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
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.
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 .
host.Run();
}
}
Thus, you can rename the default web root folder wwwroot as per
your choice.
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();
}
CreateDefaultBuilder()
Copy
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;
}
startup.cs
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.
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.
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.
new Creates a new project, configuration file, or solution based on the specified template.
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.
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
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.
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.
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.
Copy
services.Add(new ServiceDescriptor(typeof(ILog),
typeof(MyConsoleLogger), ServiceLifetime.Transient)); // Transient
services.Add(new ServiceDescriptor(typeof(ILog),
typeof(MyConsoleLogger), ServiceLifetime.Scoped)); // Scoped
}
ADVERTISEMENT
Copy
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.
Copy
return View();
}
}
Copy
using Microsoft.AspNetCore.Mvc;
return View();
}
}
Property Injection
Built-in IoC container does not support property injection. You will
have to use third party IoC container.
Copy
return View();
}
}
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
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.
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.
Using IApplicationBuilder
We can get the services in Configure method using
IApplicationBuilder's ApplicationServices property as shown below.
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.
AS
P.NET Core Middleware
});
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);
//or
Example: Use()
Copy
await next();
});
The above example will display Hello World From 1st Middleware!Hello
World From 2nd Middleware! in the browser.
Middleware Description
StaticFiles Adds support for serving static files and directory browsing.
Diagnostics Adds support for reporting and handling exceptions and errors.
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.
StatusCodePagesMiddleware UseStatusCodePages() Check for responses with status codes between 400 and
599.
Middleware Extension Method Description
Copy
The above example will display the following welcome page for each
request.
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.
Copy
return _next(httpContext);
}
}
As you can see above, the Invoke() method is not asynchronous. So,
change it to asynchronous and write your custom logic before calling
next();
Copy
_logger = logFactory.CreateLogger("MyMiddleware");
}
Copy
1. Default.html
2. Default.htm
3. Index.html
4. Index.htm
app.UseStaticFiles();
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
Copy
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
}
}
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.
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.
Copy
if (env.IsDevelopment() || env.IsStaging())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
Copy
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
Note:
Visual Studio automatically creates Error.cshtml under Home folder when you
create ASP.NET Core project with MVC template.
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
Default.html
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
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.
Ser
ving Static Files
Note:
Example: UseFileServer
Copy
Copy
app.UseStaticFiles(new StaticFileOptions() {
FileProvider = new
PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),
"Content")),
RequestPath = new PathString("/Admin")
});
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.
So, there are two important building blocks for implementing logging
in a .NET Core based application:
1. Logging API
2. Logging Providers
.NET Frameworks
Logging API
As mentioned before, Microsoft provides logging API as an extension
in the wrapper Microsoft.Extensions.Logging which comes as a NuGet
package.
ILoggerFactory
The ILoggerFactory is the factory interface for creating an
appropriate ILogger type instance and also for adding
the ILoggerProvider instance.
ILoggerProvider
The ILoggerProvider manages and creates an appropriate logger,
specified by the logging category.
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.
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.
Microsoft.Extensions.Logging.Console Console
Microsoft.Extensions.Logging.AzureAppServices Azure App Services 'Diagnostics logs' and 'Log stream' features
Microsoft.Extensions.Logging.EventSource EventSource/EventListener
The following figure illustrates how the logging API works with the
console logging provider.
Log
ging API with Console Logging Provider
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).
After successfully installing the above two packages, you can now
implement logging in your .NET Core console application, as shown
below.
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();
info: DotnetCoreConsoleApp.Program[0]
Log Levels
Log levels indicate the importance or severity of log messages. Built-
in log providers include extension methods to indicate log levels.
Trace 0 LogTrace() Logs messages only for tracing purposes for the developers.
Warning 3 LogWarning() Logs messages for abnormal or unexpected events in the application flow.
namespace DotnetCoreConsoleApp
{
class Program
{
static void Main(string[] args)
{
ILoggerFactory loggerFactory = new
LoggerFactory().AddConsole((_, __) => true);
ILogger logger = loggerFactory.CreateLogger<Program>();
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
Copy
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
Copy
namespace AspDotNetCoreMvcApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger _logger;
return View();
}
return View();
}
}
}
info: AspDoteNetCoreMvcApp.Controllers.HomeController[0]
return View();
}
return View();
}
}
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
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
.NET Frameworks
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
.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.
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.
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>
</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.
Prerequisites
Basic knowledge of .NET Framework 4.5, C#, and Visual Studio is
required.
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.
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
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.2 - Current VS 2013 .NET 4.5 28-Aug-2014 Attribute based routing
bug fixes and minor features update
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.
Open Visual Studio 2017 and select File menu -> New -> Project,
as shown below.
Create a New Project in Visual Studio
From the New ASP.NET Web Application dialog, select MVC (if not
selected already) as shown below.
Select MVC Project Template
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.
In this way, you can create your ASP.NET MVC 5 application using
Visual Studio 2017.
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
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.
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.
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.
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.
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.
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.
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+" }
);
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.
Copy
Register Route
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.
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.
MVC will throw "The resource cannot be found" error when you do not append
"Controller" to the controller class name.
Note:
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();
}
}
}
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";
}
}
}
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:
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.
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.
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.
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");
}
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.
[ActionName("Find")]
public ActionResult GetById(int id)
{
// get student from the database
return View();
}
}
NonAction
Use the NonAction attribute when you want public method in a
controller but do not want to treat it as 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();
}
}
GET To retrieve the information from the server. Parameters will be appended in the query string.
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.
Copy
[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");
}
}
Example: AcceptVerbs
Copy
[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]
public ActionResult GetAndPostAction()
{
return RedirectToAction("Index");
}
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.
Copy
The model class can be used in the view to populate the data, as well
as sending data to the controller.
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.
.vbhtml Visual Basic Razor view. Supports Visual Basic code with html tags.
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...
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
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
This will create the Index view under View -> Student folder, as
shown below:
View
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>
</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.
Example: StudentController
Copy
Copy
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>
</table>
Copy
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.
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.
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.
Editor
You can use any JavaScript editor to write jQuery code including
following.
Notepad
Visual Studio
Eclipse
Aptana Studio
Ultra edit
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.
<html>
<head>
<script src="~/Scripts/jquery-3.3.1.js"></script>
</head>
<body>
</body>
</html>
ADVERTISEMENT
<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.
<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>
So, in this way, you can download and take a reference of jQuery
library in your web page.
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.
Points to Remember :
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().
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.
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).
//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();
});
Now, you can start interacting with DOM using jQuery safely in the
callback function.
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.
<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)
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.
<div>
<p></p>
<p></p>
</div>
<p></p>
<div></div>
Try it
Select Elements by Id
jQuery Id Selector
Demo
<div id="myDiv1">
<p></p>
</div>
<p id="impPrg"></p>
<div id="myDiv2">
</div>
Try it
ADVERTISEMENT
In the following example, jQuery returns all the elements that have
class or contenteditable attribute irrespective of any value.
j
Query Attribute Selector
<div id="myDiv1">
<p></p>
</div>
<div id="myDiv1">
<p></p>
</div>
Find descendant $('div p') Find all <p> elements which are descendants of <div>
elements
Category Selector Description
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
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 attribute value ends
Category Selector Description
$("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'
jQuery 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
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..
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..
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..
});
</script>
</head>
<body>
<div id="myDiv"></div>
<p></p>
<span></span>
</body>
</html>
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.
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.
Syntax:
$('selector expression').after('content');
<div id="div1">div 1
</div>
<div id="div2">div 2
</div>
Result:
<div id="div1">div 1
</div>
<div id="div2">div 2
</div>
Syntax:
$('selector expression').before('content');
<div id="div1">div 1
</div>
<div id="div2">div 2
</div>
Result:
<div id="div2">div 2
</div>
ADVERTISEMENT
Syntax:
$('selector expression').append('content');
<p>Hello </p>
Result:
<p>Hello World!</p>
Syntax:
$('selector expression').prepend('content');
<div>
<label>This is div.</label>
</div>
Result:
<div>
<p>This is prepended paragraph</p>
<label>This is div.</label>
</div>
Syntax:
$('selector expression').remove();
<div>This is div.
<label>This is label.</label>
</div>
Result:
<div>
This is div.
</div>
Syntax:
$('content string').replaceAll('selector expression');
<div>
<p>This is paragraph.</p>
</div>
Result:
<div>
<span>This is span</span>
</div>
<span>This is span</span>
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>
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).
The following figure shows various jQuery methods to access DOM element's
attributes, properties and values.
jQuery Methods to Access Values
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.
<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.
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.
<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
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.
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.
//removes all the content from #emptyDiv and inserts "This is some
text." to it
$('#emptyDiv').text('This is some text.');
Please note that text() method only returns text content inside the element and not the
innerHtml.
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.
<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.
The following table lists all the jQuery methods to get or set DOM
element's dimensions.
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).
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).
Syntax:
$('selector expression').height(value);
<p>
This is paragraph.
</p>
ADVERTISEMENT
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.
<p>
This is paragraph.
</p>
Syntax:
$('selector expression').offset(options);
<p>
This is paragraph.
</p>
Points to Remember :
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).
Syntax:
$('selector expression').each(callback function);
<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:
Syntax:
$('selector expression').children();
Elements returned from children() method can be iterated using each() method.
<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
Syntax:
$('selector expression').find('selector expression to find child
elements');
<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.
Syntax:
$('selector expression').next();
<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>
Syntax:
$('selector expression').parent();
<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>
Syntax:
$('selector expression').siblings();
<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.
The following table lists jQuery methods for styling and css
manipulation.
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).
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.
Syntax:
$('selector expression').css('style property name','value');
$('selector expression').css({
'style property name':'value',
});
<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>
Syntax:
$('selector expression').addClass('css class name');
<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>
Syntax:
$('selector expression').toggleClass('css class name');
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.
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.
queue() Show or manipulate the queue of functions to be executed on the specified element.
Syntax:
$('selector expression').animate({ stylePropertyName : 'value'},
duration,
easing,
callback);
Apply Animation
In the following example, we are changing height and width of the
element with animation.
ADVERTISEMENT
<div id="msgDiv"></div>
<div id="msgDiv"></div>
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>
ADVERTISEMENT
Syntax:
$('selector expression').fadeIn(speed, easing, callback);
Example: jQuery fadeIn() Method
$('#myDiv').fadeIn(5000, function () {
$('#msgDiv').append('fadeIn() completed.')
});
<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>
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.')
});
Syntax:
$('selector expression').toggle(speed, easing, callback)
Example: jQuery toggle() Method
$('#myDiv').toggle(500, function () {
$('#msgDiv').append('fadeOut completed.')
});
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.
The following table lists all jQuery methods and corresponding DOM
events.
change onchange
focus onfocus
focusin onfocusin
select onselect
submit onsubmit
keypress onkeypress
keyup onkeyup
focusout
dblclick ondblclick
focusout
hover
mousedown onmousedown
Category jQuery Method DOM Event
mouseenter onmouseenter
mouseleave onmouseleave
mousemove onmousemove
mouseout onmouseout
mouseover onmouseover
mouseup onmouseup
Toggle
Resize onresize
Scroll onscroll
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.
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.
ADVERTISEMENT
Hover Events
jQuery provides various methods for mouse hover events e.g.
mouseenter, mouseleave, mousemove, mouseover, mouseout and
mouseup.
$('#myDiv').mouseleave(function (data) {
$(this).css('background-color','red');
});
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 )
$('#myDiv').on('mouseenter', mouseHandler);
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.
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.
Ajax
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.
ajaxError() Register a handler function to be called when Ajax requests complete with an error.
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.
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.
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"
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.
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.
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.
type A type of http request e.g. POST, PUT and GET. Default is GET.
username A username to be used with XMLHttpRequest in response to an HTTP access authentication request.
Let's see how to send http requests using $.ajax() (or jQuery.ajax())
method.
<p></p>
By default ajax() method performs http GET request if option parameter does
not include method option.
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
<p></p>
So this way you can send GET, POST or PUT request using ajax()
method.
Points to Remember :
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.
<p></p>
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.
<p></p>
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.
You can attach fail and done callback methods to getJson() method
as shown below.
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
Thus, you can use different get methods to retrieve different types of
resources using http get request.
Points to Remember :
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.
<p></p>
The following example shows how to submit and retrieve JSON data
using post() method.
You can also attach fail and done callback methods to post() method
as shown below.
Points to Remember :
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.
<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.
<div id="msgDiv"></div>
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>
<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 :
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>
Multiple Ids $("#myDiv1, #myDiv2") Selects multiple elements whose id is myDiv1 or myDiv2.
.class .class $(".myCSSClass1, .myCSSClass2 ") Finds all elements whose class attribute is set
to myCSSClass1 or myCSSClass2
: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='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.
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.
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.
prependTo Insert content at the beginning of the selected element(s). Perform same task as prepend() method, the
only difference is syntax.
replaceWith Replace all target element(s) with specified element and return the set of elements which was removed.
wrapAll Combine all the selected element(s) and wrap them with specified HTML.
CSS Methods
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).
Dimensions Methods
Dimensions Methods Description
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).
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.
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.
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).
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.
map() Pass each element in the current matched set through a function, producing a new jQuery object
containing the return values.
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.
parentsUntil() Selects all the ancestor elements of the matched element(s), up to but not including the element
specified in parentsUntil().
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.
clearQueue() Remove all the animations from the queue that have not been run.
Example: $('#myDiv').clearQueue();
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
Example: $('#myDiv').fadeIn(5000);
Example: $('#myDiv').fadeOut(5000);
Example: $('#myDiv').fadeTo(500);
Method Description
Example: $('#myDiv').fadeToggle(5000);
finish() Stop currently running animation and clear the queue for selected element(s)
Example: $('#myDiv').finish();
Example: $.fx.off;
Example: $('#myDiv').hide(5000);
Example: $('#myDiv').show(5000);
Example: $('#myDiv').stop()
Example: $('#myDiv').toggle(5000);
Example: $('#myDiv').slideUp(5000);
Example: $('#myDiv').slideDown(5000);
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).
hover Attach one or two event handlers to be executed when mouse pointer
enters or leaves selected element(s).
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).