Tejasp

Download as pdf or txt
Download as pdf or txt
You are on page 1of 459

Session-1

Introduction to .NET
and
.NET Framework
Contents
• Introduction to the .Net Framework
• Intermediate Language (IL)
• CLR and its functions
• JIT Compilation
• Garbage Collection and Memory Management
• AppDomain Management
• CLS, CTS
• Security
• Assemblies and their types

By : Dr. Vikrant 2
Introduction to .NET Framework

What is .NET ?
.NET is a developer platform made up of tools, programming
languages, and libraries for building many different types of
applications.

What is .NET Framework?


.NET Framework is the execution and development environment for
.NET applications. It supports running websites, services, desktop apps,
and more on Windows.

By : Dr. Vikrant 3
Introduction to .NET Framework
Architecture of .NET Framework
VB C++ C# JScript …
Common Language Specification

Visual Studio.NET
ASP.NET: Web Services Windows
and Web Forms Forms
ADO.NET: Data and XML
Base Classes
Common Language Runtime

By : Dr. Vikrant 4
Intermediate Language (IL)

By : Dr. Vikrant 5
Intermediate Language (IL)
Two stages of compilation:

1. VB or C# code you write is compiled into an intermediate language


called Microsoft Intermediate Language (MSIL) code, or Common
Intermediate Language (CIL). The compiled file with IL code is an
assembly (.dll or .exe file)
2. IL code is compiled into low-level native machine code. This stage is
known as just-in-time (JIT) compilation

By : Dr. Vikrant 6
Common Language Runtime(CLR)
• The heart of the .NET Framework is the CLR
• It is a runtime environment that executes MSIL code
• CLR is present in every .NET framework version

By : Dr. Vikrant 7
Common Language Runtime(CLR)
JIT Compilation
The .NET CLR utilizes Just In Time (JIT) compilation technology to
convert the IL code back to a platform/device–specific code. Three
types of JIT compilers:
1. Pre-JIT : This JIT compiles an assembly’s entire code into native code at one
stretch. You would normally use this at installation time.
2. Econo-JIT : You would use this JIT on devices with limited resources. It
compiles the IL code bit-by-bit, freeing resources used by the cached native
code when required.
3. Normal JIT : The default JIT compiles code only as it is called and places the
resulting native code in the cache.

By : Dr. Vikrant 8
Common Language Runtime(CLR)
Garbage Collection and Memory Management
• The CLR implements dynamic memory management through the use
of garbage collection. The programmer is responsible for allocating
memory, but it is the CLR that clears up unused memory.
• Code that is run under the garbage collection system is known as
managed code
• However, at times you may want to force the garbage collector to
run, perhaps before starting an operation that is going to require a
large amount of memory. To do this, just call GC.Collect()

By : Dr. Vikrant 9
Common Language Runtime(CLR)
Application Domains (or AppDomain)
• This are like lightweight processes
• An AppDomain, which may contain one or more assemblies, is
completely isolated from any other AppDomains running in the same
process so there’s no sharing of memory or data.
• In fact, the separation is so complete that another AppDomain
running in the same process is treated in exactly the same way as one
residing on another machine

By : Dr. Vikrant 10
Common Language Runtime(CLR)
Common Language Specification (CLS) Language Data types CLR Data type
It is responsible for converting the different
.NET programming language syntactical rules
and regulations into CLR understandable
format. In simple words, CLS enables VB.NET Integer
cross-language integration or Interoperability.
Int32
Common Type System (CTS)
Every programming language has its own data
type system, so CTS is responsible for C# int
understanding all the data type systems of
.NET programming languages and converting
them into CLR understandable format which
will be a common format. Figure : Common Type System

By : Dr. Vikrant 11
Common Language Runtime(CLR)
Security
• Security for .NET applications starts as soon as a class is loaded by the CLR.
• Before the class loader instantiates a class, security information—such as
accessibility rules and self-consistency requirements—are checked.
• Essentially system of security policies that can be set by an administrator to
allow certain levels of access based on the component’s assembly
information. The policies are set at three levels:
• the enterprise
• the individual machine
• the user

By : Dr. Vikrant 12
Assembly
• .NET applications are deployed as assemblies, which can be a single
executable or a collection of components and form a logical unit of
functionality
• Assemblies take the form of executable (.exe) or dynamic link library (.dll)
files, and are the building blocks of .NET applications.
• When you create a .NET application, you are actually creating an assembly,
which contains a manifest that describes the assembly.
• This manifest data contains the assembly name, its versioning information,
any assemblies referenced by this assembly and their versions, a listing of
types in the assembly, security permissions, its product information
(company, trademark, and so on), and any custom attributes

By : Dr. Vikrant 13
Assembly
Types of Assemblies :
1. Private : requires us to copy separately in all application folders
where we want to use that assembly’s functionalities. Without copying,
we cannot access the private assembly features and power. Private
assembly means every time we have one, exclusively copy into the BIN
folder of each application folder.
2. Shared : Only one copy is required in system level, there is no need
to copy the assembly into the application folder. Shared assembly
should install in GAC. Shared assemblies (also called strong named
assemblies) are copied to a single location (usually the Global assembly
cache).
By : Dr. Vikrant 14
Assembly
Types of Assemblies :
3. Satellite : used for deploying language and culture-specific resources
for an application.

By : Dr. Vikrant 15
References
1. https://dotnet.microsoft.com/en-us/learn/dotnet/what-is-dotnet-fr
amework
2. C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development
Fourth Edition by Mark J. Price

By : Dr. Vikrant 16
Session-2

Introduction to Visual Studio


and
.NET technologies
Contents
• Introduction to Visual Studio
• .NET Framework, .NET Code and Xamarin
• Managed and Unmanaged Code
• Using ILDASM utility

By : Dr. Vikrant 2
Introduction to Visual Studio
Microsoft has a family of code editors and Integrated Development
Environments (IDEs), which include:
• Visual Studio Code
• Visual Studio 2019
• Visual Studio 2019 for Mac

By : Dr. Vikrant 3
Introduction to Visual Studio
Visual Studio Code
• The most modern and lightweight code editor and the only one from
Microsoft that is cross-platform
• It is able to run on all common operating systems, including Windows,
macOS, and many varieties of Linux, including Red Hat Enterprise
Linux (RHEL) and Ubuntu.
• It has an extensive and growing set of extensions to support many
languages beyond C#
• Using Visual Studio Code means a developer can use a cross-platform
code editor to develop cross-platform apps.

By : Dr. Vikrant 4
Introduction to Visual Studio
Visual Studio 2019
• Microsoft Visual Studio 2019 only runs on Windows.
• You must run it on Windows 10 to create Universal Windows Platform
(UWP) apps.
• It is the only Microsoft developer tool that can create Windows apps.
Visual Studio 2019 for Mac
To create apps for the Apple operating systems like iOS to run on devices like
iPhone and iPad, you must have Xcode, but that tool only runs on macOS.
• Although you can use Visual Studio 2019 on Windows with its Xamarin
extensions to write a cross-platform mobile app, you still need macOS and
Xcode to compile it.

By : Dr. Vikrant 5
Differences .NET Framework, .NET Core and
Xamarin
.NET Framework
• .NET Framework is a development platform that includes a Common
Language Runtime (CLR), which manages the execution of code, and
a Base Class Library (BCL), which provides a rich library of classes to
build applications.
• All of the apps on a computer written for the .NET Framework share
the same version of the CLR and libraries stored in the Global
Assembly Cache (GAC), which can lead to issues if some of them need
a specific version for compatibility.

By : Dr. Vikrant 6
Differences .NET Framework, .NET Core and
Xamarin
.NET Core
• Today, we live in a truly cross-platform world where modern mobile and
cloud development have made Windows, as an operating system, much
less important.
• Because of that, Microsoft has been working on an effort to decouple .NET
from its close ties with Windows.
• While rewriting .NET Framework to be truly cross-platform, they've taken
the opportunity to refactor and remove major parts that are no longer
considered core.
• This new product was branded .NET Core and includes a cross-platform
implementation of the CLR known as CoreCLR and a streamlined library of
classes known as CoreFX.

By : Dr. Vikrant 7
Differences .NET Framework, .NET Core and
Xamarin
.NET Core
• NET Core is smaller than the current version of .NET Framework due
to the fact that legacy technologies have been removed.
• For example, Windows Forms and Windows Presentation
Foundation (WPF) can be used to build graphical user interface (GUI)
applications, but they are tightly bound to the Windows ecosystem,
so they have been removed from .NET Core on macOS and Linux.
• One of the new features of .NET Core 3.0 is support for running old
Windows Forms and WPF applications using the Windows Desktop
Pack

By : Dr. Vikrant 8
Differences .NET Framework, .NET Core and
Xamarin
.NET Core
• ASP.NET Web Forms and Windows Communication Foundation
(WCF) are old web application and service technologies that fewer
developers are choosing to use for new development projects today,
so they have also been removed from .NET Core.
• Instead, developers prefer to use ASP.NET MVC and ASP.NET Web
API. These two technologies have been refactored and combined into
a new product that runs on .NET Core, named ASP.NET Core.

By : Dr. Vikrant 9
Differences .NET Framework, .NET Core and
Xamarin
Xamarin
• Microsoft purchased Xamarin in 2016 and now gives away what used
to be an expensive Xamarin extension for free with Visual Studio
2019.
• Microsoft renamed the Xamarin Studio development tool, which
could only create mobile apps, to Visual Studio for Mac and gave it
the ability to create other types of apps.

By : Dr. Vikrant 10
Differences .NET Framework, .NET Core and
Xamarin
We can summarize and compare .NET technologies, as shown in the
following table:

Technology Description Host OS


.NET Core for cross-platform and Windows, macOS, Linux
new apps and services
. NET Framework for legacy apps Windows only
Xamarin Mobile apps only. Android, iOS, macOS

By : Dr. Vikrant 11
Managed Code and Unmanaged Code
Managed Code:
• It is executed by managed runtime environment CLR.
• It provides security to the application written in .NET Framework.
• Memory buffer overflow does not occur.
• It provide runtime services like Garbage Collection, exception
handling, etc.
• It also provides reference checking which means it checks whether
the reference point to the valid object or not
• The application is written in the languages like C#, VB.Net, etc. are
always managed code.
By : Dr. Vikrant 12
Managed Code and Unmanaged Code
Unmanaged Code:
• It is executed directly by the operating system.
• It does not provide security to the application.
• In unmanaged code, the memory allocation, type safety, security etc
are managed by the developer. Due to this, there are several
problems related to memory occur like buffer overflow, memory leak
etc.
• It provides the low-level access to the programmer.
• The application written in VB 6.0, C, C++, etc are always in
unmanaged code

By : Dr. Vikrant 13
ILDASM Utility
• The ILDASM (Intermediate Language Disassembler) is an utility which
shows the information of Assembly in human-readable format by
parsing any .NET Framework DLL.
• It also shows the namespaces and types and as well as their
interfaces.
• The advantage of ildasm.exe utility is that it can examine some native
assemblies like such as Mscorlib.dll, as well as .NET Framework
assemblies provided by others or created by yourself.

By : Dr. Vikrant 14
ILDASM Utility
Steps to see the use of ildasm utility in C#:
1. Firstly open the Developer Command Prompt for VS2022 and write
the command like this.

By : Dr. Vikrant 15
ILDASM Utility
2. Then a ildasm window will
open. In it select the File menu
and click on open menu option.

By : Dr. Vikrant 16
ILDASM Utility
3. Then go to the location of the
assembly and select the
assembly to open it.

4. A window will be opened


which shows the information of
the assembly.

By : Dr. Vikrant 17
References
1. C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development
Fourth Edition by Mark J. Price
2. https://www.geeksforgeeks.org

By : Dr. Vikrant 18
Session-3

Introduction to C# Basics
Contents
• Console Applications and Class Libraries (Demo)
• C# Basics
• Data types and CTS equivalents
• Access Specifiers
• Project References, using Classes (Demo)
• Methods
• Method overloading
• Optional parameters
• Named parameters and positional parameters
• Using params
• Properties
• Constructors and Destructors
• Object Initializers
By : Dr. Vikrant 2
C# Basics
What is C#?
•C# (pronounced "C sharp") is a programming language that
is designed for building a variety of applications that run on
the .NET Framework.
• C# is simple, powerful, type-safe(No uninitialized variables,
unsafe casts), and object-oriented.
•The first “Component oriented” language in the C/C++
family
•Everything is an object

By : Dr. Vikrant 3
C# Basics
C# - Programming Structure
•Namespace declaration
•A class or structs or interfaces or enums, or delegates
•Members : Constants, fields, methods, properties,
indexers, events, operators, constructors, destructors
•Statements & Expressions
•Comments

By : Dr. Vikrant 4
C# Basics
C# - Sample Program using System;
namespace HelloWorldApplication
{
class Hello
{
static void Main(string[] args) {

/* my first program in C# */

Console.WriteLine("Hello world");
Console.Read();
}
}
}

By : Dr. Vikrant 5
Data Types and CTS Equivalent
Integer, Float,
Simple Types
Char, Boolean

Enum
Value Type
C# Data Types Struct

Nullable

Class

Interface
Reference Type
Array

Delegate

By : Dr. Vikrant 6
Data Types and CTS Equivalent
Predefined Data Types
Type Description Range .NET Type
byte 8-bit unsigned integer 0 to 255 System.Byte
sbyte 8-bit signed integer -128 to 127 System.SByte

short 16-bit signed integer -32,768 to 32,767 System.Int16


ushort 16-bit unsigned integer 0 to 65,535 System.UInt16

int 32-bit signed integer -2,147,483,648 System.Int32


to
2,147,483,647
uint 32-bit unsigned integer 0 to 4,294,967,295 System.UInt32

By : Dr. Vikrant 7
Data Types and CTS Equivalent
Predefined Data Types
Type Description Range .NET Type
long 64-bit signed integer -9,223,372,036,854,775,808 System.Int64
to
9,223,372,036,854,775,807
ulong 64-bit unsigned integer 0 to System.UInt64
18,446,744,073,709,551,615
float 32-bit Single-precision floating -3.402823e38 to 3.402823e38 System.Single
point type
double 64-bit double-precision floating -1.79769313486232e308 to System.Double
point type 1.79769313486232e308
char 16-bit single Unicode character Any valid character, e.g. a, b, * System.Char

By : Dr. Vikrant 8
Data Types and CTS Equivalent
Predefined Data Types
Type Description Range .NET Type
bool 8-bit logical true/false value True or False System.Boolean
object Base type of all other types. System.Object

string A sequence of Unicode System.String


characters
DateTime Represents date and time 0:00:00am 1/1/01 System.DateTime
to
11:59:59pm 12/31/9999

By : Dr. Vikrant 9
Data Types and CTS Equivalent
⚫ Boxing : Value type is converted to object type, it is called boxing.
Allocates box, copies value into it.
object obj;
obj = 100; // this is boxing
⚫ Unboxing : when an Object type is converted to a value type, it is
called unboxing. Checks type of box, copies value out
int i = 123;
object obj = i; //boxing
int j = (int)obj; //unboxing

By : Dr. Vikrant 10
Access Specifiers
• Encapsulation, in object oriented programming methodology,
prevents access to implementation details.
• Abstraction allows making relevant information visible and
encapsulation enables a programmer to implement the desired level
of abstraction.
• C# supports the following access specifiers:
Public
Private
Protected
Internal
Protected internal

By : Dr. Vikrant 11
Access Specifiers
Internal :
• allows a class to expose its member variables and member
functions to other functions and objects in the current assembly.
• In other words, internal members can be accessed from any class
or method defined within the application in which the member is
defined.
Protected Internal:
The protected internal access specifier allows a class to hide its
member variables and member functions from other class objects
and functions, except a child class within the same application. This
is also used while implementing inheritance.

By : Dr. Vikrant 12
Methods
• Methods are members of a type that execute a block of statements.
• Methods can return a single value or return nothing.
• A method that performs some actions but does not return a value indicates
this with the void type before the name of the method.
• A method that performs some actions and returns a value indicates this with
the type of the return value before the name of the method.

By : Dr. Vikrant 13
Methods
Elements of Method:
• Access Specifier − This determines the visibility of a variable or a method from
another class.
• Return type − A method may return a value. The return type is the data type of
the value the method returns. If the method is not returning any values, then the
return type is void.
• Method name − Method name is a unique identifier and it is case sensitive. It
cannot be same as any other identifier declared in the class.
• Parameter list − Enclosed between parentheses, the parameters are used to pass
and receive data from a method. The parameter list refers to the type, order, and
number of the parameters of a method. Parameters are optional; that is, a
method may contain no parameters.
• Method body − This contains the set of instructions needed to complete the
required activity.

By : Dr. Vikrant 14
Methods
Example of Method:

By : Dr. Vikrant 15
Methods
Method Overloading
• Instead of having two different method names, we could give both
methods the same name. This is allowed because the methods each
have a different signature.
• A method signature is a list of parameter types that can be passed
when calling the method (as well as the type of the return value).

By : Dr. Vikrant 16
Methods
Method Overloading

By : Dr. Vikrant 17
Methods
Method Overloading

By : Dr. Vikrant 18
Methods
Optional Parameters are not compulsory parameters, they are optional.
It helps to exclude arguments for some parameters. Or we can say in
optional parameters, it is not necessary to pass all the parameters in the
method

By : Dr. Vikrant 19
Methods
Optional Parameters

By : Dr. Vikrant 20
Methods
Named and positional parameters
• Generally, while calling the method we need to pass all
the method arguments in the same sequence of parameters in the
method definition.
• If we use named parameters, we don’t need to worry about the order
or sequence of parameters while calling the method.
• In named parameters, the parameter values will map to the right
parameter based on the parameter name. So, while calling
the methods, we can send the parameters in any sequence or order

By : Dr. Vikrant 21
Methods
Named and positional parameters

Sending the
parameters in any
sequence or order

By : Dr. Vikrant 22
Methods
params : It is used as a parameter which can take the variable number
of arguments.
• It is useful when programmer don’t have any prior knowledge about
the number of parameters to be used.
• Only one params keyword is allowed and no additional params will be
allowed in function declaration after a params keyword.
• The length of params will be zero if no arguments will be passed.

By : Dr. Vikrant 23
Methods
params :

By : Dr. Vikrant 24
Properties
• Property in C# is a member of a class that provides a flexible
mechanism for classes to expose private fields.
• Internally, C# properties are special methods called accessors. A C#
property have two accessors,
• get property accessor : returns a property value
• set property accessor : assigns new value
• The value keyword represents the value of a property.
• Properties can be read-write, read-only, or write-only. The read-write
property implements both get and set accessor. A write-only property
implements a set accessor, but no get accessor. A read-only property
implements a get accessor, but no set accessor.

By : Dr. Vikrant 25
Constructors and Destructors
• Constructor is a special method which is invoked automatically at the
time of object creation. It is used to initialize the data members of
new object generally. The constructor in C# has the same name as
class or struct.
• Destructors in C# are methods inside the class used to destroy
instances of that class when they are no longer needed. The
Destructor is called implicitly by the .NET Framework’s Garbage
collector and therefore programmer has no control as when to invoke
the destructor.

By : Dr. Vikrant 26
Constructors and Destructors
• There can be five types of constructors in C#.
• Default Constructor – It has no arguments and It is invoked at the time of
creating object.
• Parameterized Constructor - A constructor which has parameters is called
parameterized constructor.
• Copy Constructor - used to copy one object’s data into another object
• Static Constructor –There is no matter how many numbers instances
(objects) of the class are created, static constructor is going to be invoked
only once and that is when the class is load for the first time. The static
constructor is used to initialize the static fields of the class.
• Private Constructor - When a class contains a private constructor then we
cannot create an object for the class outside of the class. So, private
constructors are used to creating an object for the class within the same
class
By : Dr. Vikrant 27
Object Initializer
In object initializer, you
can initialize the value to
the fields or properties of
a class at the time of
creating object without
calling constructor.

By : Dr. Vikrant 28
References
1. C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development
Fourth Edition by Mark J. Price

By : Dr. Vikrant 29
Session-4

Static keyword and


Inheritance
Contents
• Static members of the class
• Fields/Variables
• Methods
• Properties
• Constructors
• Static Class
• Inheritance
• Access Specifiers
• Constructors in Hierarchy
• Overloading in derived class
• Override
• Sealed class and methods
• Abstract class and methods
By : Dr. Vikrant 2
Static Members
Static variables
•Single copy(instance) of
the variable is created and
shared among multiple
objects.
•Static variables are
accessed with the name of
the class, they do not
require any object for
access.

By : Dr. Vikrant 3
Static Members
Static Methods
• Static methods are
accessed with the name
of the class.
• A static method can
access static and
non-static fields, static
fields are directly
accessed by the static
method without class
name whereas non-static
fields require objects.

By : Dr. Vikrant 4
Static Members
Static Properties
•Similar to static
methods
•Static properties use
the same get and set
tokens as instance
properties

By : Dr. Vikrant 5
Static Members
Static Constructor
• There is no matter how
many numbers instances
(objects) of the class are
created, static
constructor is going to
be invoked only once
and that is when the
class is load for the first
time.
• The static constructor is
used to initialize the
static fields of the class.
By : Dr. Vikrant 6
Static Class
•A static class can only
contain static data
members, static methods,
and a static constructor.
•It is not allowed to create
objects of the static class.
•Static classes are sealed,
means you cannot inherit
a static class from
another class.

By : Dr. Vikrant 7
Inheritance
• It is the mechanism in C# by which one class (child or derived) is
allowed to inherit the features(fields and methods) of another class
(parent or base).
• Inheritance is one of the primary concepts of object-oriented
programming (OOP).
• Inheritance supports the concept of “reusability”, i.e. when we want
to create a new class and there is already a class that includes some
of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of
the existing class.

By : Dr. Vikrant 8
Inheritance

•Types of Inheritance
•Single
•Hierarchical

•Multilevel
•Multiple
• (using interfaces)

By : Dr. Vikrant 9
Inheritance
Access Specifiers
protected private
public protected internal private
internal protected
Entire program Yes No No No No No

Containing class Yes Yes Yes Yes Yes Yes

Current assembly Yes No Yes Yes No No

Derived types Yes Yes No Yes No No


Derived types
within current Yes Yes Yes Yes No Yes
assembly

By : Dr. Vikrant 10
Inheritance
Constructors in Hierarchy :
Two different cases arise as follows:
Case 1: Only derived class contains a constructor. So the objects of the
derived class are instantiated by that constructor and the objects of the
base class are instantiated automatically by the default constructor.
Case 2: In this case, both the base class and derived class has their own
constructors, so the process is complicated because the constructors of
both classes must be executed. To overcome this situation C# provide a
keyword known as a base keyword. With the help of base keyword, the
derived class can call the constructor which is defined in its base class.

By : Dr. Vikrant 11
Inheritance
Overloading
• When the compiler goes looking for instance method overloads, it
considers the compile-time class of the "target" of the call, and looks
at methods declared there.
• If it can't find anything suitable, it then looks at the parent class then
the grandparent class, etc.
• This means that if there are two methods at different levels of the
hierarchy, the "deeper" one will be chosen first

By : Dr. Vikrant 12
Inheritance
Overriding:
• Overriding is a feature that allows a subclass or child class to provide a
specific implementation of a method that is already provided by one
of its super-classes or parent classes.
• When a method in a subclass has the same name, same parameters
or signature and same return type(or sub-type) as a method in its
super-class, then the method in the subclass is said to override the
method in the super-class.
• Method overriding is one of the ways by which C# achieve Run Time
Polymorphism(Dynamic Polymorphism).

By : Dr. Vikrant 13
Inheritance
Overriding:
• The overridden base method must be virtual, abstract, or override.
Parent Class

addNum() Overriden
subNum() Method

inheriting

Child Class

Overriding
addNum() Method
muliplyNum()

By : Dr. Vikrant 14
Inheritance
Overriding:
In C# we can use 2 types of keywords for Method Overriding:
• virtual keyword: This modifier or keyword use within base class
method. It is used to modify a method in base
class for overridden that particular method in the derived class.
• override: This modifier or keyword use with derived class method. It
is used to modify a virtual or abstract method into derived class which
presents in base class.

By : Dr. Vikrant 15
Inheritance
Sealed Class
• Sealed classes are used to restrict the users from inheriting the class.
A class can be sealed by using the sealed keyword.
• No class can be derived from a sealed class.
Sealed Method
• A method can also be sealed, and in that case, the method cannot be
overridden.
• If you want to declare a method as sealed, then it has to be declared
as virtual in its base class.

By : Dr. Vikrant 16
Inheritance
Abstract Class
• An Abstract class is never intended to be instantiated directly.
• This class must contain at least one abstract method, which is marked
by the keyword or modifier abstract in the class definition.
• The Abstract classes are typically used to define a base class in
the class hierarchy
Abstract Method
• A method which is declared abstract, has no “body” and declared
inside the abstract class only.
• An abstract method must be implemented in all non-abstract classes
using the override keyword
By : Dr. Vikrant 17
References
1. C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development
Fourth Edition by Mark J. Price
2. https://www.geeksforgeeks.org

By : Dr. Vikrant 18
Session-5

Interfaces and Operator


Overloading
Contents
• Interfaces
• Implementing interfaces
• Explicitly implementing interfaces
• Inheritance in interfaces
• Default interfaces methods
• IDisposable and IComparable
• Operator Overloading

By : Dr. Vikrant 2
Interface
• It is like abstract class because all the methods which are declared
inside the interface are abstract methods. It cannot have method
body but in C# 8.0 this feature has also been implemented using
Default interface methods.
• They cannot be instantiated.
• It is used to achieve multiple inheritance which can't be achieved
by class. It is used to achieve fully abstraction because it cannot
have method body.
• Its implementation must be provided by class or struct. The class
or struct which implements the interface, must provide the
implementation of all the methods declared inside the interface.

By : Dr. Vikrant 3
Interface
•Interface methods are
public and abstract by
default. You cannot
explicitly use public
and abstract keywords
for an interface
method.

By : Dr. Vikrant 4
Implementing Interface

By : Dr. Vikrant 5
Explicitly Implementing Interface

•Using <InterfaceName>.<MemberName>
•Explicit implementation is useful when class is
implementing multiple interfaces
•It is also useful if interfaces have the same method name
coincidently.
•Do not use public modifier with an explicit
implementation. It will give a compile-time error.

By : Dr. Vikrant 6
Explicitly Implementing Interface

By : Dr. Vikrant 7
Inheritance in Interface
• C# allows the user to inherit one interface into another interface.
• When a class implements the inherited interface then it must provide
the implementation of all the members that are defined within the
interface inheritance chain (i.e including the base interface methods)
Otherwise, the compiler throws an error.
• If both derived interface and base interface declares the same
member then the base interface member name is hidden by the
derived interface member name.

By : Dr. Vikrant 8
Inheritance in Interface

By : Dr. Vikrant 9
Default Interface Methods
• C# 8.0 is allowed to add members as well as their implementation to the
interface.
• Now you are allowed to add a method with their implementation to the
interface without breaking the existing implementation of the interface,
such type of methods is known as default interface methods(also known
as the virtual extension methods).
• You are allowed to implement indexer, property, or event accessor in the
interface.
• You are allowed to use access modifiers like private, protected, internal,
public, virtual, abstract, override, sealed, static, extern with default
methods, properties, etc. in the interface.

By : Dr. Vikrant 10
Default Interface Methods
• You are allowed to create static fields, methods, properties and
events in the interface.
• The explicit access modifiers with default access are public.
• If an interface contains default method and inherited by some
specified class, then the class does not know anything about the
existence of the default methods of that interface and also does not
contain the implementation of the default method.
• You are allowed to use the same name methods in the interface, but
they must have different parameter lists

By : Dr. Vikrant 11
Default Interface Methods

By : Dr. Vikrant 12
IDisposable Interfaces
• When the garbage collector runs it can clean up your managed resources.
The garbage collector does not know how to free unmanaged resources
(such as file handles, network connections and database connections).
• The term "unmanaged resource" is usually used to describe something not
directly under the control of the garbage collector
• The following are two mechanisms to automate the freeing of unmanaged
resources:

1. Declaring a destructor (or Finalizer) as a member of your class.


2. Implementing the System.IDisposable interface in your class.

By : Dr. Vikrant 13
IDisposable Interfaces
• IDisposable is an interface that contains only a single method
i.e. Dispose(), for releasing unmanaged resources.
• IDisposable is defined in the System namespace.
• When your application or class library encapsulates unmanaged resources
such as files, streams, database connections, etc, they should implement
the IDisposable interface
• Inside the Dispose() method we can perform the resources clean-up
• If you are using a class that implements the IDisposable interface, you
should call its Dispose() method when you are finished using the class
by try/finally block or using statement.
• To prevent the dispose method from running twice (in case the object
already has been disposed ) , we add GC.SuppressFinalize(this)

By : Dr. Vikrant 14
IComparable Interface
• Use the IComparable Interface in C# to sort elements. It is also used
to compare the current instance with another object of same type.
• It provides you with a method of comparing two objects of a
particular type. Remember, while implementing the IComparable
interface, CompareTo() method should also be implemented.

By : Dr. Vikrant 15
IComparable Interface

By : Dr. Vikrant 16
Operator Overloading
• Ability to use the same operator to do various operations by
providing special meaning to C# operators.
• It provides additional capabilities to C# operators when they are
applied to user-defined data types.
• It enables to make user-defined implementations of various
operations where one or both of the operands are of a user-defined
class.
• Only the predefined set of C# operators can be overloaded
• An operator can be overloaded by defining a function to it. The
function of the operator is declared by using the operator keyword.
By : Dr. Vikrant 17
Operator Overloading
Operators Description
unary operators take one operand and can be
+, -, !, ~, ++, – –
overloaded.
Binary operators take two operands and can be
+, -, *, /, %
overloaded.
==, != Comparison operators can be overloaded.
Conditional logical operators cannot be overloaded
&&, ||
directly

By : Dr. Vikrant 18
Operator Overloading
Syntax:
Access_specifier Class_Name operator Operator_symbol (parameters)
{
//Code
}
Example : public static Calculator operator + (Calculator obj1,Calculator obj2)
{
Calculator obj3 = new Calculator();
obj3.number = obj2.number + obj1.number;
return obj3;
}
By : Dr. Vikrant 19
Operator Overloading
Overloading ability of the various operators available in C#
• unary operators take one operand and can be overloaded.
• Binary operators take two operands and can be overloaded.
• Comparison operators can be overloaded.
• Conditional logical operators cannot be overloaded
• Assignment operators cannot be overloaded.

By : Dr. Vikrant 20
References
1. C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development
Fourth Edition by Mark J. Price
2. https://www.geeksforgeeks.org

By : Dr. Vikrant 21
Session-6

Reference and Value Types


Contents
• Value Types
• enum
• struct
• Reference Types
• Nullable Types
• ref and out
• Arrays
• Indexers

By : Dr. Vikrant 2
Value Types
•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. x

0x233949

int x = 400; 400

Memory Allocation of Value Type

By : Dr. Vikrant 3
Value Types
enum (enumeration type) :
• It is mainly used to assign the names or string values to integral
constants, that make a program easy to read and maintain
• is defined using enum keyword directly inside namespace, class or
structure
• Enums are lists of constants. When you need a predefined list of
values which do represent some kind of numeric or textual data, you
should use an enum.
• The default type is int, and the approved types are byte, sbyte, short,
ushort, uint, long, and ulong . But enum cannot be a string type.

Example :
enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};

By : Dr. Vikrant 4
Value Types
struct
It helps you to make a single
variable hold related data of
various data types.
The struct keyword is used
for creating a structure.
It can be used to hold small
data values that do not
require inheritance, e.g.
coordinate points, key-value
pairs, and complex data
structure.
By : Dr. Vikrant 5
Value Types
struct
•Structures cannot inherit other structures or classes.
•Structures can have defined constructors, but not destructors.
The default constructor is automatically defined and cannot be
changed. It contain parameterized constructor or static
constructor.
•A structure can implement one or more interfaces.
•Structure members cannot be specified as abstract, virtual, or
protected
•Structures can have methods, fields and properties
By : Dr. Vikrant 6
Reference Types
•Unlike value types, a reference type doesn't store its value
directly. Instead, it stores the address where the value is
being stored.
string str = “Hello”;

0x455566 0x233949

0x233949 Hello

Reference type variables Actual Value


contains address where
the value is stored By : Dr. Vikrant 7
Reference Types
•Null Reference type

Student obj;

0x455566

null

Null Reference type

By : Dr. Vikrant 8
Nullable Types
• The Nullable type allows you to assign a null value to a variable.
• Nullable types can only work with Value Type, not with Reference
Type.

Syntax : Nullable <data_type> variable_name = null;


Or
data_type? variable_name=null;
you can also use a shortcut which includes ? operator with the data
type:
By : Dr. Vikrant 9
Nullable Types
How to access the
value of Nullable type
variables?
You have to
use GetValueOrDefault(
) method to get an
original assigned value
if it is not null. You will
get the default value
zero if it is null.

By : Dr. Vikrant 10
Nullable Types
Use the '??' (Null
Coalescing
Operator) to
assign a nullable
type to a
non-nullable type.

By : Dr. Vikrant 11
Nullable Types
Advantage of Nullable Types:
• The main use of nullable type is in database applications. Suppose, a
table a row fetched null values in application, then you can use
nullable type to get the null values.
• Nullable types can only be used with value types.
• The HasValue property returns true if the variable contains a value, or
false if it is null.

By : Dr. Vikrant 12
ref
The ref keyword passes
arguments to calling
method by reference. But
before calling the method,
the arguments must be
initialized with some
values.

By : Dr. Vikrant 13
out
We need not to initialize
the parameter before
calling the method.
But C# compiler puts a
constraint on the called
method, that parameter
must be initialize within the
method.

By : Dr. Vikrant 14
Arrays
• Array is a collection of variables of the same type stored at
contiguous memory locations.
• Declaring array: datatype[] Arrayname; eg. int[] marks;
• Initializing array : int[] marks=new int[5];
• Assigning values to an array:
• Using index number : marks[0]=56; marks[1]=66;
• At the time of declaration : int[] marks={ 44, 55, 66};
• int[] marks=new int[3] { 44, 55, 66};
• int[] marks=new int[] { 44, 55, 66};

By : Dr. Vikrant 15
Arrays
Accessing Array Elements :

By : Dr. Vikrant 16
Arrays
Accessing Array Elements (using loops)

By : Dr. Vikrant 17
Arrays
Multidimensional
Array
• The
multi-dimensional
array contains more
than one row to
store the values.
• To storing and
accessing the values
of the array, one
required the nested
loop

By : Dr. Vikrant 18
Arrays
Jagged Array
An array whose
elements are arrays is
known as Jagged
arrays it means “array
of arrays“. The jagged
array elements may be
of different
dimensions and sizes.

By : Dr. Vikrant 19
Indexer
Syntax:
• An indexer is a special type of
property that allows a class or <modifier> <return type> this [argument list]
{
a structure to be accessed like get
an array for its internal {
collection. // your get block code
}
• An indexer can be defined the set
same way as property with {
‘this’ keyword and square // your set block code
brackets []. }
}
• Modifiers can be private,
public, protected or internal

By : Dr. Vikrant 20
Indexer

By : Dr. Vikrant 21
References
1. C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development
Fourth Edition by Mark J. Price
2. https://www.geeksforgeeks.org

By : Dr. Vikrant 22
Session-7

Generics and Collections


Contents
• Generics
• Generic classes
• Generic methods
• Generics constraints
• Collections ( generic and non-generic)
• Iterating collections using foreach
• Collections example based on ICollection, IList, IDictionary

By : Dr. Vikrant 2
Generics
•Enables your types to be more safely reusable and more
efficient.
•It means, generics allow you to write a class or method that
can work with any data type.
•Generic has a performance advantage because it removes
the possibilities of boxing and unboxing

By : Dr. Vikrant 3
Generic Class
• A generic class increases
the reusability. The more
type parameters mean
more reusable it becomes.
• A generic class can be a
base class to other generic
or non-generic classes or
abstract classes.
• A generic class can be
derived from other generic
or non-generic interfaces,
classes, or abstract classes.

By : Dr. Vikrant 4
Generics class

By : Dr. Vikrant 5
Non-Generics class

By : Dr. Vikrant 6
Generic Methods
• A method
declared with the
type parameters
for its return type
or parameters is
called a generic
method.

By : Dr. Vikrant 7
Generic Constraints
If we want to restrict
a generic class to
accept only the
particular type of
placeholder, then
we need to
use Constraints

By : Dr. Vikrant 8
Generic Constraints
Constraint Description
where T: struct The type argument must be a value
type.
where T: class The type argument must be a
reference type.
where T: <base class name> The type of argument must be or
derive from the specified base
class.
where T: <interface name> The type argument must be or
implement the specified interface.

By : Dr. Vikrant 9
Generic methods with Constraints

By : Dr. Vikrant 10
Collections (generic and non-generic)
• C# includes specialized classes that store series of values or objects are
called collections.
• Collection classes serve various purposes, such as allocating memory
dynamically to elements and accessing a list of items on the basis of an
index etc.
• There are two types of collections available in C#: non-generic collections
and generic collections.
• System.Collections - namespace contains the non-generic collection types
• System.Collections.Generic - namespace includes generic collection types.

By : Dr. Vikrant 11
Generic Collections
• C# includes the following generic collection classes in the namespace
System.Collections.Generic
Generic Collections Description
List<T> Contains elements of specified type. It grows automatically as you add
elements in it.
Dictionary<TKey,TValue> Contains key-value pairs.
Stores key and value pairs. It automatically adds the elements in ascending
SortedList<TKey,TValue> order of key by default.

Queue<T> Stores the values in FIFO style (First In First Out). It keeps the order in which the
values were added. It provides an Enqueue() method to add values and a
Dequeue() method to retrieve values from the collection.
Stack<T> Stores the values as LIFO (Last In First Out). It provides a Push() method to add
a value and Pop() & Peek() methods to retrieve values.

Hashset<T> Contains non-duplicate elements. It eliminates duplicate elements.


By : Dr. Vikrant 12
Generic Collections
List<T>: Its a collection of
strongly typed objects that
can be accessed by index
and having methods for
sorting, searching, and
modifying list.
It is the generic version of
the ArrayList

Note: foreach is useful for traversing each items in an array or a collection of items and displayed
one by one. By : Dr. Vikrant 13
Generic Collections
Dictionary<Tkey,Tvalue>:
• Stores key-value pairs in no
particular order.
• Implements IDictionary<TK
ey, TValue> interface.
• Keys must be unique and
cannot be null.
• Values can be null or
duplicate
• Elements are stored
as KeyValuePair<TKey,
TValue> objects.

By : Dr. Vikrant 14
Non-generic Collections
C# includes the following non-generic collection classes in the
namespace System.Collections
Non-generic Collections Usage
ArrayList Stores objects of any type like an array. However, there is no need to specify the size
of the ArrayList like with an array as it grows automatically.
SortedList Stores key and value pairs. It automatically arranges elements in ascending order of
key by default. C# includes both, generic and non-generic SortedList collection.
Stack Stores the values in LIFO style (Last In First Out). It provides a Push() method to add
a value and Pop() & Peek() methods to retrieve values. C# includes both, generic and
non-generic Stack.
Queue Stores the values in FIFO style (First In First Out). It keeps the order in which the
values were added. It provides an Enqueue() method to add values and a Dequeue()
method to retrieve values from the collection. C# includes generic and non-generic
Queue.
Hashtable Stores key and value pairs. It retrieves the values by comparing the hash value of the
keys.
By : Dr. Vikrant 15
Non-Generic Collections
ArrayList:
• Its a non-generic collection of
objects whose size increases
dynamically.
• It is the same as Array except
that its size increases
dynamically.
• can be used to add unknown
data where you don't know
the types and the size of the
data.

By : Dr. Vikrant 16
Non-Generic Collections
Hashtable
• is a non-generic collection that
stores key-value pairs, similar to
generic Dictionary<TKey,
TValue> collection
• Implements IDictionary interfac
e.
• Keys must be unique and cannot
be null.
• Values can be null or duplicate.
• Elements are stored as
DictionaryEntry objects.

By : Dr. Vikrant 17
ICollection
• The ICollection interface is inherited from the IEnumerable interface
• In the IEnumerable interface we don't know how many elements
there are in the collection whereas the ICollection interface gives us
this extra property for getting the count of items in the collection
• The ICollection interface contains the following
• Count Property – for maintaining count of elements in the list
• IsSynchronized and SyncRoot Property – to make collection thread-safe
• CopyTo Method - copies the entire collection into an array

By : Dr. Vikrant 18
Collections example using ICollection

By : Dr. Vikrant 19
IList
• The IList interface implements both ICollection The IList interface contains
and IEnumerable interfaces. the following:

• This interface allows us to add items to and 1.IsFixedSize Property


remove items from the collection. 2.IsReadOnly Property
3.Indexer
• It also provides support for accessing the items 4.Add Method
from the index. This interface has more power 5.Clear Method
than the preceding two interfaces. 6.Contains Method
7.Indexof Method
• The IList interface has one indexer by which we 8.Insert Method
can access any element by its position and can 9.Remove Method
insert an element and remove an element at 10.RemoveAt Method
any position.
By : Dr. Vikrant 20
Collections example using IList

By : Dr. Vikrant 21
IDictionary
• IDictionary Interface belongs to the collection module where we can
access the elements by keys or we can say that the IDictionary
interface is a collection of key/value pairs.
• It is available for both generic and non-generic types collection.
• Here each pair must contain a unique key and the value does not
have to be null or can be null.
• Implements ICollection and IEnumerable

By : Dr. Vikrant 22
Collections example using IDictionary

By : Dr. Vikrant 23
References
1. C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development
Fourth Edition by Mark J. Price
2. https://www.geeksforgeeks.org

By : Dr. Vikrant 24
Session-8

Delegates
Contents
• Delegates
• Calling methods using delegates
• Uses of delegates
• Multicast delegates
• Action, func, Predicate delegates
• Anonymous methods
• Lambdas

By : Dr. Vikrant 2
Delegates
•Contains the memory address of methods that matches the
same signature as the delegate so that it can be called
safely with the correct parameter types
•The delegate is a reference type data type
•A delegate can be declared outside of the class or inside the
class. Practically, it should be declared out of the class.
•Steps while working with delegates:
• Declare a delegate
• Set a target method
• Invoke a delegate

By : Dr. Vikrant 3
Delegates

By : Dr. Vikrant 4
Uses of Delegates
• Delegates are reference type but instead of referencing objects
it reference methods.
• Delegates have no method body.
• Delegates are type-safe, object-oriented and secure.
• A Delegate is a function pointer that allows you to reference a
method.
• A Function that is added to delegates must have same return
type and same signature as delegate.

By : Dr. Vikrant 5
Multicast Delegates
• A delegate that points multiple methods is called a multicast delegate
• It helps the user to point more than one method in a single call.
• Delegates are combined and when you call a delegate then a complete list
of methods is called.
• All methods are called in First in First Out(FIFO) order.
• ‘+’ or ‘+=’ Operator is used to add the methods to delegates.
• ‘–’ or ‘-=’ Operator is used to remove the methods from the delegates list.

Note: Remember, multicasting of delegate should have a return type of void


otherwise it will return the value only from the last method added in the
multicast.

By : Dr. Vikrant 6
Multicast Delegates

By : Dr. Vikrant 7
Func Delegate
• Func is a generic delegate included in the System namespace.
• It has zero or more input parameters and one out parameter. The last
parameter is considered as an out parameter.
• A Func delegate type can include 0 to 16 input parameters of different
types. However, it must include an out parameter for the result.
• Func is built-in delegate type.
• Func delegate type must return a value.
• Func delegate does not allow ref and out parameters
• Func delegate type can be used with an anonymous method or lambda
expression.

By : Dr. Vikrant 8
Func Delegate

By : Dr. Vikrant 9
Action Delegate
• Action is a delegate type
defined in the System
namespace.
• An Action type delegate is
the same as Func
delegate except that the
Action delegate doesn't
return a value. In other
words, an Action delegate
can be used with a method
that has a void return type.
• An Action delegate can take
up to 16 input parameters of
different types.

By : Dr. Vikrant 10
Predicate Delegate
• It represents a method containing a set of criteria and checks
whether the passed parameter meets those criteria.
• A predicate delegate methods must take one input parameter and
return a boolean - true or false.
• Predicate delegate is defined in the System namespace.

By : Dr. Vikrant 11
Predicate Delegate

By : Dr. Vikrant 12
Anonymous Method
• As the name suggests,
an anonymous method
is a method without a
name.
• Anonymous methods
in C# can be defined
using the delegate
keyword and can be
assigned to a variable
of delegate type
• Anonymous method
can be passed as a
parameter.

By : Dr. Vikrant 13
Anonymous Method as parameter

By : Dr. Vikrant 14
Lambda
• A lambda expression in C# describes a pattern.
• Lambda Expressions has the token => in an expression context. This is read
as “goes to” operator and used when a lambda expression is declared.
• Lambda expression is a better way to represent an anonymous method.
• Both anonymous methods and Lambda expressions allow you define the
method implementation inline, however, an anonymous method explicitly
requires you to define the parameter types and the return type for a
method
• Syntax :
Parameter => expression eg. sum=> sum+3;
Parameter-list => expression eg. (a, b) => a * b;

By : Dr. Vikrant 15
Lambda

By : Dr. Vikrant 16
References
1. C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development
Fourth Edition by Mark J. Price
2. https://www.geeksforgeeks.org

By : Dr. Vikrant 17
Session-9

Exception Handling
Contents
• Exceptions
• Checked and Unchecked
• Exception Hierarchy and classes
• Exception handling
• Try-catch-finally
• Do’s and Don’ts of Exception Handling
• User-defined Exception classes
• Events
• Declaring and raising the events

By : Dr. Vikrant 2
Exceptions
• An exception is an abnormal condition that arises in a code
sequence at run time.
• In other words, an exception is a run-time error
• When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the
error

By : Dr. Vikrant 3
Checked and Unchecked
• To handle integral type
exceptions in C#, the checked
and unchecked keywords are
used.
• They thus define the checked
context where arithmetic
overflow raises an exception
and the unchecked context
where the arithmetic overflow
is ignored and the result is
truncate

By : Dr. Vikrant 4
Checked and Unchecked
Checked
To check the overflow
explicitly, the checked
keyword is used in C#.
It also checks the
conversion of the
integral type values at
compile time

By : Dr. Vikrant 5
Checked and Unchecked
Unchecked
The integral-type
arithmetic exceptions
are ignored by the C#
Unchecked keyword.
It may thus produce a
truncated or wrong
result, as it does not
check explicitly.
Output:

By : Dr. Vikrant 6
Exception Hierarchy
• Object
• Exception
• SystemException
• IndexOutOfRangeException

• NullReferenceException

• InvalidCastException

• OutOfMemoryException

• ArgumentException
• ArgumentNullException

• ArgumentOutOfRangeException

• ArithmeticException
• DivideByZeroException

• OverflowException

• FormatException

• ApplicationException

By : Dr. Vikrant 7
Exception classes
Exception Class Description
ArgumentException Raised when a non-null argument that is passed to a method is
invalid.
ArgumentNullException Raised when null argument is passed to a method.
ArgumentOutOfRangeException Raised when the value of an argument is outside the range of
valid values.
DivideByZeroException Raised when an integer value is divide by zero.
FileNotFoundException Raised when a physical file does not exist at the specified
location.
FormatException Raised when a value is not in an appropriate format to be
converted from a string by a conversion method such as Parse.
IndexOutOfRangeException Raised when an array index is outside the lower or upper bounds of an
array or collection.

By : Dr. Vikrant 8
Exception classes
Exception Class Description
Raised when program access members of null object.
NullReferenceExceptio
n
OverflowException Raised when an arithmetic, casting, or conversion operation
results in an overflow.
Raised when a program does not get enough memory to
OutOfMemoryExceptio execute the code.
n
Raised when a stack in memory overflows.
StackOverflowExcepti
on
InvalidCastException Handles errors generated during typecasting.

By : Dr. Vikrant 9
Exception handling
(key definitions)
Used to define a try block. This block holds the code
try
that may throw an exception.
Used to define a catch block. This block catches the
catch
exception thrown by the try block.

The finally block is used to execute a given set of


statements, whether an exception is thrown or not
finally
thrown. For example, if you open a file, it must be
closed whether an exception is raised or not.

throw Used to throw an exception manually.


By : Dr. Vikrant 10
Exception handling

Assuming a block raises an


exception, a method catches
an exception using a
combination of the try and
catch keywords.
A try/catch block is placed
around the code that might
generate an exception.

By : Dr. Vikrant 11
Exception Handling

By : Dr. Vikrant 12
Exception Handling

By : Dr. Vikrant 13
Do’s and Don’t of Exception Handling
Do’s
• Use try/catch/finally blocks to recover from errors or release resources
• Throw exceptions instead of returning an error code
• Use the predefined .NET exception types
• End exception class names with the word “Exception”
• Include three constructors in custom exception classes
• Exception(), which uses default values.
• Exception(String), which accepts a string message.
• Exception(String, Exception), which accepts a string message and an inner
exception.

By : Dr. Vikrant 14
Do’s and Don’t of Exception Handling
Don’t
• Don’t throw an exception when a simple if statement can be used to
check for errors. For example, a simple if statement to check whether
a connection is closed is much better than throwing an exception for
the same.
• Don’t catch Exception. Always use the most specific exception for the
code you are writing. Remember good code is not code that doesn’t
throw exceptions. Good code throws exceptions as needed and
handles only the exceptions it knows how to handle.
• Don’t swallow an exception by putting an empty catch block

By : Dr. Vikrant 15
User-Defined Exception Classes
• Define your own exception. User-defined exception classes are derived
from the Exception class.

By : Dr. Vikrant 16
Events
• Events are user actions such as key press, clicks, mouse movements,
etc., or some occurrence such as system generated notifications.
Applications need to respond to events when they occur
• The class that sends or raises an event is called a Publisher and class
that receives or handle the event is called "Subscriber".
• A publisher is an object that contains the definition of the event and
the delegate. A publisher class object invokes the event and it is
notified to other objects.
• A subscriber is an object that accepts the event and provides an
event handler. The delegate in the publisher class invokes the
method (event handler) of the subscriber class.
By : Dr. Vikrant 17
Events
Declaring and Raise Events
To declare an event inside a class, first of all, you must declare a
delegate type for the event as:
public delegate string MyDelegate(string str);
then, declare the event using the event keyword −
event MyDelegate MyEvent;
then, raise the event using the invoke
MyEvent.invoke(“India”);

By : Dr. Vikrant 18
Events

By : Dr. Vikrant 19
Exercise
Write a C# code that simply adds two numbers. Only condition is if the
sum of number is odd it fires an event that print a message using
delegates.

By : Dr. Vikrant 20
References
1. C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development
Fourth Edition by Mark J. Price
2. https://www.geeksforgeeks.org

By : Dr. Vikrant 21
Session-10

Partial Classes and LINQ


Contents
• Anonymous types
• Extension methods
• Partial classes
• Partial methods
• LINQ
• Writing LINQ queries
• LINQ to objects
• Deferred execution
• PLINQ

By : Dr. Vikrant 2
Anonymous Types
• Anonymous type is a type without any name that can contain public
read-only properties only. It cannot contain other members, such as
fields, methods, events, etc.
• You create an anonymous type using the new operator. The implicitly
typed variable- var is used to hold the reference of anonymous types.
• The properties of anonymous types are read-only and cannot be
initialized with a null, anonymous function.

By : Dr. Vikrant 3
Anonymous Types

By : Dr. Vikrant 4
Extension Methods
• Extension method concept allows
you to add new methods in the
existing class or in the structure
without modifying the source code
of the original type
• You need to create a new class
which is static and contain lets say
two methods which you want to
add in the existing class, now bind
this class with the existing class.
• After binding you will see the
existing class can access the two
new added methods

By : Dr. Vikrant 5
Extension Methods

By : Dr. Vikrant 6
Partial Class
• Its is possible to split the implementation of a class, a struct, a
method, or an interface in multiple (.cs) files using the partial
keyword.
• The compiler will combine all the implementation from multiple (.cs)
files when the program is compiled

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

By : Dr. Vikrant 8
Partial Class

By : Dr. Vikrant 9
Partial Method
C# contains a special method is known as a partial method, which
contains declaration part in one partial class and definition part in
another partial class

By : Dr. Vikrant 10
Partial Method

By : Dr. Vikrant 11
LINQ
• LINQ is a Language Integrated Query.
• LINQ provides the new way to manipulate the data, whether it is to or
from the database or with an XML file or with a simple list of dynamic
data.
• LINQ is a uniform query system in C# to retrieve the data from
different sources of data and formats such as XML, generics,
collections, ADO.Net DataSet, Web Service, MS SQL Server, and other
databases server.
• LINQ provides the rich, standardized query syntax in a .NET
programming language such as C# and VB.NET, which allows the
developers to interact with any data sources.
By : Dr. Vikrant 12
LINQ

By : Dr. Vikrant 13
LINQ
Advantages of LINQ
• We do not need to learn new query language syntaxes for different sources
of data because it provides the standard query syntax for the various data
sources.
• In LINQ, we have to write the Less code in comparison to the traditional
approach.
• LINQ provides the compile-time error checking as well as intelligence
support in Visual Studio. This powerful feature helps us to avoid run-time
errors.
• LINQ provides a lot of built-in methods that we can be used to perform the
different operations such as filtering, ordering, grouping, etc. which makes
our work easy.
• The query of LINQ can be reused.

By : Dr. Vikrant 14
LINQ
Writing LINQ Query:
• LINQ queries return results as objects. It enables you to uses
object-oriented approach on the result set and not to worry about
transforming different formats of results into objects.
• Each Query is a combination of three things; they are:
1. Initialization(to work with a particular data source)
2. Condition(where, filter, sorting condition)
3. Selection (single selection, group selection or joining)
• There are two basic ways to write a LINQ query to IEnumerable collection
data source.
1. Using Query Syntax
2. Using Method Syntax

By : Dr. Vikrant 15
LINQ
Writing LINQ Query:
1. Using Query Syntax

Example :

By : Dr. Vikrant 16
Example -1

LINQ
Writing LINQ Query:
1. Using Query Syntax

By : Dr. Vikrant 17
Example -2

LINQ
Writing LINQ Query:
1. Using Query Syntax

By : Dr. Vikrant 18
LINQ
Points to Remember (FOR QUERY SYNTAX)
• As name suggest, Query Syntax is same like SQL (Structure Query
Language) syntax.
• Query Syntax starts with from clause and can be end
with Select or GroupBy clause.
• Use various other opertors like filtering, joining, grouping, sorting
operators to construct the desired result.
• Implicitly typed variable - var can be used to hold the result of the
LINQ query.

By : Dr. Vikrant 19
LINQ
Writing LINQ Query:
2. Using Method Syntax
• Method syntax uses extension methods included in
the Enumerable or Queryable static class, similar to how you would call the
extension method of any class.
• The extension method Where() is defined in the Enumerable class.

Example :

By : Dr. Vikrant 20
Example -1

LINQ
Writing LINQ Query:
2. Using Method Syntax

By : Dr. Vikrant 21
LINQ to Object
• LINQ to Objects offers usage of any LINQ query supporting
IEnumerable<T> for accessing in-memory data collections without
any need of LINQ provider (API) as in case of LINQ to SQL or LINQ to
XML.
• Queries in LINQ to Objects return variables of type usually
IEnumerable<T> only
• There are also many advantages of LINQ to Objects over traditional
foreach loops like more readability, powerful filtering, capability of
grouping, enhanced ordering with minimal application coding.

By : Dr. Vikrant 22
LINQ to Object

By : Dr. Vikrant 23
Deferred Execution
• In Deferred Execution, the query is not executed when declared. It is
executed when the query object is iterated over a loop.
• Deferred execution is applicable on any in-memory collection as well
as remote LINQ providers like LINQ-to-SQL, LINQ-to-Entities,
LINQ-to-XML, etc.
• Deferred Execution returns the Latest Data

By : Dr. Vikrant 24
Deferred Execution
In this example, you can see the query is
materialized and executed when you iterate using
the foreach loop. This is called deferred execution

By : Dr. Vikrant 25
PLINQ (Parallel LINQ)
• Parallel LINQ (PLINQ) is a parallel implementation of LINQ to Objects.
• PLINQ supports Parallel programming and is closely related to the
Task Parallel Library.
• In very simple words, PLINQ enables a query to automatically take
advantage of multiple processors.
• PLINQ can significantly increase the speed of LINQ to Objects queries
by using all available cores on the host computer more efficiently.
Sequential Linq execution Parallel Linq execution

By : Dr. Vikrant 26
References
1. C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development
Fourth Edition by Mark J. Price
2. https://www.geeksforgeeks.org
3. https://www.tutorialsteacher.com/linq

By : Dr. Vikrant 27
Session-11

Reflection and File IO


Contents
• Creating Shared Assembly
• Creating Custom Attributes
• Reflection
• Dynamic Assembly Loading using Reflection
• Files IO and Streams
• Reading and Writing files
• Working with Drives, Directories and Files

By : Dr. Vikrant 2
Creating Shared Assembly
• A shared assembly is an assembly that resides in a centralized
location known as the GAC (Global Assembly Cache) and that
provides resources to multiple applications.
• If an assembly is shared then single copy can be used by multiple
applications.
• The GAC folder is under the Windows folder.

By : Dr. Vikrant 3
Steps to create and use Shared Assembly
Step 1 : Open VS.NET and Create a new Class Library
Step 2: Generating Cryptographic Key Pair using the tool SN.Exe
• Make sure that you start Administrator “Developer Command Prompt for VS 2022”
• Write the following command on command prompt

C:\> sn -k "C:\mynewkey.snk“
Step 3: Sign the component with the key and build the class library
project (Go to properties of the project in solution explorer -> select
signing -> Check the checkbox of Sign the assembly and browse for the
key).
Step 4: Host the signed assembly in Global Assembly Cache
C:\>gacutil -i "E:\MyClassLibrary\bin\Debug\MyClassLibrary.dll"

By : Dr. Vikrant 4
Steps to create Shared Assembly
Step 5 : Test the assembly by creating the client application. Just add
the project reference and browse for the shared assembly recently
created.
Step 6 : Execute the client program

By : Dr. Vikrant 5
Creating Custom Attributes
• Custom attributes are essentially traditional classes that derive
directly or indirectly from System.Attribute
• Attributes are metadata extensions that give additional information
to the compiler about the elements in the program code at runtime.
• Attributes are used to impose conditions or to increase the efficiency
of a piece of code
• The primary steps to properly design custom attribute classes :
a. Applying the AttributeUsageAttribute
b. Declaring the attribute class
c. Declaring constructors
d. Declaring properties
By : Dr. Vikrant 6
Custom Attributes
Applying the AttributeUsageAttribute :
A custom attribute declaration begins with
the System.AttributeUsageAttribute, which defines some of the key
characteristics of your attribute class. For example, you can specify whether
your attribute can be inherited by other classes or specify which elements the
attribute can be applied to.

[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]

The AttributeUsageAttribute has three members that are important for the
creation of custom attributes: AttributeTargets, Inherited, and AllowMultiple.

By : Dr. Vikrant 7
Custom Attributes
Applying the AttributeUsageAttribute :
AttributeTargets.All is specified, indicating that this attribute can be applied to
all program elements.
AttributeTargets.Class, indicating that your attribute can be applied only to a
class
AttributeTargets.Method, indicating that your attribute can be applied only to
a method.

By : Dr. Vikrant 8
Custom Attributes
Applying the AttributeUsageAttribute :
AttributeUsageAttribute.Inherited property indicates whether your attribute can be
inherited by classes that are derived from the classes to which your attribute is applied.

// This defaults to Inherited = true. //The two attributes are then applied to a method in the
public class MyAttribute : Attribute base class
{ public class MyClass
//... {
} [MyAttribute]
[YourAttribute]
[AttributeUsage(AttributeTargets.Method, Inherited = public virtual void MyMethod()
false)] {
public class YourAttribute : Attribute //...
{ }
//... }
By : Dr. Vikrant 9
}
Custom Attributes
Applying the AttributeUsageAttribute :
Finally, the class YourClass is inherited from the base class MyClass. The
method MyMethod shows MyAttribute but not YourAttribute
public class YourClass : MyClass
{
// MyMethod will have MyAttribute but not YourAttribute.
public override void MyMethod()
{
//...
}
}

By : Dr. Vikrant 10
Custom Attributes public class MyClass
Applying the AttributeUsageAttribute : {
AttributeUsageAttribute.AllowMultiple property // This produces an error.
// Duplicates are not allowed.
indicates whether multiple instances of your [MyAttribute]
attribute can exist on an element. If set to true, [MyAttribute]
multiple instances are allowed; if set to false( public void MyMethod()
default), only one instance is allowed. {
//...
//This defaults to AllowMultiple = false. }
public class MyAttribute : Attribute
{ // This is valid.
} [YourAttribute]
[YourAttribute]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = public void YourMethod()
true)] {
public class YourAttribute : Attribute //...
{ }
} }

By : Dr. Vikrant 11
Custom Attributes
Declaring the Attribute class :

[AttributeUsage(AttributeTargets.Method)]
public class MyAttribute : Attribute
{
// . . .
}

By : Dr. Vikrant 12
Custom Attributes
Declaring Constructor:

public MyAttribute(bool myvalue)


{
this.myvalue = myvalue;
}

By : Dr. Vikrant 13
Custom Attributes
Declaring Properties

public bool MyProperty


{
get {return this.myvalue;}
set {this.myvalue = value;}
}

By : Dr. Vikrant 14
Reflection
• Reflection objects are used for obtaining type information at
runtime. The classes that give access to the metadata of a running
program are in the System.Reflection namespace.
• Reflection has the following applications :
• It allows view attribute information at runtime.
• It allows examining various types in an assembly and instantiate these types.
• It allows late binding to methods and properties
• It allows creating new types at runtime and then performs some tasks using
those types.

By : Dr. Vikrant 15
Reflection
• The MemberInfo object of the System.Reflection class needs to be
initialized for discovering the attributes associated with a class.

System.Reflection.MemberInfo info = typeof(MyClass);

By : Dr. Vikrant 16
Reflection

By : Dr. Vikrant 17
Dynamic Assembly Loading using Reflection
the act of loading external assemblies on demand is known as Dynamic
Loading. Using the Assembly class, we can dynamically load both private and
shared assemblies from the local location to a remote location as well as,
explore its properties.

By : Dr. Vikrant 18
Files IO and Streams
Files
• A file is a collection of data stored in a disk with a specific name and a
directory path.
• System.IO namespace has various classes that are used for
performing numerous operations with files, such as creating and
deleting files, reading from or writing to a file, closing a file etc.

By : Dr. Vikrant 19
Files IO and Streams
Basic file operations :
• Reading –data is read from a file.
• Writing –data is written to a file. By default, all existing contents are
removed from the file, and new content is written.
• Appending – writing information to a file. The only difference is that
the existing data in a file is not overwritten. The new data to be
written is added at the end of the file.

By : Dr. Vikrant 20
Files { Reading text files}

By : Dr. Vikrant 21
Files { Reading text files}

By : Dr. Vikrant 22
Exercise
1. Write a C# code to copy the content of one file to another (hint :
use File.Copy method )

2. Write a C# code to delete the existing file. (hint: use File.Delete


method)

By : Dr. Vikrant 23
Files { Writing into text files}

By : Dr. Vikrant 24
Files { Writing into text files}

By : Dr. Vikrant 25
Exercise
1. Try to append the contents in the existing file (hint : use
File.AppendAllText or File.AppendAllLines)

By : Dr. Vikrant 26
Stream
• The stream is basically the sequence of bytes passing through the
communication path.
• There are two main streams: the input stream and the output
stream. The input stream is used for reading data from file (read
operation) and the output stream is used for writing into the file
(write operation).

By : Dr. Vikrant 27
Stream
Methods Description
StreamWriter Class
Closes the current StreamWriter object
The StreamWriter class Close()
and stream associate with it.
implements TextWriter
for writing character to Flush()
Clears all the data from the buffer and
stream in a particular write it in the stream associate with it.

format. Write data to the stream. It has different


Write() overloads for different data types to write
in stream.
It is same as Write() but it adds the
WriteLine()
newline character at the

By : Dr. Vikrant 28
Stream { using StreamWriter}

By : Dr. Vikrant 29
Stream
Methods Description

StreamReader Class Close()


Closes the current StreamReader object
and stream associate with it.
The StreamReader class
implements TextReader Peek()
Returns the next available character but
for reading character does not consume it.

from the stream in a Reads the next character in input stream


particular format Read() and increment characters position by one
in the stream
Reads a line from the input stream and
ReadLine()
return the data in form of string
It is use to read/write at the specific
Seek()
location from a file

By : Dr. Vikrant 30
Stream { using StreamReader}

By : Dr. Vikrant 31
Working with Directories and Drives
Directory class
Directory class in the .NET
Framework class library
provides static methods for
creating, copying, moving,
and deleting directories
and subdirectories. Before
you can use the Directory
class, you must import the
System.IO namespace.

By : Dr. Vikrant 32
Exercise
1. Check the directory exists or not and then delete it. (use delete
method)
2. Move an existing directory to a new specified directory with full
path. (use move method)

By : Dr. Vikrant 33
Working with Directories and Drives
GetLogicalDrives
method returns all
the logical drives on a
system.

By : Dr. Vikrant 34
References
1. C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development
Fourth Edition by Mark J. Price
2. https://www.geeksforgeeks.org

By : Dr. Vikrant 35
Session-12

Threading and Task


Contents
• Process
• Threading
• ThreadStart, Parameterized ThreadStart
• Synchronizing critical data using lock and Monitor
• Working with Tasks
• Calling functions with and without return values
• Using async and await

By : Dr. Vikrant 2
Process
• Windows operating system is an example of multitasking because it is
capable of running more than one process at a time like running
Google Chrome, Word , VLC player, etc. at the same time.
• The operating system uses a term known as a process to execute all
these applications at the same time.
• A process is a part of an operating system that is responsible for
executing an application.

By : Dr. Vikrant 3
Threads
Threads are programs line of execution or smallest unit of processing
that can be scheduled by an operating system
Process v/s Thread
• Process is heavyweight component whereas thread is lightweight. A
thread can be termed as lightweight sub-process because it is
executed inside a process.
• Whenever you create a process, a separate memory area is
occupied. But threads share a common memory area.
• Process are independent but threads may dependent on each other
• Process require more time for creation/termination as compare to
threads
By : Dr. Vikrant 4
Thread life cycle
• The life cycle of a thread is started when instance
of System.Threading.Thread class is created. When the task execution
of the thread is completed, its life cycle is ended.
• Following states in the life cycle of a Thread:
• Unstarted - When the instance of Thread class is created
• Runnable (Ready to run) - When start() method on the thread is called
• Running - Only one thread within a process can be executed at a time
• Not Runnable - if sleep() or wait() method is called on the thread, or
input/output operation is blocked
• Dead (Terminated) - After completing the task, thread enters into dead or
terminated state.

By : Dr. Vikrant 5
Thread class Property Description
CurrentThread returns the instance of currently running
thread.
• Thread class IsAlive checks whether the current thread is alive or
provides properties not. It is used to find the execution status of
and methods to the thread.
create and control IsBackground is used to get or set value whether current
threads. thread is in background or not.
Name is used to get or set the name of the current
• It is found in thread.
System.Threading Priority is used to get or set the priority of the current
namespace. thread.(by default its Normal-2)
ThreadState is used to return a value representing the
thread state.

By : Dr. Vikrant 6
Thread class

Methods Description
Abort() is used to terminate the thread. It raises ThreadAbortException.

Join() is used to block all the calling threads until this thread terminates.

Resume() is used to resume the suspended thread. It is obselete.

Sleep(Int32) is used to suspend the current thread for the specified milliseconds.

Start() changes the current state of the thread to Runnable.

Suspend() suspends the current thread if it is not suspended. It is obselete.

Yield() is used to yield the execution of current thread to another thread.

By : Dr. Vikrant 7
Types of Thread
Foreground Thread
• A thread which keeps on running to complete its work even if
the Main thread leaves its process, this type of thread is known as
foreground thread.
• Foreground thread does not care whether the main thread is alive or
not, it completes only when it finishes its assigned work Or in other
words, the life of the foreground thread does not depend upon the
main thread.

By : Dr. Vikrant 8
Types of Thread
Foreground Thread

By : Dr. Vikrant 9
Types of Thread
Background Thread
• A thread which leaves its process when the Main method leaves its
process, these types of the thread are known as the background
threads.
• The life of the background thread depends upon the life of the main
thread. If the main thread finishes its process, then background
thread also ends its process.

By : Dr. Vikrant 10
Types of Thread
Background Thread

By : Dr. Vikrant 11
ParameterizedThreadStart
• Thread(ParameterizedThreadStart) Constructor is used to initialize a
new instance of the Thread class.
• It defines a delegate which allows an object to pass to the thread
when the thread starts.
• This constructor gives ArgumentNullException if the parameter of this
constructor is null.

By : Dr. Vikrant 12
ParameterizedThreadStart

By : Dr. Vikrant 13
ThreadStart
• ThreadStart is a delegate which represents a method to be invoked
when this thread begins executing.
• Thread(ThreadStart) Constructor is used to initialize a new instance
of a Thread class. This constructor will give ArgumentNullException if
the value of the parameter is null.
• Syntax :
public Thread(ThreadStart start);

By : Dr. Vikrant 14
ThreadStart

By : Dr. Vikrant 15
Thread Synchronization
• Synchronization is a
technique that allows only
one thread to access the
resource for the particular
time. No other thread can
interrupt until the
assigned thread finishes
its task.
• Advantages:
• Consistency Maintain
• No Thread Interference
Money withdraw from the same bank account at the same time

By : Dr. Vikrant 16
Thread Synchronization
Synchronizing critical data using lock :
• lock keyword to execute program synchronously. It is used to get lock
for the current thread, execute the task and then release the lock.
• It ensures that other thread does not interrupt the execution until the
execution finish

By : Dr. Vikrant 17
Synchronizing critical data using lock

By : Dr. Vikrant 18
Monitor class
• Provides a mechanism that synchronizes access to objects.
• It can be done by acquiring a significant lock so that only one thread can
enter in a given piece of code at one time.
• Monitor is not different from lock but the monitor class provides more
control over the synchronization of various threads trying to access the
same block of code.
• The Monitor class has the following methods for the synchronize access to
a region of code by taking and releasing a lock:
• Monitor.Enter
• Monitor.TryEnter
• Monitor.Exit.

By : Dr. Vikrant 19
Monitor class

By : Dr. Vikrant 20
Working with Tasks
• the task is basically used to implement Asynchronous Programming
i.e. executing operations asynchronously (means you can move to
another task before the previous one finishes.)
• Task-related classes are in System.Threading.Tasks namespace.
• In a performance point of view, the Task.Run or
Task.Factory.StartNew methods are preferable to create and
schedule the computational tasks.

By : Dr. Vikrant 21
Working with Tasks

By : Dr. Vikrant 22
Task return type
Using async and await

• Async methods that don't contain a return statement or that contain


a return statement that doesn't return an operand usually have a
return type of Task.
• If you use a Task return type for an async method, a calling method
can use an await operator to suspend the caller's completion until
the called async method has finished.

By : Dr. Vikrant 23
Task return type
Using async and await

By : Dr. Vikrant 24
Exercise
Let us think one berth is available in a train and two passengers are
requesting for the berth. Write a code to allocate one birth to only single
person.
Conditions:
Availability of birth = 1
Requested = 1
If (available >=requested)
Available=available-requested
Else
Display “ Sorry no berths available”

By : Dr. Vikrant 25
References
1. C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development
Fourth Edition by Mark J. Price
2. https://www.geeksforgeeks.org

By : Dr. Vikrant 26
Session-13

Introduction to ASP.NET
Contents
• What is ASP.NET?
• ASP.NET and earlier Web Development platforms
• Seven important facts about ASP.NET
• Web Architecture
• ASP.NET page life cycle
• Validation controls

By : Dr. Vikrant 2
What is ASP.NET?
ASP.NET is a server-side technology for building powerful, dynamic
Web applications and is part of the .NET Framework

By : Dr. Vikrant 3
ASP.NET and earlier web development
platforms
✔ ASP.NET features a completely object-oriented programming model,
which includes an event-driven, control-based architecture that
encourages code encapsulation and code reuse.

✔ ASP.NET gives you the ability to code in any supported .NET language
(including Visual Basic, C#, J#, and many other languages that have
third-party compilers)

By : Dr. Vikrant 4
ASP.NET and earlier web development
platforms
✔ ASP.NET is also a platform for building web services, which are
reusable units of code that other applications can call across platform
and computer boundaries.
✔ ASP.NET is dedicated to high performance. ASP.NET pages and
components are compiled on demand instead of being interpreted
every time they’re used. ASP.NET also includes a finetuned data
access model and flexible data caching to further boost performance.

By : Dr. Vikrant 5
Seven Important Facts About ASP.NET
Fact 1: ASP.NET Is Integrated with the .NET Framework
Fact 2: ASP.NET Is Compiled, Not Interpreted
Fact 3: ASP.NET is Multilanguage
Fact 4: ASP.NET runs inside the CLR
Fact 5: ASP.NET is Object Oriented
Fact 6: ASP.NET is Multidevice and Multibrowser
Fact 7: ASP.NET is Easy to Deploy and configure

By : Dr. Vikrant 6
Web Architecture

PC/Mac/Unix/...
Client
+ Browser
Request:
http://www.digimon.com/default.aspx

Network HTTP, TCP/IP

Response:
<html>….</html>

Server Web Server

By : Dr. Vikrant 7
ASP.NET Page Life Cycle
Srno Stages Description
1. Page request When the page is requested by a user, ASP.NET determines whether
the page needs to be parsed and compiled (therefore beginning the
life of a page)
2. Start Page properties such as Request and Response are set. At this stage,
the page also determines whether the request is a postback or a
new request and sets the IsPostBack property

3. Initialization During page initialization, controls on the page are available and
each control's UniqueID property is set. A master page and themes
are also applied to the page if applicable.

4 Load During load, if the current request is a postback, control properties


are loaded with information recovered from view state and control
state.

By : Dr. Vikrant 8
ASP.NET Page Life Cycle
Srno Stages Description

5. Postback event handling If the request is a postback, control event handlers are called. After
that, the Validate method of all validator controls is called, which
sets the IsValid property of individual validator controls and of the
page
6. Rendering Before rendering, view state is saved for the page and all controls.
During the rendering stage, the page calls the Render method for
each control, providing a text writer that writes its output to
the OutputStream object of the page's Response property.

7. Unload The Unload event is raised after the page has been fully rendered,
sent to the client, and is ready to be discarded. At this point, page
properties such as Response and Request are unloaded and
cleanup is performed.
By : Dr. Vikrant 9
Validation Controls
• A Validation server control is used to validate the data of an input
control.
• If the data does not pass validation, it will display an error message to
the user.
• Syntax:
<asp:control_name id="some_id" runat="server" />

By : Dr. Vikrant 10
Validation Controls
Validation Server Control Description
RequiredFieldValidator Makes an input control a required field
RangeValidator Checks that the user enters a value that falls
between two values
CompareValidator Compares the value of one input control to the
value of another input control or to a fixed value
RegularExpressionValidator Ensures that the value of an input control matches
a specified pattern
CustomValidator Allows you to write a method to handle the
validation of the value entered
ValidationSummary Displays a report of all validation errors occurred in
a Web page

By : Dr. Vikrant 11
Validation Controls
RequiredFieldValidator: ensures that the required field is not empty. It
is generally tied to a text box to force input into the text box.
Syntax:
<asp:RequiredFieldValidator
ID="rfvusername“
runat="server“
ControlToValidate =“txtUsername“
ErrorMessage=“*“ >
</asp:RequiredFieldValidator>

By : Dr. Vikrant 12
Validation Controls
• The RangeValidator control verifies that the input value falls within a
predetermined range.
• It has three specific properties:
<asp:RangeValidator ID="rvclass“
Properties Description runat="server“
Type it defines the type of the data; ControlToValidate="txtclass"
the available values are:
Currency, Date, Double,
ErrorMessage="Enter your class (6 -
Integer and String 12)"
MinimumV it specifies the minimum value MaximumValue="12“
alue of the range MinimumValue="6“
MaximumV it specifies the maximum Type="Integer">
alue value of the range </asp:RangeValidator>
By : Dr. Vikrant 13
Validation Controls
• The CompareValidator control compares a value in one control with
a fixed value, or, a value in another control.
• It has specific properties:
Properties Description
Type it specifies the data type
ControlToCompare it specifies the value of the input control to compare
with
ValueToCompare it specifies the constant value to compare with

Operator it specifies the comparison operator, the available


values are: Equal, NotEqual, GreaterThan,
GreaterThanEqual, LessThan, LessThanEqual and
DataTypeCheck
By : Dr. Vikrant 14
Validation Controls
CompareValidator control :
Syntax:
<asp:CompareValidator
ID="CompareValidator1"
runat="server"
ErrorMessage="Password Must Be Same“
ControlToValidate="txtConfirmPwd"
ControlToCompare="txtChoosePwd">
</asp:CompareValidator>

By : Dr. Vikrant 15
Validation Controls
• The RegularExpressionValidator allows validating the input text by
matching against a pattern against a regular expression. The regular
expression is set in the ValidationExpression property.
• Syntax:
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1“
runat="server“
ErrorMessage="Please Enter Valid Email“
ControlToValidate="txtEmail"
ValidationExpression="\w+([-+.']\w+)*@\w+([- .]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>

By : Dr. Vikrant 16
Validation Controls
• The CustomValidator control allows writing application specific
custom validation routines for both the client side and the server side
validation.
• The client side validation is accomplished through the
ClientValidationFunction property. The client side validation routine
should be written in a scripting language, like JavaScript or VBScript,
which the browser can understand.
• The server side validation routine must be called from the controls
ServerValidate event handler. The server side validation routine
should be written in any .Net language, like C# or VB.Net.

By : Dr. Vikrant 17
Validation Controls
• Syntax:
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ErrorMessage="Password Should not be less than 5 character"
ControlToValidate="txtChoosePwd"
ClientValidationFunction="validateText">
</asp:CustomValidator>

By : Dr. Vikrant 18
Validation Controls
• The ValidationSummary control does not perform any validation but
shows a summary of all errors in the page.
• The summary displays the values of the ErrorMessage property of all
validation controls that failed validation.
• Syntax:
<asp:ValidationSummary
ID="ValidationSummary1"
runat="server"
DisplayMode = "BulletList" />

By : Dr. Vikrant 19
References
1. C .Net Web Developers Guide by Syngress
2. ASP.NET 4.5, Covers C# and VB Codes, Black Book , Kogent Learning
Solutions Inc.

By : Dr. Vikrant 20
Session-14

Introduction to ASP.NET MVC


Contents
• ASP.NET MVC Architecture
• ASP.NET MVC folder structure
• Creating controllers
• Action Methods
• Different Types of Action Results

By : Dr. Vikrant 2
ASP.NET MVC Architecture
• MVC stands for Model, View, and Controller.
• MVC is a standard design pattern
• The ASP.NET MVC framework is a lightweight, highly testable
presentation framework that (as with Web Forms-based applications)
is integrated with existing ASP.NET features, such as master pages
• The MVC framework is defined in the System.Web.Mvc namespace
and is a fundamental, supported part of
the System.Web namespace.

By : Dr. Vikrant 3
ASP.NET MVC Architecture
Models.
• Model objects are the parts of the application that implement the
logic for the applications data domain.
• Often, model objects retrieve and store model state in a database.
• For example, a Product object might retrieve information from a
database, operate on it, and then write updated information back to
a Products table in SQL Server.

By : Dr. Vikrant 4
ASP.NET MVC Architecture
View
• View in MVC is a user interface.
• View display model data to the user and also enables them to modify
them.
• View in ASP.NET MVC is HTML, CSS, and some special syntax (Razor
syntax) that makes it easy to communicate with the model and the
controller.

By : Dr. Vikrant 5
ASP.NET MVC Architecture
Controller:
• The controller handles the user request.
• Typically, the user uses the view and raises an HTTP request, which
will be handled by the controller.
• The controller processes the request and returns the appropriate
view as a response.
• Controller is the request handler

By : Dr. Vikrant 6
ASP.NET MVC folder structure
• App_Data : folder can contain
application data files like LocalDB, .mdf
files, XML files, and other data related
files.
• App_Start : folder can contain class files
that will be executed when the
application starts
• Content : folder contains static files like
CSS files, images, and icons files. MVC
application includes bootstrap.css,
bootstrap.min.css, and Site.css by
default.

By : Dr. Vikrant 7
ASP.NET MVC folder structure
• 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". Eg.
HomeController
• Fonts : folder contains custom font files
for your application.
• 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.

By : Dr. Vikrant 8
ASP.NET MVC folder structure
• Scripts folder contains JavaScript or
VBScript files for the application.
• Views folder contains HTML files for the
application. Typically view file is a .cshtml
file where you write HTML and C# 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.

By : Dr. Vikrant 9
ASP.NET MVC folder structure
Configuration files :
• 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 : file is managed by
NuGet to track what packages and
versions you have installed in the
application.
• Web.config : file contains
application-level configurations.
By : Dr. Vikrant 10
Creating Controllers
• The Controller in MVC architecture handles any incoming URL request
• Controller is a class derived from the base class
System.Web.Mvc.Controller
• Controller class contains public methods called Action methods.
• Controller and its action method handles incoming browser requests,
retrieves necessary model data and returns appropriate responses.

By : Dr. Vikrant 11
Creating the Controller

By : Dr. Vikrant 12
Creating Controller

By : Dr. Vikrant 13
Creating Controller

By : Dr. Vikrant 14
Example : StudentController

By : Dr. Vikrant 15
Example : StudentController

By : Dr. Vikrant 16
Action Methods
• 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 must be public. It
cannot be private or protected
• Action method cannot be
overloaded
• Action method cannot be a static
method.

By : Dr. Vikrant 17
Different Types Of Action Results In ASP.NET MVC

By : Dr. Vikrant 18
View Result
View result is a basic view result. It returns basic results to view page.
View result can return data to view page through which class is defined
in the model. View page is a simple HTML page.

public ViewResult Gallary()


{
ViewBag.Message = "This is about gallary page";
return View();
}

By : Dr. Vikrant 19
PartialView Result
Partial View Result is returning the result to Partial view page. Partial
view is one of the views that we can call inside Normal view page.
We should create a Partial view inside shared folder, otherwise we
cannot access the Partial view.

public PartialViewResult Index()


{
return PartialView("_PartialView");
}
By : Dr. Vikrant 20
Redirect Result
• Redirect result is returning the result to specific URL. It is rendered to
the page by URL.

public RedirectResult Index()


{
return Redirect("Home/Contact");
}

By : Dr. Vikrant 21
Redirect to Action Result
Redirect to Action result is returning the result to a specified controller
and action method. Controller name is optional in Redirect to Action
method. If not mentioned, Controller name redirects to a mentioned
action method in current Controller

public ActionResult Index()


{
return RedirectToAction("GetStudents", "Student");
}

By : Dr. Vikrant 22
Json Result
public JsonResult GetAllStudents()
{
Json (JavaScript List<Student> students = new List<Student>()
Object Notation) {
new Student
result is a {
significant Action StudentId = 1,
StudentName = "Alex"
Result in MVC. It },
will return simple new Student
{
text file format and StudentId = 2,
key value pairs. }
StudentName = "Smith"

};

return Json(students, JsonRequestBehavior.AllowGet);

By : Dr. Vikrant 23
File Result
File Result returns different file format view page when we implement
file download concept in MVC using file result.

public ActionResult Index()


{
return File("Web.Config", "text");
}

By : Dr. Vikrant 24
Content Result
Content result returns different content's format to view. MVC returns
different format using content return like HTML format, Java Script
format and any other format.

public ActionResult Index()


{
return Content("<script>alert('Welcome To All');</script>");
}

By : Dr. Vikrant 25
References
1. C .Net Web Developers Guide by Syngress
2. ASP.NET 4.5, Covers C# and VB Codes, Black Book , Kogent Learning
Solutions Inc.

By : Dr. Vikrant 26
Session-15

Understanding Views and State


management
Contents
• Razor View Engine
• HTML Helpers
• Standard HTML Helper methods
• Strongly-Typed HTML Helper
• Validations using Data Annotation Attributes
• State Management
• Client side state management
• Server side State management

By : Dr. Vikrant 2
Razor View Engine
• Razor is one of the view engines supported in ASP.NET MVC. Razor
allows you to write a mix of HTML and server-side code using C# or
Visual Basic
• The razor view uses @ character to include the server-side code. You
can use C# or Visual Basic syntax to write server-side code inside the
razor view.

By : Dr. Vikrant 3
Razor View Engine
ASP.NET MVC supports the following types of razor view
files:
File extension Description
.cshtml C# Razor view. Supports C# code with
html tags.

.vbhtml Visual Basic Razor view. Supports Visual


Basic code with html tags.

.aspx ASP.Net web form


.ascx ASP.NET web control

By : Dr. Vikrant 4
Razor View Engine

By : Dr. Vikrant 5
HTML Helpers
• HtmlHelper class renders HTML
controls in the razor view.
• It binds the model object to HTML
controls to display the value of model
properties into those controls and also
assigns the value of the controls to the
model properties while submitting a
web form.
• So we can use the HtmlHelper class in
razor view instead of writing HTML
tags manually.
• @Html is an object of the HtmlHelper
class

By : Dr. Vikrant 6
Form Design using HTML Helpers Methods
// Index.cshtml // StudentController

@model Session15DemoMVC.Models.Student public ActionResult Form1( Student obj)


@{ {
Layout = null; ViewBag.Id = obj.StudentId;
} ViewBag.Name = obj.StudentName;
<!DOCTYPE html> ViewBag.Age=obj.Age;
<html>
<head> return View("Index");
<meta name="viewport" content="width=device-width" /> }
<title>Index</title>
</head>
<body>
@using (Html.BeginForm(“Form1", “Student", FormMethod.Post))
{
@Html.LabelFor(m => m.StudentId); @Html.TextBoxFor(m => m.StudentId);
@Html.LabelFor(m => m.StudentName); @Html.TextBoxFor(m => m.StudentName);
@Html.LabelFor(m => m.Age); @Html.TextBoxFor(m => m.Age);
<input type="submit" value="Submit Form" />
}
</body>
<h4 style="color:purple">
<b>ID:</b> @ViewBag.Id <br />
<b>Name:</b> @ViewBag.Name <br />
<b>Age:</b> @ViewBag.Age
</h4>
</html>
By : Dr. Vikrant 7
Standard HTML Helper methods
• @Html.ActionLink() - Used to create link on html page
• @Html.TextBox() - Used to create text box
• @Html.CheckBox() - Used to create check box
• @Html.RadioButton() - Used to create Radio Button
• @Html.BeginForm() - Used to start a form
• @Html.EndForm() - Used to end a form
• @Html.DropDownList() - Used to create drop down list
• @Html.Hidden() - Used to create hidden fields
• @Html.label() - Used for creating HTML label is on the browser
• @Html.TextArea() - The TextArea Method renders textarea element on browser
• @Html.Password() - This method is responsible for creating password input field on browser
• @Html.ListBox() - The ListBox helper method creates html ListBox with scrollbar on browser
By : Dr. Vikrant 8
Strongly-Typed HTML Helper
• @Html.HiddenFor()
• @Html.LabelFor()
• @Html.TextBoxFor()
• @Html.RadioButtonFor()
• @Html.DropDownListFor()
• @Html.CheckBoxFor()
• @Html.TextAreaFor()
• @Html.PasswordFor()
• @Html.ListBoxFor()

By : Dr. Vikrant 9
Validations using Data Annotation Attributes
Attribute Usage
• ASP.NET MVC includes Required Specifies that a property value is
built-in attribute classes in required.
the System.ComponentMo StringLength Specifies the minimum and maximum
del.DataAnnotations length of characters that are allowed in
a string type property.
namespace.
Range Specifies the numeric range
• You can apply these constraints for the value of a property.
attributes to the properties RegularExpression Specifies that a property value must
of the model class to match the specified regular expression.
display appropriate CustomValidation Specifies a custom validation method
validation messages to the that is used to validate a property.
users.

By : Dr. Vikrant 10
Validations using Data Annotation Attributes
Attribute Usage
EmailAddress Validates an email address.

FileExtension Validates file name extensions.

MaxLength Specifies the maximum length of array


or string data allowed in a property.
MinLength Specifies the minimum length of array
or string data allowed in a property.
Phone Specifies that a property value is a
well-formed phone number.

By : Dr. Vikrant 11
Validations using Data Annotation Attributes
Student.cs (inside model)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Session15DemoMVC.Models
{
public class Student
{
[Required]
public int StudentId { get; set; }

[StringLength(10)]
[Required]
public string StudentName { get; set; }

[Range (18,45)]
public int Age { get; set; }

[EmailAddress]
[Required]
public string Email { get; set; }
}
}

By : Dr. Vikrant 12
Validations using Data Annotation Attributes
Index.cshtml

By : Dr. Vikrant 13
State Management
• State Management is the process where developers can maintain
status, user state and page information on multiple requests for the
same or different pages within the web application.
• Two types :
• Client-side state management - The information is stored in the customer
system while end-to-end interaction. Eg. ViewBag, TempData, Cookies,
QueryStrings
• Server-side state management - Store all the information in the server’s
memory. Eg. Session and Application

By : Dr. Vikrant 14
Client-Side State Management
//EmployeeDetails.cshtml
@{
ViewBag.Title = "EmployeeDetails";
View bag : It is used to transfer the data }

from Controller to View <h2>EmployeeDetails</h2>

<h3>@ViewBag.Message</h3>
//HomeController <html>
<body>
public ActionResult EmployeeDetails() @{
{ var emp = ViewBag.Emp;
Employee employee = new Employee(); <table>
{ <tr>
employee.Empid = 101; <td>ID :</td>
employee.Ename = "Alex"; <td> @emp.Empid</td>
} </tr>
<tr>
ViewBag.Message = "Employee Details"; <td>Name :</td>
ViewBag.Emp= employee; <td> @emp.Ename</td>
return View(); </tr>
} </table>
}
</body>
By : Dr. Vikrant </html> 15
Client-Side State Management

TempData: stores value in key/value pair. It is derived from


TempDataDictionary. If the data for TempData has been read, then it
will get cleaned. To persist the data, we use Keep()
TempData is used to transfer data from view to controller, controller
to view, or from one action method to another action method of the
same or a different controller.
TempData stores the data temporarily and automatically removes it
after retrieving a value.

By : Dr. Vikrant 16
Client-Side State Management
//About.cshtml
TempData: @{
ViewBag.Title = "About";
}
public ActionResult TestTempData() <h2>@ViewBag.Title.</h2>
{
Employee employee = new Employee(); <p>
{ @{
employee.Empid = 101; var data = (StateManagementDemo.Models.Employee)TempData["Emp"];
employee.Ename = "Alex"; TempData.Keep();
}
//Setting the TempData @data.Empid;
TempData["emp"] = employee;
return RedirectToAction("Contact"); @data.Ename;
}
}
public ActionResult Contact() </p>
{
//Not reading TempData
return View();
}

public ActionResult About()


{
//Data will available here because we have not read data yet
var tempEmpData = TempData["Emp"];

return View();
} By : Dr. Vikrant 17
Client-Side State Management
Cookies:
• A cookie is a plain-text file stored by the client (usually a browser), tied to a specific
website.
• The client will then allow this specific website to read the information stored in this file
on subsequent requests, basically allowing the server (or even the client itself) to store
information for later use.
public ActionResult Cookietest()
{
HttpCookie cookie = new HttpCookie("TestCookie");
cookie.Value = "This is test cookie"; //Setting Cookie value
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);

if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("TestCookie"))
{
HttpCookie cookievar = this.ControllerContext.HttpContext.Request.Cookies["TestCookie"];
ViewBag.CookieMessage = cookievar.Value;
}
return View();
} By : Dr. Vikrant 18
Client-Side State Management
QueryString
• A query string is a string variable that is inserted at the end of the page URL. It can be
used for sending data over several pages
//HomeController
public ActionResult QueryStringTest()
{
//Send Model object in QueryString to another Controller.
return RedirectToAction("Index", "Employee", new { Empid = 1, Ename = "Gary" });
}

//EmpoyeeController
public ActionResult Index()
{
Employee obj = new Employee()
{
Empid = int.Parse(Request.QueryString["Empid"]),
Ename = Request.QueryString["Ename"]
};
return View(obj);
}
By : Dr. Vikrant 19
//Index.cshtml of EmployeeController
//QueryStringTest.cshtml of @model StateManagementDemo.Models.Employee
HomeController @{
Layout = null;
}
@{
<!DOCTYPE html>
Layout = null;
<html>
}
<head>
<meta name="viewport" content="width=device-width" />
<!DOCTYPE html>
<title>Index</title>
</head>
<html>
<body>
<head>
<table cellpadding="0" cellspacing="0">
<meta name="viewport" content="width=device-width" />
<tr>
<title>QueryStringTest</title>
<th colspan="2" align="center">Employee Details</th>
</head>
</tr>
<body>
<tr>
@using (Html.BeginForm("Form1", "Home", FormMethod.Post))
<td>Employee ID: </td>
{
<td>@Model.Empid</td>
<input type="submit" value="Send" />
</tr>
}
<tr>
</body>
<td>Name: </td>
</html>
<td>@Model.Ename</td>
</tr>

</table>
</body>
</html>

By : Dr. Vikrant 20
Server-Side State Management
Session : Session state enables you to store and retrieve values for a
user when the user navigates to other view in an ASP.NET MVC
application
//Index.cshtml
//EmployeeController
Session Name :
public ActionResult Form1(Employee obj) @if (Session["empid"] != null)
{ {
Session["empid"] = Convert.ToString(obj.EmpID);
@Html.Label(Convert.ToString(Session["empid"]))
return View("Index"); }
}

By : Dr. Vikrant 21
Server-Side State Management
• Application State : is stored in the memory of the server and is faster than
storing and retrieving information in a database.
• Session sate is specific for a single user session, but Application State is for
all users and sessions.
• Technically the data is shared amongst users by a HTTPApplicationState
class and the data can be stored here in a key/value pair.
• It can also be accessed using the application property of the HTTPContext
class.
• Global.asax file is used for handling application events or methods. It
always exists in the root level

By : Dr. Vikrant 22
Server-Side State Management
Event execution by the HTTPApplication class for any specific
requirement.

By : Dr. Vikrant 23
References
1. C .Net Web Developers Guide by Syngress
2. ASP.NET 4.5, Covers C# and VB Codes, Black Book , Kogent Learning
Solutions Inc.

By : Dr. Vikrant 24
Session-17

Layout, Bundle, Minification and


MVC Security
Contents
• Layout View
• Understanding Bundles and Bundle Types
• Minification
• Error handling in MVC with log entry
• MVC Security
• Cross Site Request Forgery Attacks
• Anti-forgery token
• Introduction to OAuth

By : Dr. Vikrant 2
Layout View
• An application may contain a specific UI portion that remains the
same throughout the application, such as header, left navigation bar,
right bar, or footer section.
• ASP.NET MVC introduced a Layout view which contains these
common UI portions so that we don't have to write the same code in
every page
• The layout view eliminates duplicate coding and enhances
development speed and easy maintenance

By : Dr. Vikrant 3
Layout View
• The layout view has the
same extension as other
views, .cshtml or .vbhtml.
• Layout views are shared
with multiple views, so it
must be stored in the
Shared folder

By : Dr. Vikrant 4
Layout View
Method Description
RenderBody() Renders the portion of the child
view that is not within a named
section. Layout view must include
the RenderBody() method.
RenderSection(string name) Renders a content of named
section and specifies whether the
section is required.

By : Dr. Vikrant 5
By : Dr. Vikrant 6
Layout View
@RenderSection :
• false parameter denotes that particular section is optional and It is
your choice whether to use it or not.
• If you use true parameter then it is compulsory to use this section in
child page otherwise you will get error.

@RenderSection("subheader", required:false)

By : Dr. Vikrant 7
Layout View
Layout View (_myLayout.cshtml)
<div class="container-fluid">
<p>
@RenderBody()
</p>
<div class="border-end bg-primary" style="color: white">
@RenderSection("subheader", required:false)
</div>
</div>

Child View (About.cshtml)


@{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

<p>Use this area to provide additional information.</p>

@section subheader {
About Us Footer
} By : Dr. Vikrant 8
Bundling Loading Scripts in Separate Request

https://www.amazon.com/Scripts/abc.js

• Bundling and abc.js

minification techniques Browser https://www.amazon.com/Scripts/xyz.js Server


were introduced in MVC xyz.js
4 to improve request
load time.
• Bundling allows us to Loading Bundle
load the bunch of static
files from the server in a https://www.amazon.com/js-bundle

single HTTP request. Browser Server


xyz.js
abc.js

By : Dr. Vikrant 9
Bundle Types
• ScriptBundle: ScriptBundle is responsible for JavaScript minification
of single or multiple script files.
bundles.Add(new ScriptBundle("~/bundles/myjsfiles").Include(
"~/Scripts/scripts.js")); //In BundleConfig.cs
@Scripts.Render("~/bundles/myjsfiles") //In .cshtml file

• StyleBundle: StyleBundle is responsible for CSS minification of single


or multiple style sheet files.
bundles.Add(new StyleBundle("~/Content/mycss").Include(
"~/Content/styles.css")); //In BundleConfig.cs

@Styles.Render("~/Content/mycss") //In .cshtml file


By : Dr. Vikrant 10
Minification
Minification technique optimizes script or CSS file size by removing
unnecessary white space and comments and shortening variable
names to one character.
Example: JavaScript Minification
details = function(name)
{ sayHello=function(n){var t="Hello"+n;alert(t)}
//this is comment
var msg= "Hello"+ name;
alert(msg);
}

By : Dr. Vikrant 11
Error handling in MVC with log entry
• HandleError is the default bulit-in exception filter in ASP.NET MVC
• HandleError Attribute filter works only when custom errors are
enabled in the Web.config file of your application. Controller
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Error/NotFound"/>
</customErrors>
</system.web>

Action

By : Dr. Vikrant 12
MVC Security
• MVC Security implements security features in the application. It also
supports new membership features included with ASP.NET and
available for use from ASP.NET MVC.
• Also it has the new identity components that is a part of ASP.NET and
see how to customize membership for our users and roles.

By : Dr. Vikrant 13
MVC Security
Authentication of user
means verifying the
identity of the user. This
is really important.
You might need to
present your
application only to the
authenticated users for
obvious reasons.

By : Dr. Vikrant 14
MVC Security
Authentication options
1. None : The first option is No Authentication/None and this option is used
when you want to build a website that doesn't care who the visitors are.
2. Individual User Accounts : This is the traditional forms-based
authentication where users can visit a website. They can register, create a
login, and by default their username is stored in a SQL Server database
using some new ASP.NET identity features
3. Microsoft Identity platform: It’s an open-source libraries, and application
management tools
4. Windows :which works well for intranet applications. A user logs into
Windows desktop and can launch a browser to the application that sits
inside the same firewall

By : Dr. Vikrant 15
Cross Site Request Forgery Attacks
Malicious websites HTML form
• CSRF attacks are possible against web sites
<h1>Congratulations!! </h1>
that use cookies for authentication, because <form action="http://somewebsite.com/api/account"
browsers send all relevant cookies to the method="post">
destination web site.
• Example of a CSRF attack: <input type="hidden" name="Transaction"
value="withdraw" />
1. A user logs into www.somewebsite.com using
form authentication <input type="hidden" name="Amount" value=“2000000" />
2. The server authenticates the user. The
response from the server includes an <input type="submit" value="Click Me"/>
authentication cookie.
3. Without logging out, the user visits a malicious </form>
web site. This malicious site contains the given
HTML form.
4. The user clicks the submit button. The browser Notice that the form action posts to the vulnerable site,
includes the authentication cookie with the not to the malicious site. This is the "cross-site" part of
request.
CSRF.
5. The request runs on the server with the user's
authentication context, and can do anything
that an authenticated user is allowed to do.
By : Dr. Vikrant 16
Cross Site Request Forgery Attacks
• As soon as user clicks the form button, the malicious page could
just as easily run a script that submits the form automatically.
• Even SSL does not prevent a CSRF attack, because the malicious
site can send an "https://" request.

By : Dr. Vikrant 17
Anti-forgery token
To help prevent CSRF attacks, ASP.NET MVC uses anti-forgery tokens, also
called request verification tokens.
1. The client requests an HTML page that contains a form.
2. The server includes two tokens in the response. One token is sent as a
cookie. The other is placed in a hidden form field. The tokens are
generated randomly so that an adversary cannot guess the values.
3. When the client submits the form, it must send both tokens back to the
server. The client sends the cookie token as a cookie, and it sends the
form token inside the form data.
4. If a request does not include both tokens, the server disallows the
request.

By : Dr. Vikrant 18
Anti-forgery token
Example of an HTML form with To add the anti-forgery tokens to a Razor page,
use the HtmlHelper.AntiForgeryToken helper
hidden form token:
method:
<form action="/Home/Test" method="post">
@using (Html.BeginForm(“Form2", “Employee"))
<input name="__RequestVerificationToken"
{
type="hidden"
@Html.AntiForgeryToken()
value="6fGBtLZmVBZ59oUad1Fr33BuPxANKY9
}
q3Srr5y[...]" />

<input type="submit" value="Submit" />

</form>

By : Dr. Vikrant 19
OAuth
• OAuth stands for Open Authorization
• OAuth is an open standard for authorization.
• OAuth provides client applications a "secure delegated access" to
server resources on behalf of a resource owner.
• It specifies a process for resource owners to authorize third-party
access to their server resources without sharing their credentials.
• It is an open standard for token-based authentication and
authorization.

By : Dr. Vikrant 20
References
1. C .Net Web Developers Guide by Syngress
2. ASP.NET 4.5, Covers C# and VB Codes, Black Book , Kogent Learning
Solutions Inc.
3. https://docs.microsoft.com/

By : Dr. Vikrant 21
Session-18

Entity Framework and ASP.NET


MVC Core
Contents
• Introduction to Entity Framework
• Different Approaches
• Code First
• Database First
• Model First
• Data Annotations Attributes in EF 6
• Introduction to ASP.NET Core
• Difference ASP.NET MVC and MVC Core

By : Dr. Vikrant 2
Introduction to Entity Framework
• Entity Framework is an Object Relational Mapper (ORM) which is a
type of tool that simplifies mapping between objects in your software
to the tables and columns of a relational database.
• It is an open source ORM framework for ADO.NET which is a part of
.NET Framework.
• An ORM takes care of creating database connections and executing
commands, as well as taking query results and automatically
materializing those results as your application objects.

By : Dr. Vikrant 3
Different Approaches
The Entity Framework provides three approaches to create an entity
model and each one has their own pros and cons.
• Code First
• Database First
• Model First

By : Dr. Vikrant 4
Different Approaches
Code First:
• Code First modeling workflow targets a
database that doesn’t exist and Code
First will create it.
• It can also be used if you have an empty
database and then Code First will add
new tables to it.
• You focus on the domain of your
application and start creating classes for
your domain entity rather than design
your database first and then create the
classes which match your database
design
• This means you need to start coding first
in C# or VB.NET and then EF will create
the database from your code.

By : Dr. Vikrant 5
Different Approaches
Database First:
• It creates model codes (classes, properties, DbContext etc.) from the
database in the project and those classes become the link between
the database and controller.
• creates the entity framework from an existing database.

By : Dr. Vikrant 6
Different Approaches
Model First:
• Model First is good when you are starting a new project where the
database doesn't even exist yet.
• The model is stored in an EDMX file and can be viewed and edited in the
Entity Framework Designer.
• In Model First, you define your model in an Entity Framework designer
then generate SQL, which will create database schema to match your
model and then you execute the SQL to create the schema in your
database.
• The classes that you interact with in your application are automatically
generated from the EDMX file.
.

By : Dr. Vikrant 7
Data Annotations Attributes in EF 6
Namespace to include : System.ComponentModel.DataAnnotations

Attribute Description
Key Can be applied to a property to specify a key property in an entity and make the
corresponding column a PrimaryKey column in the database.
Required Can be applied to a property to specify that the corresponding column is a NotNull
column in the database.
MinLength Can be applied to a property to specify the minimum string length allowed in the
corresponding column in the database.
MaxLength Can be applied to a property to specify the maximum string length allowed in the
corresponding column in the database.
StringLength Can be applied to a property to specify the maximum string length allowed in the
corresponding column in the database.

By : Dr. Vikrant 8
Data Annotations Attributes in EF 6
Namespace to include :
System.ComponentModel.DataAnnotations.Schema Attributes

Attribute Description
Table Can be applied to an entity class to configure the corresponding table name and
schema in the database.
Column Can be applied to a property to configure the corresponding column name, order
and data type in the database.
Index Can be applied to a property to configure that the corresponding column should
have an Index in the database. (EF 6.1 onwards only)
ForeignKey Can be applied to a property to mark it as a foreign key property.

NotMapped Can be applied to a property or entity class which should be excluded from the
model and should not generate a corresponding column or table in the database.

By : Dr. Vikrant 9
Some Examples of Data Annotations in EF
1. Table
using System.ComponentModel.DataAnnotations.Schema;

[Table("StudentMaster")]
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
}

2. Key
using System.ComponentModel.DataAnnotations;

public class Student {

[Key]
public int StudentKey { get; set; }
public string StudentName { get; set; }
} By : Dr. Vikrant 10
Introduction to ASP.NET Core
ASP.NET Core is a cross-platform,
high-performance, open-source framework for building modern,
cloud-enabled, Internet-connected apps. With ASP.NET Core, you can:
• Build web apps and services, Internet of Things (IoT) apps, and mobile
backends.
• Use your favorite development tools on Windows, macOS, and Linux.
• Deploy to the cloud or on-premises.
• Run on .NET Core.

By : Dr. Vikrant 11
Difference ASP.NET MVC and MVC Core
Difference 1 – Single aligned web stack for ASP.NET Core MVC and Web
APIs

By : Dr. Vikrant 12
Difference ASP.NET MVC and MVC Core
Difference 2 – Project (Solution) Structure Changes : ASP.NET Core 5 MVC
solution explorer on the right-hand side, there is no Web.config, Global.asax

By : Dr. Vikrant 13
Difference ASP.NET MVC and MVC Core
Difference 3 – ASP.NET Core
apps don’t need IIS for hosting
The goal of ASP.NET Core is to be cross-platform
using .NET Core (.NET 5). With this in mind,
Microsoft decided to host ASP.NET Core
applications on IIS and be self-hosted or use the
Nginx web server on Linux.

Difference 4 – wwwroot folder


for static files

By : Dr. Vikrant 14
Difference ASP.NET MVC and MVC Core
Difference 5 – New approach to
Server-side and client-side
dependency management of
packages. Leverage the experience of
working in Visual Studio IDE and deploy
ASP.NET Core applications either on Windows,
Linux, or Mac using .NET Core, its Server side
management of dependencies. Client-side
dependency management is more important
because the client-side has more different
packages from the server-side. Client-side will
indeed have jQuery, Bootstrap, grunt, and any
Javascript frameworks like AngularJS, Backbone,
images, and style files. Server Side (red) and Client-Side
(green) Dependency Management

By : Dr. Vikrant 15
Difference ASP.NET MVC and MVC Core
Difference 6 – Inbuilt Dependency Injection (DI) support for ASP.NET
Core 5
Dependency Injection (DI) achieves loosely coupled, more testable code; it’s vital because it helps
write unit tests.

Note : The Dependency Injection Design Pattern in C# is a process in which we are injecting the
object of a class into a class that depends on that object. Dependency Injection pattern
involves 3 types of classes:
• Client Class: The Client class (dependent class) is a class that depends on the service class.
• Service Class: The Service class (dependency) is a class that provides service to the client
class.
• Injector Class: The Injector class injects the service class object into the client class.

By : Dr. Vikrant 16
References
1. C .Net Web Developers Guide by Syngress
2. ASP.NET 4.5, Covers C# and VB Codes, Black Book , Kogent Learning
Solutions Inc.
3. https://docs.microsoft.com/

By : Dr. Vikrant 17
Session-19

Localization in MVC
and
Deploying MVC Application
Contents
• Localization
• ISO Codes for Cultures
• CultureInfo class
• Server Side Culture Declaration
• Setting the culture to the client's culture
• Deploying MVC Application on IIS

By : Dr. Vikrant 2
Localization
• Internationalization is the process of enabling your code to run
correctly all over the world. It has two parts: globalization and
localization.
• Globalization is about writing your code to accommodate multiple
languages and region combinations. The combination of a language
and a region is known as a culture.
• Localization the process of customization to make our application
behave depending on the current culture and locale
• The namespace required : System.Globalization

By : Dr. Vikrant 3
ISO Codes for Culture Combinations
• There are International Organization for Standardization (ISO) codes
for all culture combinations.
• For example,
1. in the code da-DK, da indicates the Danish language and DK indicates the
Denmark region,
2. in the code fr-CA, fr indicates the French language and CA indicates the
Canadian region.

By : Dr. Vikrant 4
CultureInfo Class
• In the .NET Framework , the CultureInfo class from
System.Globalization namespace provides culture-specific
information such as the associated language, country or region,
calendar, and cultural conventions.
• The CurrentCulture property represents the culture that the current
thread uses.
• The CurrentUICulture property represents the current culture that
Resource Manager uses to look up culture-specific resources at run
time.

By : Dr. Vikrant 5
Server Side Culture Declaration
• ASP.NET enables you to define the culture used by your entire ASP.NET
application or by a specific page within your application. You can specify
the culture for any of your ASP.NET applications by means of the
appropriate configuration files.
• Defining the <globalization> section in the web.config file
<configuration>
<system.web>
<globalization culture="ru-RU" uiCulture="ru-RU" />
</system.web>
</configuration>

Note : Setting the culture at either the server-wide or the application-wide


level

By : Dr. Vikrant 6
Server Side Culture Declaration
• Defining the culture at the page level using the @Page directive
<%@ Page Language="C#" UICulture="ru-RU" Culture="ru-RU" %>

This example determines that the Russian language and culture


settings are used for everything on the page.

By : Dr. Vikrant 7
Setting the culture to the client's culture
When working with culture on the client side, the culture that is
used is the culture that is defined on the server. Therefore, if
you have the culture set to en-US on your server, this is the
default that is utilized on the client-side operations as well.
int value=3000;
//Spanish(Mexico)
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("es-MX");
Console.WriteLine(value.ToString("c"));

//English(UK)
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB");
Console.WriteLine(value.ToString("c"));

By : Dr. Vikrant 8
Deploying MVC Application
Enabling IIS and required IIS
components on Windows 10
1. Open Control Panel and click
Programs and Features > Turn
Windows features on or off.
2. Enable Internet Information
Services.
3. Expand the Internet
Information Services feature
and verify that the web server
components listed in the next
section are enabled.
4. Click OK.
5. Check from start menu for “ IIS
Manager” in Windows
By : Dr. Vikrant 9
Deploying MVC Application
6. Start IIS Manager with
Administrator

By : Dr. Vikrant 10
Deploying MVC Application
Publish the MVC application
1. Open the Visual Studio with
Administrator
2. In the Solution explorer,
Right click the Project and
Select “Publish”
3. Select Webserver (IIS) and
Click next
4. Then Select “Web Deploy
Package” and click Next
5. Then provide the location of
your Project and Mention site
name.
6. Then Publish
By : Dr. Vikrant 11
Deploying MVC Application

Creating Virtual Directory


1. Open the IIS Manager with
Administrator
2.Right Click on the Default
Web Site and Add Application
3. Give the Alias and path of
the Application folder
4. Click OK
5. Test the website execution
by right click on website added
> Manage Application and
Browse

By : Dr. Vikrant 12
References
1. C# 8.0 and .NET Core 3.0 – Modern Cross-Platform Development
2. https://vmsdurano.com/deploying-your-asp-net-mvc-5-app-to-iis8/

By : Dr. Vikrant 13
Session-20

Windows Communication
Foundation(WCF)
Contents
• Services
• SOA
• WCF overview
• Contracts
• Service Contracts
• Data Contracts
• Message Contracts
• Programming Model of WCF
• Binding Types
• Adding WCF in VS2022
• WCF Service Creation
By : Dr. Vikrant 2
Services
• Services are the logical encapsulation of self-contained business
functionalities
• Services are not classes or namespaces or objects. It's just
self-contained business functionality.

Example : The petrol filling station is providing three services( fuel


filling up, air pressure checking, checking puncture) that are logically
encapsulated within one filling station and they are self contained

By : Dr. Vikrant 3
Service Oriented Architecture (SOA)
SOA is nothing but an architectural style where two non-compatible
applications can communicate using a common language.
Eg. Windows Communication Foundation (WCF)

The message format can be XML, JSON or even a plain CSV file
By : Dr. Vikrant 4
WCF Overview
• WCF stands for Windows Communication Foundation.
• It is a framework for building, configuring, and deploying
network-distributed services by which we can send asynchronous
message/data from one service endpoint to another service
endpoint.
• The basic feature of WCF is interoperability
• WCF is used to build service-oriented applications.
• A WCF application consists of three components −
• WCF service,
• WCF service host, and
• WCF service client.

By : Dr. Vikrant 5
Fundamental Concepts of WCF
• Message : Message instances are sent as well as received for all types
of communication between the client and the service.
• Endpoint : It defines the address where a message is to be sent or
received.
• Binding: It defines the way an endpoint communicates. It comprises
of some binding elements that make the infrastructure for
communication. For example, a binding states the protocols used for
transport like TCP, HTTP, etc., the format of message encoding, and
the protocols related to security as well as reliability.
• Contracts: It is a collection of operations that specifies what
functionality the endpoint exposes to the client. It generally consists
of an interface name.

By : Dr. Vikrant 6
Fundamental Concepts of WCF
• Hosting: refers to the WCF service hosting which can be done
through many available options like self-hosting and IIS hosting
• WCF Client: A client application that gets created for exposing the
service operations in the form of methods is known as a WCF client.
• Channel: Channel is a medium through which a client communicates
with a service.
• SOAP: Although termed as ‘Simple Object Access Protocol’. It is an
XML document comprising of a header and body section.

By : Dr. Vikrant 7
Contracts
The contracts layer is just next to the application layer and contains
information similar to that of a real-world contract that specifies the
operation of a service and the kind of accessible information it will make.
Types discussed below:
• Service contract − This contract provides information to the client as well
as to the outer world about the offerings of the endpoint, and the
protocols to be used in the communication process.
• Data contract − The data exchanged by a service is defined by a data
contract. Both the client and the service has to be in agreement with the
data contract.
• Message contract − A data contract is controlled by a message contract. It
primarily does the customization of the type formatting of the SOAP
message parameters. SOAP stands for Simple Object Access Protocol.

By : Dr. Vikrant 8
Programming Model of WCF

The ABCs of Endpoints


9
Programming Model of WCF
• Address: "A" stands for Address that specifies where the service is.
Every service has a unique address whose format is as follows:

[Transport] ://[Domain Name]:[Port]//[Service Name]

• Binding: "B" stands for Binding that specifies how to talk with the
service. All built-in bindings are defined in the System.ServiceModel
namespace.
• Contract: "C" stands for Contract that tells us about what can service
do for me.
By : Dr. Vikrant 10
Types of Bindings
• BasicHttpBinding: This is the basic web service for the communicate
with a web server or a client application. It is designed to expose a
WCF service as an asmx web service. This binding uses the HTTP
protocol for communication.
• NetMsmqBinding: It is used to implement message queuing in a WCF
service. It enables a client application to send a message to a WCF
service even if the service is unavailable.
• NetTcpBinding: It allows the communication between a WCF service
and a .NET client application over a network. It uses the TCP protocol
and is a much faster and more reliable binding compared to HTTP
protocol binding.

By : Dr. Vikrant 11
Types of Bindings
• NetPeerTcpBinding: For peer-to-peer communication where
messages are sent and received using the TCP protocol.
• WSHttpBinding: It is similar to BasicHttpBinding and uses the HTTP or
HTTPS protocol. It also supports WS-Transactions and WS-Security
that are not supported by the BasicHttpBinding.
• WSDualHttpBinding: It is similar to WSHttpBinding, except it supports
bi-directional communication which means both clients and services
can communicate with each other by sending and receiving
messages.
• NetNamedPipeBinding: This binding uses named pipes for
communication between two services on the same machine that is
most secure and the fastest binding among all the bindings.
By : Dr. Vikrant 12
Adding WCF in Visual Studio

Search ‘WCF’ in
the individual
components and
add Windows
communication
foundation in
Visual Studio just
like we add
previous
components

By : Dr. Vikrant 13
WCF Service Creation
1. Once WCF
installed
completely,
Create the New
Project and Select
WCF Service
Application.
2. Click Next.
3. Then, Give the
name for your
Project and Click
Create

By : Dr. Vikrant 14
WCF Service Creation

4. One interface
and one class
gets added in the
project.
5. Implement the
interface
methods in
Service1.svc.cs
6. Test and execute

By : Dr. Vikrant 15
WCF Service Creation

7. Keep it in
execution mode to
consume by client
applications
8. Copy the address

By : Dr. Vikrant 16
Consuming the WCF Service by client
• Create any client
application
• Right click the project
and then Add the
reference ->
System.ServiceModel

By : Dr. Vikrant 17
Consuming the WCF Service by client
• Again right click the
project and then Add the
service reference
• Paste the copied address
from the running wcf
service
• Change the namespace
for the reference
• Click ok
• Use its services in your
client application

By : Dr. Vikrant 18
References
1. https://docs.microsoft.com

By : Dr. Vikrant 19
Session-21

Web APIs
Contents
• API
• Web API
• Uses of API
• Creating WebAPI project

By : Dr. Vikrant 2
API
An API, or application programming interface, is a set of rules that
define how applications or devices can connect to and communicate
with each other.

By : Dr. Vikrant 3
Web API
• Web API is an application
programming interface (API)
that is used to enable
communication or
interaction with software
components with each other.
• ASP.NET Web API is a
framework that makes it
easy to build HTTP Service
that reaches a broad range
of clients, including browsers
and mobile devices.
• Using ASP.NET, web API can
enable communicating by
different devices from the
same database.
By : Dr. Vikrant 4
Uses of Web API
• It is used to access service data in web applications as well as many
mobile apps and other external devices.
• It is used to create RESTful web services. REST stands for
Representational State Transfer, which is an architectural style for
networked hypermedia applications.
• It is primarily used to build Web Services that are lightweight,
maintainable, and scalable, and support limited bandwidth.
• It is used to create a simple HTTP Web Service. It supports XML, JSON,
and other data formats.

By : Dr. Vikrant 5
Creating Web API project

By : Dr. Vikrant 6
Creating Web API project

By : Dr. Vikrant 7
Creating Web API project

This project is same as default MVC project with two specific files for Web API, WebApiConfig.cs
(to configure routes and other things for Web API) in App_Start folder and ValuesController.cs
in Controllers folder as shown below. By : Dr. Vikrant 8
Creating Web API project
Web API has returned a result in XML or JSON format. Our output looks like below.

By : Dr. Vikrant 9
References
1. https://docs.microsoft.com

By : Dr. Vikrant 10
Ti
me20mi
ns

1.Whi
chist hedefaul
tbasecl
assf
oral
lcl
asses?
A.System.object
B.System.Object
C.SystemObject
D.Object
Syst em

2.Howdoyouspeci f
yt hatacl asscannotbeusedasabasecl
ass?
A.markitasast ruct
(structclassMyCl ass{}
)
B.changeitsaccessspecifi
erfrompubl i
ct oanyot
her accessspeci
fi
er(i
nter
nalcl
ass
MyClass{}
)
C.mak ei
tabstract(abstractclassMyCl ass{]
)
D.makeitsealed(sealedcl assMyCl ass{})

3.Thisist
hecor rectsyntaxforover l
oadingthe+operat
orf
orMyCl
assandai
nt
A.publi
cMyCl assoper at
or+(
inta){.
.
.}
B.publi
cstat
icMyCl assoperator+(i
nta){.
..
}
C.publi
cMyClassoper ator+(
MyCl assx,i
nta){
..
.}
D.publi
cstati
cMyCl assoperator+(MyClassx,i
nta)
{.
..
}

4.Thisisthecorrectsymtaxf orwr iti


nganext ensi
onmet
hodf
orast
ring
A.publi
cvoi dDoSomet hi
ng(
stri
nga) {
..
.}
B.publi
cIExtensi
onvoidDoSomet hi
ng(str
inga){..
.}
C.publi
cs tat
icvoidDoSomet hing(stri
nga){ .
.
.}
D.publi
cst ati
cvoidDoSomet hi ng(t
hisstringa){.
..
}

5.WhatdoesAr
ray.
I
ndexOf
()r
etur
nift
hei
tembei
ngsear
chedi
snotf
ound?
A.null
B.error
C.Indexoft
hel
asti
tem+1
D.-1

6.GivetheCTS(CommonTypeSys
tem)t
ypef
orf
loat
A.System.Fl
oat
B.System.
Decimal
C.System.Si
ngle
D.System.Doubl
e

7.charvar
iabl
esoccupy___byt
es
A.1
B.2
C.0
D.4

8.Whatisthecor
rectsyn
taxf
oral
ambdat
hatt
akesnopar
amet
ersandhasmul
ti
plel
i
ne
ofcode
a.()=>{
code}
b. =>code
c.delegat
e( )
{}
d Notpossibletodoso

9.Foraclasstobeseri
ali
zedusi
ngt heBinaryFor matter,
A.Theclassneedstobemar kedwithanat tributeISeriali
zable
B.Theassemblyneedstobemar k
edwi t
hanat t
ribut
eI Serial
izabl
e
C.Theclassneedstobemarkedwi t
hanat t
ributeSer i
alizable
D.Theassemblyneedstobemar kedwithanat tr
ibuteSer ial
i
zable

10.Whichoftheseiscorrectfortheexpli
citi
mpl
ement
ati
onofani
nter
face?
A.publi
cvoidMet hod1
(){
}
B.voidMethod1(
){}
C.publi
cvoidInterf
aceName.Method1
(){
}
D.voidInt
erfaceName.Method1()
{}

11
.Howdoyoudecl ar
eanul
labl
eint?
A.Null
abl
einta;
B.i
nta=null;
C.int
?a; OR Null
abl
e<T>i=null
;
D.int
??a;

12.Whichint
erf
acedoesArrayLi
sti
mpl
ement
?
A.ILi
st
B.ILi
st<T>
C.IDicti
onar
y
D.IDicti
onar
y<TKey,
TValue>

13.Whichofthesei
sthecor rectsynt
axf
oranobj
ecti
ni
ti
ali
zer
?
a.Class1o=newClass1{
a=1 0};
b.Class1o=newClass1(
){a=10};
c.Class1o=newClass1(
20){a=10};
d.Alloftheabove

14.Howdoyoucallafunct
ionusi
ngThr
eadPool
?
a.Start
b.Begin
c.Invoke
d.QueueUser
WorkI
tem

15.Whi
choft hefoll
owingstatement sisfal
se?
A.Astructdoesnotallowinheri
t ance.
B.Astructcannothaveanopar amet erconst
ruct
or
C.Astructisavaluetype
D.Astructisstor
edont hestacki nmemor y.
E.Astructcannothavemet hods.

16.I
nFormsAuthenti
cati
on,thefoll
owingmet
hoddel
etest
heaut
hent
icat
ioncook
ie.
A.FormsAuthent
icati
on.
Cook i
e.Del
ete
B FormsAut
henticat
ion.
Logout
C.For
msAuthent
icati
on.
SignOut
D.For
msAut
henticat
ion.
Cookie.
Remove

17.Togenerat
eapr
oxycl
assf
oraWCFser
viceweuset
hef
oll
owi
ngcommandl
i
neut
il
it
y
a.genprox
b.svcutil
c.wsdl
d.csc

18.Howdoyouover ridethebundl
ingset
tingofweb.confi
g?
a.writecodeinBundleConfig.
csandsett heEnableOpti
mizati
onspropertyofthe
BundleTableclass
b.writecodeinBundleConfi
g.conf
igandsettheEnableOptimi
zati
onspropert
yoft he
BundleTablecl
ass
c.writecodeinBundleConfi
g.csandsettheEnableOpti
mizati
onspropert
yoft he
BundleColl
ecti
onclass
d.writecodeinBundleConfi
g.conf
igandsettheEn abl
eOptimi
zati
onspropert
yoft he
BundleColl
ecti
onclass

19.ToachieveMi nif
icat i
on(
Minif
icati
onremovesallwhi tespaceandr
enamesvar
iabl
est
o
thei
rshort
estpossi blename)i nasp.n
etmvc
a.Setmini
ficat
ion=t rueincompi l
ati
onsecti
oninweb. conf i
g
b.Setmini
ficat
ion=f alseincompilat
ionsect
ioninweb. config
c.Setdebug=t ruei ncompi l
ati
ons ecti
oninweb.confi
g
d.Setdebug=f alseincompi l
ationsectioni
nweb. config

20.Toshowapar tialvi
ewi
nasp.
netmvcwi
thamet
hodt
hatr
etur
nsaht
mlst
ringweuse
a.Html
.Parti
al(
)
b.Html
.
Render Parti
al()
c.Html
.RenderAction()
d.Html
.RenderView( )

==================================================================

.
NetMi
dmodul
etest

1.Oncompi
lat
ionofCShar
psour
cecode,t
heout
putwegeti
s
A.bytecode
B.assembl
y
C.IL
D.MSIL

2.Ji
tcompil
ati
onconvert
s
A.ILtoMSIL
B.MSILtoIL
C.sourcecodetoIL
D.sourcecodetonati
vecode
E.noneoftheabove
3.Garbagecollecti
onhappensat
A.regul
arint
erval s
B.whenanobj ectgoesoutofscope
C.whent heCLRdeci des
D.attheendoft hecodeexecuti
on

4.Appdomainsare
A.Theareainmemor ywhereanappli
cati
onruns
B.Theareainsi
deapr ocesswhereanappli
cati
onr
uns
C.Theareawher etheappli
cat
ionhasi
tsdomain
D.Ontheheap

5.CLSis
A.asetofrulesthatal
l.netcompiler
sfoll
ow
B.asetofrulest
hatareal l
owedf ora.netlanguage
C.asetofr ul
esthatall.
netlanguagesmustf oll
owt obeabl
etobecal
ledf
romot
her
l
anguages
D.usedfordatatypes

6.GivetheCTSt ypef
orf
loat
A.System.Fl
oat
B.System.
Decimal
C.System.Si
ngle
D.System.Doubl
e

7.charvar
iabl
esoccupy___byt
es
A.1
B.2
C.0
D.4

8.Whichoft hefol
lowingstatementsisTrue?
A.Funcisusedt ocallmethodswi thavoidretur
nt ype,Act i
onfornonvoi
dreturntype
methodsandPr edi
cat eformethodswi t
haboolpar amet er
B.Funcisusedt ocallmethodswi t
havoi dret
urnt ype,Act ionfornonvoi
dret
urnt ype
methodsandPr edi
cat eformethodswi t
haboolr etur nvalue
C.Actioni
susedt ocal lmethodswi t
havoidreturnt ype,Funcfornonvoi
dretur
nt ype
methodsandPr edi
cat eformethodswi t
haboolpar amet er
D.Actionisusedtocal lmethodswi thavoidreturnt ype,Funcfornonvoi
dreturntype
methodsandPr edicateformet hodswithaboolr et urnvalue

9.Whenisthestat
icconst
ruct
orcalled?
A.wheneveranobjecti
screated
B.whentheclassi
sloaded
C.whenMainiscal
led
D.wheneverastati
cmethodiscall
ed

10.Whichofthefoll
owi
ngi
str
uef orast
ati
ccl
ass?
A.Itcanonlycontai
nst
ati
cmethods
B.I
tcannotbei nst
ant
iat
ed
C.Itcannotbeusedasabasecl
ass
D.Alloftheabove
E.Noneoft heabove

11
.Whati sthedef
aul
taccessspeci
fi
erf
ormember
sinacl
ass?
A.int
ernal
B.publ
ic
C.pri
vat e
D.protected

12.Whatisthedef
aul
taccessspeci
fi
erf
oracl
assdecl
aredi
nanamespace?
A.inter
nal
B.publi
c
C.pri
vat e
D.protected

13.
classBaseCl ass
{inta;
publicBaseCl ass(inta)
{t hi
s.a=a; }
}
classDer ivedClass:BaseClass
{intb;
publicDer i
vedCl ass(i
ntb)
{t hi
s.b=b; }
}
classPr ogram{
staticvoidMai n()
{Der i
vedCl asso=newDeri
vedCl
ass(
10)
;}
}

Whatisthevalueino.
aafterr
unni
ngt
hiscode?
A.0
B.10
C.null
D.codewillnotcompi
le.

14.Whichofthesest atement
si str
ue?
A.Toover l
oadaf uncti
ondefinedint
hebasecl
assfr
omtheder
ivedcl
assweusethe
overl
oadsk eyword
B.Toover l
oadaf unctiondefi
nedinthebasecl
assf
romt
hederi
vedclassweuset
henew
(ForMethodHiddi
ng) keyword
C.Toover l
oadaf unct i
ondefinedint
hebasecl
assfr
omtheder
ivedcl
assweusethe
overr
idekeywor d
D.Noneoft heabove

1
5.Whi
choft
hesest
atement
sist
rue?
A.Tohideaf unct
iondef
inedi
nthebasecl
assfromt
hederi
vedclassweusethe
overl
oadskeyword
B.Tohideafunctiondefi
nedi
nthebaseclassf
romtheder
ivedclassweusethenew
keyword
C.Tohideafunctiondef
inedi
nthebasecl
assfromt
hederi
vedclassweusetheoverr
ide
keyword
D.Tohideafunctiondef
inedi
nthebasecl
assfromt
hederi
vedclassweusetheseal
ed
keyword
E.Noneoftheabove

16.Whi choft hesest atement


sisfalse?
A.Toover r
ideaf unct i
ondefi
nedinthebasecl
assfr
omtheder
ivedcl
assthebaseclass
met hodmustbeavi rtualmet
hod
B.Toover ri
deaf unctiondef
inedi
nt hebasecl
assf
romt
hederi
vedclassweuset he
over ri
dek eywor d
C.Toover r
ideaf unct i
ondefi
nedinthebasecl
assfr
omtheder
ivedcl
assthemethod
signaturesmustbet hesame
D.Noneoft heabove

17.Whi
choft hesest atementsisfalse?
A.Anabstractcl assneednothaveanyabst ractmethods
B.Anabstractcl asscannotbei nstantiated
C.Aclasst hatcont ainsatleastoneabst r
actmethodneedstobemar k
edasabstr
act
D.Aderivedcl assmusti mplemental labstractmethodsofanabst
ractbasecl
assort
he
deri
vedclassmustbemar kedasabs tract
E.Noneoft heabove

18.Whi
chofthesest
atementsisf al
se?
A.Asealedcl
asscannotbeusedasa basecl ass
B.Asealedcl
asscanbeinstant
iated
C.Asealedcl
asscannothavevi r
tualmet
hods
D.Asealedcl
asscannothaveabst r
actmethods
E.Noneoftheabove

19.Whichoft hesestat
ementsistr
ue?
A.Inlatebi nding,wedeclar
eanobj ectofthebasecl assandall
ocatememoryfora
derivedclass
B.Inlat
ebi nding,wedeclareanobjectofthederivedclassandall
ocatememoryfora
baseclass
C.Inlatebinding,wecannotdeclar
eanobj ectoft hebaseclassandall
ocat
ememoryfora
sub-der
ivedcl ass
D.Inlatebinding,weneednothaveanyvi rtualmethodsinthebaseclass
E.Noneoft heabove

20.Whichofthesei scorr
ectf ortheexpli
citi
mpl
ement
ati
onofani
nter
face?
A.publi
cvoidMet hod1(
){}
B.voidMethod1(
){}
C.publi
cvoidInt
er f
aceName. Method1
(){
}
D.voidInt
erfaceName.Met hod1(
){}
21.Howdoyoudeclar
eanul
labl
eint
?
A.Nul l
abl
einta;
B.inta=null;
C.int?a;
D.int??a;

22.Whichstat ementi
sf alse?
A.outvari
abl esneednothaveani ni
ti
alval
ue
B.outvari
ablesl osetheirini
ti
alvaluewhent heyent erthefunction
C.youmusti niti
ali
seanoutvar i
blebeforecontrolleavesthef uncti
on
D.outvari
abl escannotbeusedi nthefuncti
onbef oretheyar einit
ial
ised
E.Noneoft heabove

23.Whichstatementistrue?
A.refvari
ablesneednothaveani niti
alval
ue
B.refvari
ableslosetheiri
ni
ti
alvaluewhent heyentert
hefunction
C.youmusti ni
ti
ali
sear efvari
blebeforecontroll
eavesthefuncti
on
D.refvari
ablescannotbeusedi nthefunct
ionbeforetheyareinit
ial
i
sed
E.Noneoft heabove

24.
i
nt[,]ar
r=newi nt
[4,
3];
Whatwi l
lbethevaluesfor:
arr
.Rank,ar
r.
GetLength(
1),ar
r.
Get
Upper
Bound(
0)
A.2,3,3
B.2,4,3
C.2,3,4
D.1,3,3
E.1,4,3

25.WhatdoesArray.
IndexOf
()r
etur
nift
hei
tembei
ngsear
chedi
snotf
ound?
A.null
B.error
C.Indexoft
helastit
em+1
D.-1

26.Whichclassi
susedtoiteratethr
uaSor
tedLi
st<TKey,
TVal
ue>?
A.Dict
ionaryEnt
r y
B.Di
cti
onaryEntry<TKey,
TVal ue>
C.KeyValuePair
D.KeyValuePair<TKey,
TValue>

27.WhichinterfacedoesI
Col
lect
ion<T>i
nher
itf
rom?
A.IEnumerable
B.IEnumerable<T>
C.ILi
st<T>
D.IDict
ionary<T>
E.Noneoft heabove
28.I
ngener
ics,whatcons
trai
ntmean
sthatTcanonl
ybeaval
uet
ype?
A.whereT:value
B.wher
eT:val ueType
C.whereT:struct
D.wher
eT:cl ass

29.Whatisthebasecl
assofal
lcl
assesi
fnocl
asshasbeenspeci
fi
edast
hebasecl
ass?
A.Nothi
ng
B.ToStri
ng(
)
C.base
D.Object

30.Whi
choft hefoll
owingstatementsisfalse?
A.Astructdoesnotallowinheri
tance.
B.Astr
uctcannothaveanopar amet erconstr
uct
or
C.Astructi
saval uetype
D.Astr
uctisstoredont hestackinmemor y.
E.Astr
uctcannothavemet hods.

31.Howdoyouspeci fythatathreadshoul
dgetahi
ghert
imesl
i
ce?
a.setthePri
orit
ypr oper
ty
b.settheThreadPri
ori
typropert
y
c.settheTi
meSl i
ceinmill
i
seconds
d.Cannotbedone

32.Howcanyouk
eepwai
ti
ngt
il
lanot
hert
hread(
cal
ledt
)fi
ni
shes?
a.t.
Join
b.t.
WaitOne
c.t.
Wait
d.t.
Sleep

33.Whichofthesei
sthecorrectsynt
axf
oranobj
ecti
ni
ti
ali
zer
?
a.Cl
ass1o=newCl ass1
{a=10};
b.Cl
ass1o=newCl ass1
(){
a=10};
c.Cl
ass1o=newCl ass1
(20){
a=10};
d.Alloftheabove

34.Howdoyoucallafunct
ionusi
ngThr
eadPool
?
a.Star
t
b.Begi
n
c.I
nvoke
d.QueueUser
Wor
kItem

35.Whatist hecor
rectsynt
axf
oral
ambdat
hatt
akesnopar
amet
ersandhasmul
ti
plel
i
ne
ofcode
a.()=>{code}
b. =>code
c.delegate(){
}
d Notpossi
blet
odoso

======================================================================

1.Whi
choft hefol
lowingstatementsisfal
se?
a.TheGar bageCollectorusestheconceptofgenerati
onstofr
eememory.
b.Generati
on0i scheckedf i
rst.
c.I
fanobj ectisnotf r
eed,itispromotedtoGener
ationN+1whereNi
sit
scurr
ent
gener
ation.
d.Thereareamaxi mumof3gener at
ions0,
1,
and2.
e.Noneoft heabove.

2.Whyshoul dweimplementIDisposable?
a.I
tisbetterthannondeterminist
icfi
nali
zation
b.Di
sposeget scal
ledautomat i
call
yf orallobj
ect
sinausi
ngbl
ock
c.Towr i
tecodet ofreeresources
d.Alloftheabove
e.Noneoft heabove

3.Whichofthefol
lowingstatementsi
sf al
se?
a.TheAssemblycontainsMetadataandcode.
b.Theassemblyi
sinMSI Lformat.
c.Theassemblymaycont ai
noneormor emodul
es.
d.Theassemblyhasanent r
ypoint(Main()
).
e.Noneoftheabove.

4.AutomaticProper tyhast hefoll


owingsyntax
a.publ
icpropertypr opertyname{ get{
}set{}
}
b.publ
ici
ntproper tyname{ get{}set{}
}
c.publ
icpropertyname{ get;set ;
}
d.publ
icintpropertyname{ get;set;
}

5.Whichofthefol
lowi
ngstatement
sisfal
se?
a.arefer
encetypecannotbepassedasar ef
b.avaluetypecanbepassedasar ef
c.r
efandoutcanbot hchangethevalueofthevar
iabl
eint
hecal
li
ngcode
d.avaluetypecanbepassedasout

6.Howcanyouk
eepwai
ti
ngt
il
lanot
hert
hread(
cal
ledt
)fi
ni
shes?
a.t.
Join
b.t.
WaitOne
c.t.
Wait
d.t.
Sleep

7.Whi
chstat
ementistr
uef oranExtensi
onmethod?
a.Ext
ensi
onmethodscanbewr i
tteni
nanyclass.
b.Ext
ensi
onmethodscannothaveparameter
s.
c.Ext
ensi
onmet
hodscanbeoverri
dden.
d.Ext
ensi
onmethodsmustbest
ati
c.

8.Whichofthesemet
hodscannotbeover
ri
dden?
a.stati
c
b.overri
de
c.vi
rtual
d.abstr
act

9.Whi choft hefol


lowi
ngt
ypescanbeusedasabasecl
ass?
a.Abst ractClass
b.Struct
c.Seal edclass
d.Enum
e.Noneoft heabove

10.Whichdelegateclassi
susedt ospeci
fyaf uncti
ontobecal
ledaut
omat
ical
lyaf
tert
he
functi
onthatisinvok
edbydel egateobj
ect.
BeginI
nvoke?
a.IAsyncResult
b.AsyncCallback
c.AsyncResult
d.Action
e.Noneoft heabove

11
.Howdoyouspeci fythatat hreadshoul
dgetahi
ghert
imesl
i
ce?
a.setthePri
orit
ypr operty
b.settheThreadPri
ori
typr opert
y
c.settheTi
meSl i
ceinmill
iseconds
d.Cannotbedone

12.Whichofthesecl
assesisusedf
orsynchr
oni
zat
ioni
nThr
eadi
ng?
a.ThreadPool
b.ThreadStar
t
c.Monitor
d.Par
amet eri
zedThr
eadStart

13.
WhatdoesaLI NQquer
yret
urn?
a.var
b.I
Collect
ion<T>
c.I
List
<T>
d.I
Enumerable<T>

14.Whatisthecorrectsynt
axf
oral
ambdat
hatt
akesnopar
amet
ersandhasmul
ti
plel
i
ne
ofcode
a.()=>{code}
b. =>code
c.delegate()
{}
d Notpossibletodoso
15.Howdoyouconver tLi
nqquerytoPLI
NQ?
a.cannotbedone
b.justaddtheletterPbef or
eit
c.UseAsPar al
lel
()fort hecoll
ecti
onobj
ect
d.implementI
Enumer abl
e<Pli
nq>

16.Whichofthefol
lowi
ngi
saVal
uet
ype?
a.Array
b.Int
erface
c.Delegate
d.Class
e.Noneoft heabove

17.Howcanyoucal lafuncti
onusingTask?
a.Createat askobjectandcalltheStartmet
hod
b.UseTask.Run
c.UseTask.Factory.St
artNew
d.Alloftheabove

18.Whichoft hesei scor


rectf
oraf
unct
iont
hatr
etur
nsani
ntandt
akesast
ringasa
parameter?
a.Action<i
nt,st ri
ng>
b.Action<string,i
nt>
c.Func<int
,str i
ng>
d.Func<st r
ing,int>

19.Whatisthecorrectsynt axforoperatorover
loadi
ng?
a.publ
i
cintoper at
or+(Class1o,inti)
{}
b.publ
icstati
cintoperat or
+(Class1o,inti
){
}
c.publ
i
cintoper at
or+(inti)
{}
d.publ
i
cst ati
cintoperator+(inti)
{}

20.Howdoyoucallafunct
ionusi
ngThr
eadPool
?
a.Star
t
b.Begi
n
c.I
nvoke
d.QueueUser
Wor
kItem

1. Whi
chofthef
oll
owingst
at ement
siscorrect
A.C#datatypebool-CTSt ypeBoolean,C#datat
ypef
loat–CTSt
ypeFl
oat
B.C#dat
atypebool-CTSt
ypeBool,C#dat atypefl
oat–CTStypeFl
oat
C.C#dat
atypebool-CTStypeBoolean,C#datatypefl
oat–CTStypeSingl
e
D.C#dat
atypebool-CTSt
ypeBool,C#dat atypefl
oat–CTStypeSi
ngl
e

2.Whi
chofthefol
lowingstatementsisfalse?
A.Assembl
ymet adatacanber eadusingRefl
ect
ion
B.Assembl
yisi
nI Lform
C.Assembl
ycont ai
nsmetadat aandcode
D.Assembl
ycanhaveat t
ribut
es
E.Noneoftheabove

3.Thedef aul
tdat
atypeofanenumi
s
A.Int32
B.Int16
C.Int64
D.String

4.Tomakeanassembl yshared,weneedt
o…
A.Giveitastrongname
B.Si
gnitwithak eypair
C.I
nstal
liti
nt heGAC
D.Alloftheabove
E.Noneoft heabove

5. i
)Stori
ngavaluet ypeintoar eferencetyperesult
sinBoxing
ii
)St
or i
ngaref
er encetypei n
toaval uetyperesul
tsinBoxing
ii
i
)St ori
ngavaluet ypeint
oar eferencetyperesul
tsinUnBoxing
i
v)St
ori
ngar
efer
encet
ypei
ntoaval
uet
yper
esul
tsi
nUnBoxi
ng
A.Allar
ef alse
B.Allar
et rue
C.i
)andii
i)aretrue
D.i
i)
andiv)ar etrue
E.i
)andiv)ar etrue
F.i
)andii
)ar etrue

6.Whi
choft hefoll
owingst at
ement sisfalse?
A.AllGeneri
cCol l
ectionsimplementIEnumerabl
e<T>
B.I
List
<T>i nheri
tsfromI Coll
ection<T>
C.I
Dicti
onaryinheri
tsf r
omI Coll
ection
D.I
Collecti
oninheri
tsf r
omI Enumerable
E.Noneoft heabove
7.Tocal
lamet hodasynchronousl
yusingadel
egat
eobj
ect
,weuse
A.obj
Del.I
nvoke(…)
B.objDel
.Begi
nInvoke(…)
C.obj
Del.EndI
nvoke(…)
D.System.Del
egate.I
nvokeAsync(
…)

8.Whati
st heerrorinthefoll
owingsni
ppet
?
voi
dDoSomet hing(
)
{
tr
y
{
…..
}
catch(
Except i
onex){…}
catch(
NullRefer
enceExcepti
onex){…}
catch(
DivideByZeroExcepti
onex){…}
}

A.Nofinall
ywri
tten
B.Noer r
ors
C.exobjectisre-
decl
aredmult
ipl
et i
mes
D.Baseclassexcepti
onisgi
venfirst

9.Whichproper
tymustbeseti nWCFConf i
gurati
ont oal
lowuser
stoseeExcept
ion
Detai
lsofaWCFMet hods?
A.servi
ceDebugallowExcept i
ons
B.ser
viceDebugincludeExcept ionDet
ail
InFault
s
C.servi
ceDebugincludeCust omExcepti
onDet ai
ls
D.servi
ceMetadatai ncludeCustomExcepti
onDet ai
l
s

1
0.Torai
seaneventdef i
nedbyyou,
A.RaiseEventEventName
B.RaiseEventEventName(…)
C.EventName( …)
D.DelegateClassName(…)

1
1.Whichoft hef
oll
owi
ngi
snotaval
i
dThr
eadst
ateasdef
inedi
ntheThr
eadSt
ate
enum?
A.Abor ted
B.Running
C.St opped
D.Sleep
E.Suspended
F.Backgr
ound

1
2.Whatistr
uef oraback
groundthread?
A.Backgroundthr
eadcannotbecal l
eddirect
ly
B.Backgroundthr
eadgetsalesserprior
ity
C.Backgroundthr
eadisUnmanagedcode
D.Backgroundthr
eadrunsonl
ywhent heCPUi si
dle
E.Alloftheabove
F.Noneoft heabove

1
3.Whatisthedi f
f er
encebetweenoutandr efvari
ables?
A.outvariablescan’tchanget hecall
ingcodevariabl
evaluebutrefcan
B. outvariablescanchanget hecalli
ngcodevar i
ableval
uebutrefcan’t
C.outvar i
ablesmustbei nit
iali
zedbef orethefuncti
onends.Notrequi
redf
orr
ef
variabl
es
D.outvariablescan’tbeusedf orr
eferencetypesbutrefcan.
E.Noneoft heabove

1
4.Whatisfalseforast aticconst
ruct
or?
A.Paramet erl
ess
B.Cantbeover loaded
C.Impli
cit
lypr i
vate
D.Calledwhent heclassi
sloadedint
omemor
y
E.Calledjustonce
F.Noneoft heabove

1
5.Forpr
opertyaccessors,whi choft hefoll
owi
ngisnotal
lowed?
A.Publi
cpr oper
ty,pri
vat eaccessor
B.Protectedinter
nalproper ty,pr
ivat
eaccessor
C.Protectedproperty,internalaccessor
D.Int
ernalpropert
y,pri
vat eaccessor

1
6.Whi
chclasscanbeusedasabaseclass?
A.Abstract
B.Seal
ed
C.Stat
ic
D.i
nter
nalclassdef
inedi
nanot
herassembl
y

1
7.Whi
choft hefol
lowingstat
ement si
sf al
se?
A.Anabst r
actclasshasatleastoneabst ractmethod
B.Allabstr
actmet hodsar
epur evi
rtualfuncti
ons
C.Anabst r
actmet hodcanonlyexistinanabstractcl
ass
D.Thederi
vedclassmusti
mpl
emental
ltheabst
ractmet
hodsorbemar
kedasan
abst
ractcl
ass
E.Noneoftheabove

1
8.i
nt?a=100;
Whati
sfalsef orthi
sstatement?
A.aisanullabletypevariabl
e
B.Compi
lerconver tsthi
st oNul
labl
e<i
nt>a=1
00?
C.Thi
sli
nei saner ror
D.a=nullisvalid

1
9.Whatisfalse?
A.AllArraysinheritf
romtheAr r
ayclass
B.Wecani ter
ateusingaforeachloop
C.Arraysar ear efer
encetype
D.Doubledi mensionarr
ayscanbesor tedusi
ngAr
ray.
Sor
t

20.Whichisnotval i
dLINQ?
i
) f r
omai nbwher ea.i>0sel ecta.j
i
i) b.
Select(a=>a.j
).
Wher e(a=>a.
i>0)
i
ii
)b.Wher e(a=>a.
i>0).Select(
a=>a.j
)
A.Onlyi
B.Onl yii
C.Onlyi i
i
D.iiandiii

21
.I nFormsAuthenti
cati
on,thef oll
owingmet
hoddel
etest
heaut
hent
icat
ioncook
ie.
A.FormsAuthent
icat
ion.Cook i
e.Del
ete
BFormsAuthenti
cati
on.Logout
C.FormsAuthenti
cati
on.SignOut
D.For
msAut hent
icat
ion.Cookie.
Remove

22.Whichoftheseisavail
abl
einaRedi
rectbutnoti
nsubsequentr
equest
s?
a.ViewBag
b.ViewData
c.TempData
d.Sessi
onvariabl
e

23.Howdoyouoverr
idethebundl
ingsett
ingofweb.
confi
g?
a.wri
tecodei
nBundleConfi
g.csandsettheEnabl
eOpti
mizati
onspropert
yofthe
Bundl
eTabl
eclass
b.wri
tecodei
nBundleConf
ig.
confi
gandsettheEnabl
eOptimi
zati
onspropert
yofthe
Bundl
eTabl
ecl
ass
c.wri
tecodeinBundleConf
ig.
csandsettheEnabl
eOpti
mizati
onsproper
tyofthe
Bundl
eColl
ect
ionclass
d.wri
tecodeinBundleConf
ig.
conf
igandsettheEnabl
eOptimi
zati
onsproper
tyof
theBundl
eCol
lect
ionclass

24.ToachieveMini
fi
cati
oninasp. netmvc
a.Setmini
fi
cati
on=t rueincompi l
ati
onsecti
oninweb. confi
g
b.Setmini
fi
cati
on=f alseincompilat
ionsect
ioninweb. conf
ig
c.Setdebug=trueincompi lati
onsecti
oninweb.confi
g
d.Setdebug=f al
seincompi l
ati
onsectioni
nweb. config

25.Toshowaparti
alviewi nasp.
netmvcwi
thamet
hodt
hatr
etur
nsaht
mlst
ringweuse
a.Ht
ml.
Parti
al(
)
b.Ht
ml.
RenderParti
al()
c.Ht
ml.
RenderAction()
d.Ht
ml.
RenderView()

26. Toall
owamethodtobecall
edfromaWebservi
ce,dot hefol
lowi
ng
A. Keepi
tasapubl
icmethod
B. Keepi
tasapubl
icst
aticmet
hod
C. Keepi
tasapubl
icmethodwithaWebMet
hodat t
ribut
e
D. Keepi
tasapubl
icst
aticmet
hodwithaWebMethodattri
but
e

27. Whichclassdowei
nher
itf
romwhi
l
eint
eract
ingwi
tht
heEnt
ityFr
amewor
k
A. Enti
ty
B. Framework
C. DbContext
D. DataContext

28. Whi
choft hefoll
owingstatement
sist r
ue?
A. Acommandcanbeexecut edfromacl osedconnect
ion
B. ADatareadercannotcontainmorethanonesetofdata
C. ADataSetcanonl yhaveonedat aTable
D. ADataAdapterneednothaveanopenconnect iontocal
lit
sfi
llmet
hod

29. WhatdoestheSoapFor matterser


iali
ze
A. methodsofaclass
B. publ
icvari
abl
esandpr opert
iesofacl ass
C. publ
icandpri
vatevariablesofacl ass
D. publ
icandpri
vateproperti
esofacl ass

30. ToaddaPr i
marykeyconst
raintontheDataTable
A. passaDat
aColumnarr
ayobjectt ot
hePrimaryKeypr opert
yf ortheDat aSet
B. passaDat
aColumnobjectt
ot hePri
maryKeypr oper
tyf ortheDat aSet
C. passaDataCol
umnarrayobjecttothePri
mar yKeypr oper
tyf ortheDat aTabl
e
D. passaDat
aCol
umnobj
ectt
othePr
imar
yKeypr
oper
tyf
ort
heDat
atabl
e

31
. Toseerecordsf
romaDat aTabl
einasor
tedmanneruse…
A. Sor
tproper
tyofDataTable
B. Sor
tpropert
yofDataView
C. Sor
tproper
tyofDataSet
D. Sor
tproper
tyofDataColumn

32.Howdoyour unamet hodi


nanewthr
ead
a.Createat hreadobjectandpassamet
hodasapar
amet
ert
otheconst
ruct
or
b.callt
hread.Run()
c.callthr
ead.Start(
)
d.callt
hread.BeginI
nvoke()

33.Whichoft hesepr
ovi
desar
eadonl
y,f
orwar
donl
ywayofr
eadi
ngr
ecor
ds
a.DataTable
b.Dat
aVi ew
c.DataSet
d.Sql
Dat aReader

34.Whichofthesedoesnotr
equi
ret
ypecast
ingwhi
l
eaccessi
ngi
t
a.ViewBag
b.ViewData
c.TempData
d.Sessi
onvari
able

35.Whichmethodoft
heDat
aSetr
etur
nst
her
ecor
dswhoseRowSt
atei
snotUnchanged
a.AcceptChanges
b.Reject
Changes
c.GetChanges
d.Update

36.InaWCFservi
cet
hef
oll
owi
ngdescr
ibest
heWCFser
vicei
ndet
ail
a.ProxyClass
b.WSDL
c.Mexendpoint
d.Discofi
l
e

37.Whatat t
ributeisusedt
omar
kamet
hodi
naSer
viceCont
ract
?
a.Servi
ceCont ract
b.DataContract
c.DataMember
d.Operati
onCont act

38.Dupl
exWCFser
viceusest
hef
oll
owi
ngbi
ndi
ng
a.WsDupl
exHt tpBinding
b.WsDual
HttpBi nding
c.WebHtt
pBinding
d.Basi
cHt
tpBinding

39. Toaddanewrowt oaDat


atable…
a. cal
ltheAddmet
hodoftheRowscollecti
onoftheDataSet
b. cal
ltheAddmet
hodoftheDataTabl
e
c. cal
ltheAddmethodoft
heRowscol lect
ionoftheDataTabl
e
d. cal
ltheAddmet
hodoftheDataSet

40.Restf
ulWCFser viceusest
hef
oll
owi
ngbi
ndi
ng
a.WsDuplexHt tpBi
nding
b.WsDualHttpBinding
c.WebHttpBinding
d.Basi
cHttpBinding
C# is a simple, modern and a general-purpose Object-oriented
programming language developed by Microsoft within its .NET framework.

Beginner’s Level
Q1. List down the differences between Public, Static and void
keywords?

Ans-

Keyword Description
It is an access specifier which states
Public that the method of a class can be
accessed publicly
It is a keyword used for declaring a
Static
member of a type, specific to that type
It states that the method does not
void
return any value
1
using System;
2class test
3{
4static void main(String args[])// main is the method that gets executed first
5{
6Console.Writeline("Welcome to the world of C#");
7}
8}
Q2. Define C# and list the features.

Ans- C# is an object-oriented, typed safe and manage


language that is compiled by .NET framework and was developed by Microsoft
back in 2000. The idea was that it will be used in the development of all kinds of
software aiming at different platforms like Windows, Web, mobile using only one
programming language. Fast forward to the present day it is one of the most
popular programming languages worldwide, millions of developers use this
language to build all kinds of software.
Some of the features of C#(sharp) are:

• Use of Constructors and Destructors


• Easy to grasp
• General Purpose and Object-Oriented
• Structured language
• Platform independent for compilation
• Part of .NET framework

Let’s move on to the next question,

Q3. List down the reason behind the usage of C# language.

Ans- There are several reasons for the usage of C# as a programming platform.
Some of them are listed below.

o Easy to pickup
o Component oriented language
o Follows a Structured approach
o Produces readable and efficient programmes
o Once written can be compiled on different platforms
o Passing parameters is easy

Q4. What are the advantages of using C#?

Ans- Following are the advantages of using C#:

o Easy to learn
o Object-Oriented language
o The syntax is easy to grasp
o Component oriented
o Part of the .NET framework

Q5. What are the different types of comments in C#?

Ans- Below listed are the types of comments followed in C#:

a. Single line comments

1// hello, this is a single line comment


b. Multiline comments

1/* Hello this is a multiline comment


2 last line of comment*/
c. XML comments

1/// Hello this is XML comment


Q6. Illustrate the process of code compilation in C#?

Ans- There exist four steps in the process of code compilation:

a. Compilation of Source code in managed code


b. Clubbing the newly created code into assembly
c. Loading the CLR (Common Language Runtime)
d. Execution of assembly through CLR

Q7. List down the access modifiers available in C#.

Ans- Following are the access modifiers available for general use:

• Public- When an attribute or method is defined as public it can be accessed


from any part of code.
• Private- A private attribute or method can be accessed from within the
class itself.
• Protected- When a user defines a method or attribute as protected then it
can be accessed only within that class and the one inheriting the class.
• Internal- When an attribute or method is defined as internal then it will be
accessed from that class at the current assembly position.
• Protected Internal- When you define an attribute or method as protected
internal, then it’s access restricted to classes within the current project
assembly or different types defined by that class.

Moving ahead in C# Interview questions, let’s unfold some functionalities used in


C#.

Q8. List down the different IDE’s Provided by Microsoft for C#


Development.

Ans- Below listed are few IDE’s for C# development:

• Visual Studio Express (VCE)


• Visual Studio (VS)
• Visual Web Developer
• MonoDevelop
• browxy

Q9. Distinguish between Continue and Break Statement?


Ans- Using break statement you can ‘jump out’ of the loop whereas while
making use of continue statement you can jump over an iteration and continue
the loop execution.

Example (Break Statement):

1
2using System;
3using System.Collections;
4using System.Linq;
5using System.Text;
6
7namespace break_example{
8Class break_Stmnt{
9public static void main(String args[]){
10for(int i=0;i<=6;i++)
{
11
if(i==5)
12{
13break;
14}
15Console.Readline("The number is +i");
16}
17}
18}
Output:

the number is 0;
the number is 1;
the number is 2;
the number is 3;
the number is 4;

Example (Continue Statement):

1using System;
2using System.Collections;
3using System.Linq;
4using System.Text;
5
namespace continue_example{
6
Class continue_Stmnt{
7public static void main(String args[]){
8for(int i=0;i<=6;i++)
9{
10if(i==5)
11{
12continue;
13}
14Console.Readline("The number is +i");
15}
16}
17}
18
Output:

the number is 0;
the number is 1;
the number is 2;
the number is 3;
the number is 5;

Q10. What are the different approaches of passing parameters to a


method?

Ans- There are three ways of passing parameters to a method:

Value Parameters- Under this method the actual value of an argument is copied
to the formal parameter of the function. In, this case the changes made into the
formal parameter of the function have no effect on the actual value of the
argument.

Reference Parameters- This method copies the argument referring to the


memory location into the formal parameter. Meaning changes made to the
parameter affect the argument.

Output Parameters- This method returns more than one value.

Let’s move ahead in C# Interview Questions and see the next category.

Intermediate level C# Interview Questions


Q11. Distinguish between finally and finalize blocks?

Ans- finally block is called after the execution of try and catch blocks, It is used for
exception handling whether or not the exception has been caught this block of
code gets executed. Generally, this block of code has a cleaner code.

The finalize method is called just before the garbage collection. Main priorities are
to perform clean up operation for unmanaged code, it is automatically invoked
when an instance is not subsequently called.

Q12. What is Managed or Unmanaged Code?


Ans- Managed code is one which is executed by CLR (Common Language
Runtime) in simple terms it means all the application code is dependent on the
.NET platform, considered as overseen in view of them. Unmanaged code is any
code that is executed by runtime application of some other structure different
from .NET platform. The runtime of application will deal with memory, security
and other execution activities.

Q13. What is an Object?

Ans- Object is an instance of a class, It is used for accessing the methods of a class.
“New” keyword is used for the creation of an object, a class that creates an object
in the memory location contains the information about methods, variables, and
behavior of that class.

To know more about Object in Java, Python, and C++ you can go through the
following blog:

• Java Object
• Python Object
• C++ Object

Q14. What is a Class?

Ans- A class is a blueprint of an object. It defines different kinds of data and


functionalities objects will have. A class enables you to create your own custom
types by clubbing together variables of different types, methods, and events. In
C# a class is defined by a class keyword.

To know more about Class in Java, Python, and C++ you can go through the
following blog:

• Java Class
• Python Class
• C++ Class

Q15. Define an abstract class?

Ans- It is a type of class whose objects can’t be instantiated, It contains something


like a single approach or technique and indicated by the keyword ‘abstract’.

To know more about abstract class in Java you can go through the following
blog:

• Java abstract class


Q16. Define sealed classes in C#?

Ans- You create sealed classes in situations when you want to restrict the class to
be inherited. For doing this sealed modifiers are used. If you forcefully specify a
sealed class as a base class then a compilation error occurs.

Q17. Define a Partial class?

Ans- A partial class is the only one that essentially splits the definition of a class
into multiple classes in either same source code files or multiple source code files.
One can create a class definition in multiple files but that is compiled as one class
at run-time and when an instance of this class is created, one can access all
methods from every source file with the same object. It is indicated by the
keyword ‘partial’.

Q18. List down the fundamental OOP concepts?

Ans- There are four fundamental OOP (Object Oriented Programming) concept
they are listed as follows:

• Inheritance- Ever heard of this dialogue from relatives “you look exactly
like your father/mother” the reason behind this is called ‘inheritance’.
From the Programming aspect, It generally means “inheriting or transfer
of characteristics from parent to child class without any modification”. The
new class is called the derived/child class and the one from which it is
derived is called a parent/base class.
• Polymorphism- You all must have used GPS for navigating the route, Isn’t
it amazing how many different routes you come across for the same
destination depending on the traffic, from a programming point of view this
is called ‘polymorphism’. It is one such OOP methodology where one task
can be performed in several different ways. To put it in simple words, it is a
property of an object which allows it to take multiple forms.
• Encapsulation- In a raw form, encapsulation basically means binding up of
data in a single class.A class shouldn’t be directly accessed but be prefixed
in an underscore.
• Abstraction- Suppose you booked a movie ticket from bookmyshow using
net banking or any other process. You don’t know the procedure of how
the pin is generated or how the verification is done. This is called
‘abstraction’ from the programming aspect, it basically means you only
show the implementation details of a particular process and hide the
details from the user. It is used to simplify complex problems by modeling
classes appropriate to the problem.An abstract class cannot be instantiated
which simply means you cannot create objects for this type of class. It can
only be used for inheriting the functionalities.

To know more about OOPs in Java, Python, and C++ you can go through the
following blogs:

• Java OOPs
• Python OOPs
• C++ OOPs

Q19. Explain the process of inheriting a class into another class?

Ans- Colon is used as an inheritance operator in C#. Place the colon and the class
name.

1public class Derivedclass: childclass


Q20. Define method overloading in C#?

Ans- Method overloading essentially is creating multiple methods with the same
name and unique signatures with the same class. When you
compile, the compiler makes use of overload resolution to determine the specific
method which will be invoked.

Q21. List the differences between method overriding and method


overloading?

Ans- Under Method overriding the definition of the derived class is changed which
in turn changes the method behavior. Method overloading is simply creating a
method with the same name under the same class under different signatures.

Q22. Explain StreamReader/StreamWriter class?

Ans- Streamreader and StreamWriter are classes of namespace.System.IO. Used


when we want to read or write charact90, Reader based data,
respectively.

members of StreamReader are: close(), Read(), Readline().


members of Streamwriter are: close(), write(), writeline().

Example program:

1Class Testprogram
2{
3using(StreamReader sr = new StreamReader("C:Readme.txt")
4{
5// Any code to read//
6}
7using(StreamWriter sr = ndew StreamWriter("C:Readme.txt")
8{
9// Any code to write//
10}
}
11
Q23. What is an Interface?

Ans- An Interface is basically a class with no implementation. It contains only the


declaration of properties, attributes, and events.

Q24. Distinguish between a class and struct?

Ans- Given below are the differences between a class and struct:

Class Struct
It supports inheritance It does not support inheritance
It is Pass by reference It is pass by value
Members are private by default Members are public by default
Considered good for larger complex
Considered good for small models
objects
Q25. List the difference between the Virtual method and the
Abstract method?

Ans- A Virtual method must always have a default implementation. However, it


can be overridden in a derived class by the keyword override.

An Abstract method doesn’t have any implementation. It resides in the abstract


class, and also it is mandatory that the derived class must implement abstract
class. Use of override keyword is not necessary.

Q26. Illustrate Namespaces in C#?

Ans- Namespaces are used for organizing large code projects. “System” is one of
the most popular and widely used namespaces in C#. One can create their own
namespace and use one into another called nesting.

Q27. Define using statement in C#?

Ans- “Using” keyword simply denotes that the particular namespace is being used
by the program. For ex- using System, Here System is a namespace. The class
console is defined under system, so we can use the Console.Writeline(…) or
Readline in our program.

Q28. Define an Escape Sequence, Name few strings in Escape


Sequence?

Ans- An Escape Sequence is denoted by a backslash (). The backslash merely


indicates that the character it is following should be interpreted literally or is a
special character. An escape sequence is a single character.

Few escape sequences are as follows:

n – newline character

b – backspace

– backlash

‘ – Single quote

” – Double quote

Q29. Define Boxing and Unboxing in C#?

Ans- Converting a value type to the reference type is called boxing.

Example:

1int value = 10
2//-------Boxing--------//
3object boxedvalue = value1;
Explicit conversion of the same reference type i.e. converting it back to the value
type is called Unboxing.

Example:

1//----------------Unboxing-------// int UnBoxing = int(boxedvalue);


To know more about Boxing and Unboxing in Java you can go refer this
article- Boxing in Java.

Q30. Define an array?

Ans- An array is used to store multiple variables of the same type. Collection of
variables stored in a contiguous memory location.
Example:
double numbers = new double[10];
int[] Score = new int[4] {25,24,23,22,21,20}

Above given example above is of a Single Dimensional array. It is a linear array


where values are stored in a single row. A multidimensional array is the one
having more than one dimension. A good example would be of a rectangle.

Example:

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

To know more about arrays in Java, Python , and C++ you can go through the
following blogs:

• Python array
• Java array
• C++ array

Q31. Define a Jagged Array in C#?

Ans- A Jagged array is referred to as an “array of arrays”. It is an array whose


elements are arrays, the element of the same can be of different dimensions and
sizes. The length of each array index can differ.

Example:

int[][] jagArray = new int[5][];

Q32. Distinguish between Array and Arraylist in C#?

Ans-

Array ArrayList
Array uses the vector array for storing ArrayList uses the LinkedList to store
the elements the elements
Size of the Array must be defined until There’s no need for specifying storage
redim used(vb) size.
ArrayList can store everything as an
An array is a specific data type storage
object
Typecasting is not necessary Typecasting is necessary
There is no RunTime exception There is a RunTime error exception
Elements can’t be inserted or deleted Elements can be inserted or deleted in
in between between
Q33. Define Collections?

Ans- A collection essentially works like a container for instances of other classes.
Every class implements Collection Interface.

To know more about collections in Java, check out the following blog:

• Java Collections

Q34. Write a short note on Interface?

Ans- An Interface is a class with no implementation. It consists of a declaration of


methods, Parameters, and values.

To know more about Interface in Java, check out the following blog:

• Java Interface

Moving on in C# Interview Question let’s see the next category.

Advance Level
Q35. Illustrate Serialization?

Ans- A process that involves converting some code into its binary format is known
as a serialization in C#. In doing so it gives the flexibility where code can be stored
easily and or written to a disk or some other storage device. Serialization is used
when there is a strict need for not losing the original code.

Serialization in C# is of three types:

Binary Serialization- It is fast and demands less space, converts any code into its
binary format. Serialize and restore public and non-public properties.

SOAP- Generates a complete SOAP compliant envelope used by any system by its
ability to understand SOAP. Classes under this type of Serialization reside
in System.Runtime.Serialization.

XML Serialization- It serializes all the public properties to XML document.


Readability being one factor, an XML document can also be manipulated in
various ways. Classes under this type reside in System.sml.Serialization.
To know more about Serialization in Java, check out the following blog:

• Java Serialization

Q36. Define Parsing? Explain how to Parse a DateTime String?

Ans- Parsing is a method of converting a string into another data type.

Example:

1string text = "200";


2int num = int.Parse(text);
In the above-given example, 200 is an integer. So, the Parse method converts the
string 200 into its own base type, i.e. int.
To parse a DateTime String let’s see a small example.

Example:

1string dateTime = "Aug 26,2019"; Datetime parsedvalue = Datetime.Parse(dateTime);


Q37. Define Delegate?

Ans- Delegate is a variable that holds the reference to a method. It is a function


pointer of the reference type. All Delegates are derived from the
System.Delegate namespace. Both Delegate and the method that it refers to can
have the same signature. Let’s see a small example.

Example:

1
2public Delegate int myDel(int number); //declaring a delegate
3public class Program
4{
5public int SubstractNumbers(int a) //Class Program has the method same signature as delegate
{
6
int difference = a - 10;
7return difference;
8}
9public void start()
10{
11myDel DelegateExample = SubstractNumbers;
12}
13}
Q38. Distinguish between System.String and
System.Text.StringBuilder classes?

Ans – System.String is immutable. Whenever you modify the value of a string


variable then a new memory is allocated to the new value and previous memory
allocation is released. System.Text.StringBuilder is mutable i.e. supports the fact
that a variety of operations can be performed
without allocating a seperate memory location for the already modified string.

Q39. Illustrate the differences between the System.Array.CopyTo() and


System.Array.Clone()?

Ans – Using the Clone() method, a new array object is created containing all
elements of the original array. Using the CopyTo() method all the elements of the
existing array gets copied into another existing array. Both use a shallow copy
method.

Q40. Write the Syntax for catching an exception in C#?

Ans – To catch an Exception we make use of try-catch blocks. The catch block has
a parameter of the system.Exception type.

Example:

1try
2{
3GetAllData();
4}
5catch(Exception ex){
6}
Q41. Explain about generics in C#.NET?

Ans- Generics are used to make reusable code classes which decrease the code
redundancy,

• Increase type safety, performance, and optimization


• Using Generics one can do a variety of things like create collections
• To create Generic collection, System.namespace
• The generic namespace should be used inspite of classes such as ArrayList
in the System
• Generics instigates the usage of a parameterized type

Q42. List down the differences between “dispose” and “finalize”


methods in C#.

Ans- Dispose() is called when we want an object to release unmanaged resources


with them. Whereas, Finalize() is used for the same purpose but
it doesn’t assure garbage collection of an object.
Q43. Define C# I/O classes? List the commonly used classes?

Ans- C# consists of System.IO namespace which has classes that compute and
perform various operations on files like creating, deleting, opening
and closing etc.

Few commonly used I/O classes are listed below:

File- Helps in manipulating file.


StreamWriter- Generally used for writting characters to a stream.
StreamReader- Generally used for reading characters to a stream.
StringWriter- Used for writing a string buffer.
Stringreader- Used for reading a string buffer.

Q44. Define thread? Explain about Multithreading?

Ans- Thread is a set of instructions that when executed enables the program to
perform concurrent processing. Concurrent processing helps in doing more than
one process at a time. By default, C# consists of only thread. Other threads can
be created to execute the code in parallel with original thread.

Thread follows a life cycle where it starts whenever a thread is created and gets
terminated immediately after the execution. The namespace it follows
is System.Threading which has to be included to create threads and use its
members.

Threads are created by extending the thread class. Start() method marks the
beginning of the thread execution.

1//callThread is our target method//


2ThreadStart methodThread = new ThreadStart(CallThread);
3Thread childThread = new Thread(methodThread);
4childThread.start();
C# can also execute more than proceeses/task at a time which is done by handling
different processes at different time labeled as “multithreading”.
Several operations of the same are listed below:

• Start
• Sleep
• Abort
• Suspend
• Resume
• Join
Q45. What are Events?

Ans- Events in C# follow a concept where it consists of a Publisher, Subscriber,


Notification and a handler. You can think of an event as nothing but an
encapsulated delegate.

Example:

1public Delegate void TestEvent();


2public TestEvent TestEvent1;
Q46. Explain Synchronous and Asynchronous Operations?

Ans- Synchronization is a way of creating a thread-safe code where only a single


thread will access the code in a given time. A synchronous call waits for
completion of method and then continous the program flow. Synchronous
programming adversely affects the UI operations that normally happens when
user tries to perform time-consuming operations since only one thread is used.

In Asynchronous operation, the method call immediately returns allowing the


program to perform other operations while the method called completes its
share of work in certain circumstances.

Q47. Explain Async and Await?

Ans- Async and Await keywords are mostly used for creating asynchronous
methods in C#. Usage of the same is shown through an example:

1
2public async Task>CalculateCount()
{
3
await Task.Delay(2000);
4return 1;
5}
6public async task mytestmethod()
7{
8Task> count = CalculateCount();
9int result = await count;
10}
In the above-given code async keyword is used for method declaration. The Count
is of a task type int which calls the method CalculateCount(). CalculateCount()
starts execution and calculates something.

Q48. Explain Deadlock?

Ans- A deadlock is a situation that arises when a process isn’t able to complete it’s
execution because two or more than two processes are waiting for each other to
finish. This usually occurs in multi-threading. In this, a shared resource is being
held up by a process and another process is waiting for the first process to get
over or release it, and the thread holding the locked item is waiting for another
process to complete.

Q49. Illustrate Race Condition?

Ans- A Race Condition occurs in a situation when two threads access the same
resource and try to change it at the same time. The thread which accesses the
resource first cannot be predicted. Let me take a small example where two
threads X1 and X2 are trying to access the same shared resource called T. And if
both threads try to write the value to T, then the last value written to T will be
saved.

Q50. What is Thread Pooling?

Ans- A Thread pool is a collection of threads that perform tasks without disturbing
the primary thread. Once the task is completed by a thread it returns to the
primary thread.

This brings us to the end of this article on C# Interview Questions. I hope it helped
in adding up to your knowledge. Wishing you all the best for your interview. Happy
learning.

In case you are looking for the most common Technical Interview Questions,
read along:

• OOPs Interview Questions


• MVC Interview Questions
• SQL Interview Questions
• Java Interview Questions
• Python Interview Questions

Check out the online training by Edureka, a trusted online learning company with a
network of more than 250,000 satisfied learners spread across the globe. We are here
to help you with every step on your journey through our online certification training.

Got a question for us? Please mention it in the comments section of this “C#
Interview Questions” article and we will get back to you as soon as possible.

You might also like