You are on page 1of 122

.

Net Framework

1. SOILD Principle

SOLID are five basic principles which help to create good software architecture. SOLID is an acronym
where:-

SOILD is an acronym for five principle of architecture.

S-Single responsibility principle

O-Open close Principle

L-Liskov substitution principle

I-Interface segregations Principle

D-Dependency Inversion principle

Single Responsibility Principle-it says that every class should have single responsibility. A class
should not have more than one reason to change.

Example
1. Asp.net MVC HomeController class should be responsible related to Home Page functionality of
software system.
Suppose, you have created a class XmlValidator for XML validation, which has the responsibility to
validate XML.

If there is a need to update XML, then a separate class should be created for the same. XmlValidator
class should not be used for updating XML.

1. public class XmlValidator


2. {
3.
4. public void Validate()
5. {
6.
7.
8. }
9.
10. }

For updating a new class, it should be created.

1. public class XmlUpdate


2. {
3.
4. public void DoUpdate()
5. {
6.
7.
8. }
9.
10.
11. }

Open Close Principle- A class should be open for an extension and closed for the modification.

1. In detail, We can extend any class via Interface, Inheritance or Composition whenever it's
required instead of opening a class and modifying it's code.
For example, suppose you have implemented a functionality to calculate area of Rectangle and after
some time you need to calculate the area of Square, then In this case you should not modify your
original class code to add extra code for square. Instead you should create one base class initially
and now you should extend this base class by your square class.

2. Example

Suppose, we have a class name Customer, which has a property InvoiceNumber, which has an
integer type

public class Customer {

public int InvoiceNumber {

get;
set; }

In the future, if the requirement changes now, InvoiceNumber should be alphanumeric rather than
only an integer. Hence, in this case, you should create a subclass CustomerNew with a same
property but different datatype rather than modifying the previous one.

public class CustomerNew : Customer


{

public new String InvoiceNumber


{
get;
set;

}
}

Liskov Substitution Principle (LSP)

A parent object should be able to replace its child during runtime polymorphism.

In other words, if A is subtype of B then instances of B may be replaced by the instances of A without
altering the program correctness.
Interface Segregation Principle (ISP)
Client specific interfaces are better than general purpose interfaces.
In other words No client should be forced to implement other methods which it does not require. It
means it's better to create a separate interface and allow your classes to implement multiple
interfaces.
Suppose, we have one interface for clicking.
public interface IClick{
void onClick(Object obj);
}

As time passes, new requirement comes for adding one more function onLongClick. You need to add
this method in already created interface.

public interface IClick{


void onClick(Object obj);
void onLongClick(Object obj);
}

After some time, one new requirement comes for adding function for touch also and you need to
add the method in the same interface

public interface IClick{


void onClick(Object obj);
void onLongClick(Object obj);
void onTouch(Object obj);
}

At this point, you need to decide to change the name of interface too because touch is different than
click.

In this way, this interface becomes a problem—generic and polluted. At this stage, ISP comes into
play.

Why Generic Interface creates problem?

Suppose, some clients need only onClick function and some need only onTouch function, then one
will be useless for both. Hence ISP gives the solution, which splits the interface into two interfaces.

ITouch and IClick. The client which has required onClick can implement IClick, which needs onTouch.
It can implement ITouch and when it needs both, it can implement both.

public interface IClick{


void onClick(Object obj);
void onLongClick(Object obj);
}

public interface ITouch{


void onClick(Object obj);
void onTouch(Object obj);
}
Dependency Inversion Principle (ISP)
It states two points, where the first point is a higher level module, which should not depend on a low
level module. Both should depend on abstraction. The second point is abstraction, which should not
depend on detail.
Detail should depend on abstraction.
In other words, no object should be created inside a class. They should be passed or injected from
outside. When it is received, it will be an interface rather than a class.

Here is a bad design without using Dependency Injection.


class Student
{
// Handle to EventLog writer to write to the logs
LogWriter writer = null;
// This function will be called when the student has problem
public void Notify(string message)
{
if (writer == null)
{
writer = new LogWriter();
}
writer.Write(message);
}
}

This is also a bad design.

class Student
{
// Handle to EventLog writer to write to the logs
LogWriter writer = null;
Public Student(LogWriter writer)
{

This.writer = writer;
}
// This function will be called when the student has problem
public void Notify(string message)
{
writer.Write(message);
}
}

The written classes given above are bad designs because in the case of a change in LogWrite, you
have to disturb Student class. We should use an interface inside Student instead of a class.

With Dependency Injection, the code is given, as shown below.

class Student
{
// Handle to EventLog writer to write to the logs
ILogWriter writer = null;
Public Student(ILogWriter writer)
{

This.writer = writer;
}
// This function will be called when the student has problem
public void Notify(string message)
{
writer.Write(message);
}
}

How Design Principles are different from Design Patterns?

 Design Principles are the core principles which we are supposed to follow while designing
any software system on any platform using any programming language. Examples of Design
Principles:
o Dependency on abstraction not concrete classes
o Encapsulate that varies
o Program to interfaces not implementations
 Design Patterns are the solutions to common occurring general problems, they are not exact
program that can be fit to solve your problem rather you need to customize according to
your problem. Design Patterns are already invented solutions which are well tested and safe
to use. Examples of Design Patterns:
o Single Design Pattern: When you want only one instance of a class.
o Repository Design Pattern: To separate different layers of application (Business
Repository, Data Repository)

SRP – What is mean by “module” and “Reason to change” in explanation?


Module - May be class, function, namespace
Reason to change – Responsibility.
Every Modules should contain only one responsibility. Here the word responsibility depends on the
context where we are talking like, when we say module as class responsibility indicates “database
responsibility”, “reporting responsibility” etc., when we say module as function it indicates
“Generating xml from list”, “using generated xml for inserting multiple records into sql”.

OCP – Can you name some techniques using which we can expose new functionality to client
without touching existing code?
There are various ways achieving it. Some are,

 Using Extension methods in .net 3.5


 By creating derived classes

2. Garbage collector
Garbage collector is a feature of CLR which cleans unused managed (it does not clean
unmanaged objects) objects and reclaims memory. It’s a back ground thread which runs
continuously and at specific intervals it checks if there are any unused objects whose memory
can be claimed

When program start system allocated some memory for program to get executed.
There are 2 places in memory where the CLR stored items
1. Stack -Keep track what executing in your code(like your local variable)

2. Heap-keeps track of your object

Value types can be stored on both the stack and the heap.
For an object on the heap, there is always a reference on the stack that points to it.
The garbage collector starts cleaning up only when there is not enough room on the heap to
construct a new object
The stack is automatically cleared at the end of a method. The CLR takes care of this and you don’t
have to worry about it.
The heap is managed by the garbage collector.

What are generations in Garbage collector (Gen 0, 1 and 2)?

Generations defines age of the object. There are three generations:-

 Gen 0:- When application creates fresh objects they are marked as Gen 0.it stored short lived
object like temp variable.Grabage collector occurs must frequently in this generation

 Gen 1:- When GC is not able to clear the objects from Gen 0 in first round it moves them to Gen
1 bucket.

 Gen 2:- When GC visits Gen 1 objects and he is not able to clear them he moves them gen 2.
This generation contains long-lived objects. An example of a long-lived object is an object in a
server application that contains static data that is live for the duration of the process.

Generations are created to improve GC performance. Garbage collector will spend more time on
Gen 0 objects rather than Gen 1 and Gen 2 thus improving performance.

Generation 0 – Short-lived Objects


Generation 1- As a buffer between short lived and long lived objects
Generation 2 – Long lived objects

Garbage collector cleans managed code then how do we clean unmanaged code?

Garbage collector only claims managed code memory. For unmanaged code you need to put clean
up in destructor / finalize.

Can we force garbage collector to run?

“System.GC.Collect ()” forces garbage collector to run. This is not a recommended practice but can
be used if situations arise.
and using statement
when we create a destructor the performance falls down?
Yes, when we define a destructor, garbage collector does not collect these objects in the first round.
It moves them to Gen 1 and then reclaims these objects in the next cycle.

As more objects are created in Gen 1 the performance of the application falls down because more
memory is consumed.

Garbage collection Method

1. GC.GetGenteration -This method returns the generation number of the target object. It required
single parameter i.e the target object of which generation number is required.

using System;

public class Demo {

public static void Main(string[] args)


{
Demo obj = new Demo();
Console.WriteLine("The generation number of object obj is: "
+
GC.GetGeneration(obj));
}
}
2. GC.GetTotalMemory method
This method returns the number of bytes that are allocated in the system. It requires a single
boolean parameter where true means that the method waits for the occurrence of garbage
collection before returning and false means the opposite.

using System;

public class Demo {

public static void Main(string[] args)


{
Console.WriteLine("Total Memory:" + GC.GetTotalMemory(false));

Demo obj = new Demo();

Console.WriteLine("The generation number of object obj is: "


+
GC.GetGeneration(obj));

Console.WriteLine("Total Memory:" + GC.GetTotalMemory(false));


}
}

3. GC.Collect method –
Garbage collection can be forced in the system using the GC.Collect() method. This method
requires a single parameter i.e. number of the oldest generation for which garbage collection
occurs

using System;

public class Demo {

public static void Main(string[] args)


{
GC.Collect(0);
Console.WriteLine("Garbage Collection in Generation 0 is: "
+
GC.CollectionCount(0));
}
}
Dispose Vs Finalize

Garbage collector (GC) plays the main and important role in .NET for memory management so
programmer can focus on the application functionality. Garbage collector is responsible for releasing
the memory (objects) that is not being used by the application. But GC has limitation that, it can
reclaim or release only memory which is used by managed resources. There are a couple of
resources which GC is not able to release as it doesn't have information that, how to claim memory
from those resources like File handlers, window handlers, network sockets, database connections
etc. If your application these resources than it's programs responsibility to release unmanaged
resources. For example, if we open a file in our program and not closed it after processing than that
file will not be available for other operation or it is being used by other application than they cannot
open or modify that file.

So Dispose and Finalize will be used to release unmanage object that is not in used.

Dispose() Method

- This dispose method will be used to free unmanaged resources like files, database connection
etc.
- To clear unmanaged resources we need to write code manually to raise dispose() method.
This Dispose() method belongs to IDisposable interface.
- If we need to implement this method for any custom classes we need to inherit the class from
IDisposable interface.
- It will not show any effect on performance of website and we can use this method whenever we
want to free objects immediately.

//Implement Dispose Method.


public class TestDispose : IDisposable
{
private bool disposed = false;

//Implement IDisposable.
public void Dispose()
{
Dispose(true);
}

protected virtual void Dispose(bool disposing)


{
if (!disposed)
{
if (disposing)
{
// clean unmanged objects
}
// clean unmanaged objects).

disposed = true;
}
}
}

Finalize() Method

- This method also free unmanaged resources like database connections, files etc…
- It is automatically raised by garbage collection mechanism whenever the object goes out of
scope.
- This method belongs to object class.
- We need to implement this method whenever we have unmanaged resources in our code and
make sure these resources will be freed when garbage collection process done.
- It will show effect on performance of website and it will not suitable to free objects
immediately.
- Finalize method can not be called explicitly in the code. Only Garbage collector can call the the
Finalize when object become inaccessible. Finalize method cannot be implemented directly it can
only be implement via declaring destructor
Example

// Implementing Finalize method


public class Sample
{
//At runtime destructor automatically Converted to Finalize method.
~Sample()
{
// your clean up code
}
}

4. CLR(Common Language Runtime)


It is the hard of the .net framework. It manage the Lifecyle and execution on the .net
program writing in any language that use the .net framework(C#,VB,F# etc.)
First, the developer has to write the code using any dot net supported programming languages such
as C#, VB, J#, etc. Then the respective language compiler will compile the program into something
called Intermediate language (IL) code. For example, if the programming language is C#, then the
compiler is CSC and if the programming language is VB, then the compiler will be VBC. This
Intermediate Language (IL) code is half compiled code i.e. partially compiled code and cannot be
executed directly by the operating system. So, when you want to execute this IL code on your
machine, the dot net framework provides something called CLR or Common Language Runtime
which takes the responsibility to execute your IL Code.
The CLR takes the IL (Intermediate Language) code and gives it to something called JIT (Just-in-Time)
Compiler. The JIT compiler takes the IL code and reads each and every line of the IL code and
converts it to machine-specific instructions (i.e. into binary format) which can be executed by the
underlying operating system.

Functions of .NET CLR

 Convert code into CLI


 Exception handling
 Type safety
 Memory management (using the Garbage Collector)
 Security
 Improved performance
 Language independency
 Platform independency
 Architecture independency

Why Partial Compiled Code or why not fully compiled Code?


As a developer, you may be thinking about why partially compiled code or why not fully compiled
code. The reason is very simple. We don’t know in what kind of environment .NET Code will run (for
example, Windows XP, Windows 7, Windows 10, Windows Server, etc.). In other words, we don’t
know what operating system is going to run our application; we also don’t know the CPU
configuration, machine configuration, security configuration, etc. So, the IL code is partially compiled
and at runtime, this IL code is compiled to machine-specific instructions using environmental
properties such as OS, CPU, Machine Configuration, etc.

5. CTS(Common Type System)


The .net framework support different languages like C#,VB.J#. Every programming language has
its own data types. One programming languages cannot understand other programming
language . but same situation we want call one language code in other language.

So CLR will contains its own data type which is common to all programming language.

At the time of compilation, all language specific data types are convert into CLR data types. This
data type system of CLR which is common to all programming language of .net is call CTS.

C#

StringBuilder and String

String is immutable, Immutable means if you create string object you cannot modified it. and It
always create new object of string type in memory.

Stringbuilder

StringBuilder is mutable, means if create string builder object then you can perform any
operation like insert, replace or append without creating new instance for every time.it will
update string at one place in memory doesn’t create new space in memory.

We create stringBuilder class using new keyword and passing in initials string.

using System.Text; // include at the top

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


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

Append and AppendLine in StringBuilder


Use the Append() method to append a string at the end of the current StringBuilder object.
he AppendLine() method append a string with the newline character at the end.

Example: Adding or Apending Strings in StringBuilder

StringBuilder sb = new StringBuilder();


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

Output:

Hello World!
Hello C#.

https://www.tutorialsteacher.com/csharp/csharp-stringbuilder

Constructor in c#
It is the special type of method of class that automatically executed whenever we create
instance of the class.

Rules to follow while creating the C# Constructors:


1. The constructor name should be the same as the class name.
2. It should not contain return type even void also.
3. The constructor should not contain modifiers.
4. As part of the constructor body return statement with value is not allowed.
What a Constructor have in C#?
1. It can have all five accessibility modifiers.
2. The constructor can have parameters.
3. It can have throws clause it means we can throw an exception from the constructor.
4. The constructor can have logic, as part of logic it can have all C#.NET legal statements except
return statements with value.
5. We can place a return; in the constructor.
6.
Can we define a method with the same class name in C#?
No, it is not allowed to define a method with the same class name in C#. It will give you a compile-
time error.

Types of constructor in C#

1. Default Constructor-without parameter call default constructor.


 User-define default constructor -define by user
 System Define default constructor-if not define by user the system will provide.
2. Parameter constructor
3. Copy constructor
4. Static constructor
5. Private constructor

Note: The point that you need to keep in mind is that the System will only provide the default
constructor if as a programmer you are not defined any constructor explicitly.

When do we need to provide the constructor explicitly?


If you want to execute some logic at the time of object creation, that logic may be object
initialization logic or some other useful logic, then as a developer, we must provide the constructor
explicitly.

Draw back of Default constructor


Every instance of the class it is initialize with same value and it is not possible to initialize each
instance of the class to different values.

Parameter constructor

When should we define a parameterized constructor in a class?


If you want to initialize the object dynamically with the user-given values then you need to use the
parameterized constructor. The advantage is that you can initialize each object with different values.
What is Parameterized Constructor in C#?
With the help of a Parameterized constructor, we can initialize each instance of the class with
different values. That means using parameterized constructor we can store a different set of values
into different objects created to the class.

We can define many constructor in class with different signature

Copy Constructor

The constructor which take parameter of the class type is called a copy constructor. This constructor
is used to copy one object’s data into another object. The main purpose of the copy constructor is to
initialize a new object (instance) with the values of an existing object (instance).

namespace ConstructorDemo
{
class Employee
{
int eid, age;
string address, name;
public Employee()
{
Console.WriteLine("ENTER EMPLOYEE DETAILS");
Console.WriteLine("Enter the employee id");
this.eid = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the employee age");
this.age = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the employee name");
this.name = Console.ReadLine();
Console.WriteLine("Enter the employee address:");
this.address = Console.ReadLine();
}
public Employee(Employee tempobj)
{
this.eid = tempobj.eid;
this.age = tempobj.age;
this.name = tempobj.name;
this.address = tempobj.address;
}
public void Display()
{
Console.WriteLine();
Console.WriteLine("Employee id is: " + this.eid);
Console.WriteLine("Employee name is: " + this.name);
Console.WriteLine("Employee age is: " + this.age);
Console.WriteLine("Employee address is: " + this.address);
}
}
class Test
{
static void Main(string[] args)
{
Employee e1 = new Employee();
Employee e2 = new Employee(e1);
e1.Display();
e2.Display();
Console.ReadKey();
}
}
}

Static Constructor

We can create a constructor as static and when a constructor is created as static, it will be invoked
only once. There is no matter how many numbers of instances (objects) of the class are created but
it is going too invoked only once and that is during the creation of the first instance (object) of the
class.
The static constructor is used to initialize static fields of the class and we can also write some code
inside the static constructor that needs to be executed only once.

1. There can be only one static constructor in a class.


2. The static constructor should be without any parameter.
3. It can only access the static members of the class.
4. There should not be any access modifier in the static constructor definition.
5. If a class is static then we cannot create the object for the static class.
6. Static constructor will be invoked only once i.e. at the time of first object creation of the
class, from 2nd object creation onwards static constructor will not be called.

Private constructor

The constructor whose accessibility is private is known as a 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.

private constructors are used in class that contains only static members.

How private constructor invoke within class?

When class initialize private constructor will invoke.

How private constructor invoke outside class?

Another way of accessing a private constructor is by creating a public static method within
this class and have its return type as its object. Yes, we can access the private constructor or
instantiate a class with private constructor.

IMP- https://www.geeksforgeeks.org/private-constructors-in-c-sharp/

Give 2 scenarios where static constructors can be used?


A typical use of static constructors is when the class is using a log file and the constructor is used to
write entries to this file. Static constructors are also useful when creating wrapper classes for
unmanaged code when the constructor can call the LoadLibrary method.
https://dotnettutorials.net/lesson/constructor-interview-questions-answers-csharp/

What is the Struct

In C#, a structure is a value type data type. 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 contain a
parameterized constructor, static constructor, constants, fields, methods, properties, indexers,
operators, events, and nested types.struct can be used to hold small data values that do not require
inheritance, e.g. coordinate points, key-value pairs, and complex data structure.

public struct SubventionData


{
public string Type;
public int StartDay;
public int EndDay;
public double Rate;
public string Component;
public string Party;

What do we use struct in C#

In C#, a structure is a value type data type. It helps you to make a single variable hold related data of
various data types. The struct keyword is used for creating a structure.

Difference between Class and Structure


Class Structure

Classes are of reference types. Structs are of value types.

All the reference types are allocated on heap


memory. All the value types are allocated on stack memory.

Allocation of large reference type is cheaper Allocation and de-allocation is cheaper in value type as
than allocation of large value type. compare to reference type.

Class has limitless features. Struct has limited features.

Class is generally used in large programs. Struct are used in small programs.
Structure does not contain parameter less constructor or
destructor, but can contain Parameterized constructor or
Classes can contain constructor or destructor. static constructor.

Classes used new keyword for creating Struct can create an instance, with or without new
instances. keyword.

A Struct is not allowed to inherit from another struct or


A Class can inherit from another class. class.

The data member of a class can be protected. The data member of struct can’t be protected.

Function member of the class can be virtual or Function member of the struct cannot be virtual or
abstract. abstract.

Two variable of class can contain the reference Each variable in struct contains its own copy of
of the same object and any operation on one data(except in ref and out parameter variable) and any
variable can affect another variable. operation on one variable can not effect another variable.

Sealed Class

A class from which it is not possible to create/derive a new class is known as sealed class. In simple
words, we can also define the class that is declared using the sealed modifier is known as the
sealed class and a sealed class cannot be inherited by any other class.

Points to Remember while working with Sealed Class


1. A sealed class is completely opposite to an abstract class.
2. This sealed class cannot contain abstract methods.
3. It should be the bottom-most class within the inheritance hierarchy.
4. A sealed class can never be used as a base class.
5. This sealed class is specially used to avoid further inheritance.
6. The keyword sealed can be used with classes, instance methods, and properties.
Note: Even if a sealed class cannot be inherited we can still consume the class members from any
other class by creating the object of the class.

If we don’t want to override method in sub class?

We will use new keyword to hide method or restrict overridden.

Sealed Method-

The method that is defined in a parent class, if that method cannot be overridden under a child class,
we call it a sealed method. By default, every method is a sealed method because overriding is not
possible unless the method is not declared as virtual in the parent class.
When should a method be declared as sealed in C#?
If we don’t want to allow subclasses to override the superclass method and to ensure that all sub-
classes use the same superclass method logic then that method should be declared as sealed.

What is the difference between the private and sealed method in C#?
The private method is not inherited whereas the sealed method is inherited but cannot be
overridden in C#. So, a private method cannot be called from sub-classes whereas sealed method
can be called from sub-classes. The same private method can be defined in sub-class and it does not
lead to error.
How the sealed class method constructor access?
Creating object of the class.

using System;
public class Animal{
public virtual void eat() { Console.WriteLine("eating..."); }
public virtual void run() { Console.WriteLine("running..."); }

}
public class Dog: Animal
{
public override void eat() { Console.WriteLine("eating bread..."); }
public sealed override void run() {
Console.WriteLine("running very fast...");
}
}
public class BabyDog : Dog
{
public override void eat() { Console.WriteLine("eating biscuits..."); }
public override void run() { Console.WriteLine("running slowly..."); }
}
public class TestSealed
{
public static void Main()
{
BabyDog d = new BabyDog();
d.eat();
d.run();
}
}
Partial Classes

A class in which code can be written in two or more files is known as a partial class. To make
any class partial we need to use the keyword partial. even physically they are divided but
logically it is one single unit only.

namespace PartialDemo
{
public partial class PartialEmployee
{
public void DisplayFullName()
{
Console.WriteLine(@"Full Name is : {0} {1}", _firstName, _lastName);
}
}
}
All the parts spread across different class files, must use the partial keyword. Otherwise, a compiler
error is raised. Missing partial modifier. Another partial declaration of this type exists.
All the parts spread across different files, must have the same access modifiers. Otherwise, a
compiler error is raised. Partial declarations have conflicting accessibility modifiers.

Partial Method

Partial method is private by default and it is giving complier error if include access modifiers.

partial class PartialClass


{
// Declaration of the partial method.
partial void PartialMethod();
}
}

Rules

6. Partial method declares in partial class only.


7. Partial methods are private by default and it is a compile-time error to include any access
modifiers, including private. The following code will raise an error stating – A partial method
cannot have access modifiers or the virtual, abstract, override, new, sealed, or extern
modifiers.
8. It is a compile-time error to include declaration and implementation at the same time for a
partial method. The code below produces a compile-time error – No defining declaration
found for implementing declaration of partial method
‘PartialDemo.PartialClass.partialMethod()’
9. A partial method return type must be void. Including any other return type is a compile-time
error – Partial methods must have a void return type
10. A partial method can be implemented only once. Trying to implement a partial method more
than once raises a compile-time error – A partial method may not have multiple
implementing declarations.

I have a class that is split into two partial classes. These two partial classes have the same
methods. What happens when we compile
At compile time all partial classes will be combined together to form a single final class. In the
same class, we cannot have multiple methods with the same name. But of course method
overloading possible.

If you do not specify an access modifier for a method, what is the default access modifier?
private
Classes and structs support inheritance. Is this statement true or false?
False, only classes support inheritance. structs do not support inheritance.
If a class derives from another class, will the derived class automatically contain all the public,
protected, and internal members of the base class?
Yes, the derived class will automatically contain all the public, protected, and internal members of
the base class except its constructors and destructors.

3. Can we have static method in partial classes ?

Yes, you can access static methods in partial classes. Partial classes are just a way of representing a
regular class in multiple source files, often with some of those source files controlled (or generated)
by tools.

4. Static class,Method,Constractor

Static class

Static means something which cannot be instantiated. You cannot create an object of static class and
cannot access static member using object
C# classes, variables, methods, properties, operators, events, and constructors can be defined as
static using the static modifier keyword.
Static Class
Apply the static modifier before the class name and after the access modifier to make a class static.
Below is the example of Static Class:

public static class Calculator


{
private static int _resultStorage = 0;

public static string Type = "Arithmetic";

public static int Sum(int num1, int num2)


{
return num1 + num2;
}

public static void Store(int result)


{
_resultStorage = result;
}
}

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

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


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

Calculator class is static class. All the member of its also static. We cannot the create object of static
class therefore member of the static class can be accessed directly using class name like
ClassName.MemberName.

Rules for Static Class

1. Static classes cannot be instantiated.


2. All the members of a static class must be static; otherwise the compiler will give an error.
3. A static class can contain static variables, static methods, static properties, static operators,
static events, and static constructors.
4. A static class cannot contain instance members and constructors.
5. Indexers and destructors cannot be static
6. var cannot be used to define static members. You must specify a type of member explicitly
after the static keyword.
7. Static classes are sealed class and therefore, cannot be inherited.
8. A static class remains in memory for the lifetime of the application domain in which your
program resides.

Static member in Non-Static Class

The non static class contain one or more static member,properties,methods fields.
Static fields in non static class can be define using the static keyword.
Static fields of non-static class is shared access all the instance. So, changes done by one instance
would reflect to other.
Below is the example of Static member in Non-Static class
using System;

public class Program


{
static int counter = 0;
string name = "Demo Program";
public static void Main()
{
StopWatch sw1 = new StopWatch();
StopWatch sw2 = new StopWatch();
Console.WriteLine(StopWatch.NoOfInstances);

StopWatch sw3 = new StopWatch();


StopWatch sw4 = new StopWatch();
Console.WriteLine(StopWatch.NoOfInstances);
}
}
public class StopWatch
{ public static int NoOfInstances = 0;
public StopWatch()
{
StopWatch.NoOfInstances++;
}
}
Output is the 2 and 4.
Static Method

We can define one or more static method in non static class. static method can be called without
creating an object. You cannot call static methods using an object of the non static class. You cannot
access non-static members of the class in the static methods.

Below is the example

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

static void Main(string[] args)


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

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


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

static void Display(string text)


{
Console.WriteLine(text);
}

public void SetRootFolder(string path) { }


}
Rules for Static Methods
 Static methods can be defined using the static keyword before a return type and after an
access modifier.
 Static methods can be overloaded but cannot be overridden.
 Static methods can contain local static variables.
 Static methods cannot access or call non-static variables unless they are explicitly passed as
parameters.

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

using System;

public class Program


{
public static void Main()
{
StopWatch.DisplayInfo(); // static constructor called here
StopWatch.DisplayInfo(); // none of the constructors called here

//StopWatch sw1 = new StopWatch(); // First static constructor and then instance constructor
called
//StopWatch sw2 = new StopWatch();// only instance constructor called
//StopWatch.DisplayInfo();
}
}
public class StopWatch
{
// static constructor
static StopWatch()
{
Console.WriteLine("Static constructor called");
}

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

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

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

Output:

Static constructor called.

DisplayInfo called

DisplayInfo calle

In the above example static constructor called only once when the Static method is called.

Rules of Static Constructors


 A Static constructor does not have access modifers or have parameters
 A Class or struct can only have one counstructor.
 Static constructors cannot be inherited or overloaded.

 Static constructor will be executed only once in the lifetime. So, you cannot determine when
it will get called in an application if a class is being used at multiple places.
 A static constructor can only access static members. It cannot contain or access instance
members.
 A Static constructor is called automatically to initialize the class before the first instance is
created or any static members are referenced. A static constructor will run before an
instance constructor. A type's static constructor is called when a static method assigned to
an event or a delegate is invoked and not when it is assigned.
 A static constructor cannot be called directly and is only meant to be called by the common
language runtime (CLR). It is invoked automatically.
 It is not possible to create a static constructor with parameters. This is because the static
constructor is the first block of code which is going to execute under a class. And this static
constructor called implicitly, even if parameterized there is no chance of sending the
parameter values.

Usage

 A typical use of static constructors is when the class is using a log file and the constructor is
used to write entries to this file.

 Static constructors are also useful when creating wrapper classes for unmanaged code, when
the constructor can call the LoadLibrary method.

 Static constructors are also a convenient place to enforce run-time checks on the type
parameter that cannot be checked at compile time via constraints (Type parameter
constraints).
What is the difference between static class and class with static methods? In which case I should
use either of them?
If your class has only static members you never need an instance of that class so you should make
the class itself static but if your class has instance members (non-static) then you have to make your
class an instance class to access its instance members via instances of your class.

Extension Method Extension Methods

Extension methods, as the name suggest are the additional methods. Extension methods allow
developers to extend functionality on an existing method without creating a new derived type,
recompiling, or otherwise modifying the original type.

Extension methods can be used as an approach of extending the functionality of a class in the future
if the source code of the class is not available or we don’t have any permission in making changes to
the class

How to use extension methods?


An extension method is a static method of a static class, where the "this" modifier is applied to the
first parameter. The type of the first parameter will be the type that is extended.
Extension methods are only in scope when you explicitly import the namespace into your source
code with a using directive.

Benefits of extension methods



Extension methods allow existing classes to be extended without relying on inheritance or
having to change the class's source code.
 If the class is sealed than there in no concept of extending its functionality. For this a new
concept is introduced, in other words extension methods.
 This feature is important for all developers, especially if you would like to use the dynamism
of the C# enhancements in your class's design.
Program to show how to use extension methods
Create a project Class Library as:

using System;
using System.Text;namespace ClassLibExtMethod
{
public class Class1 {
public string Display()
{
return ("I m in Display");
}

public string Print()


{
return ("I m in Print");
}
}
}

Now create a new project using "File" -> "New" -> "Project...".

Add the reference of the previously created class library to this project.
Use the following code and use the ClassLibExtMEthod.dll in your namespace:using System;
using System.Text;
using ClassLibExtMethod;
namespace ExtensionMethod1
{
public static class XX
{
public static void NewMethod(this Class1 ob)
{
Console.WriteLine("Hello I m extended method");
}
}

class Program
{
static void Main(string[] args)
{
Class1 ob = new Class1();
ob.Display();
ob.Print();
ob.NewMethod();
Console.ReadKey();
}
}
}
How to extent the inbuild string method ?

namespace CustomExtensions
{
// Extension methods must be defined in a static class.
public static class StringExtension
{
// This is the extension method.
// The first parameter takes the "this" modifier
// and specifies the type for which the method is defined.
public static int WordCount(this String str)
{
return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
https://dotnettutorials.net/lesson/extension-methods-csharp/

Important point

1. Extension method must be defined only under the static class.


2. The first parameter of an extension method is known as the binding parameter
which should be the name of the class to which the method has to be bound, and
the binding parameter should be prefixed with this keyword

3. An extension method can have only one binding parameter and that should be
defined in the first place of the parameter list.
4. If required, an extension method can be defined with normal parameter also
starting from the second place of the parameter list.

Inheritance

 It is one of the primary pillars of object-oriented programming.


 It allows code reuse
 Code reuse can reduce time and error
 C# support only single class inheritance. (Class can have only one base class)
 Multiple class inheritance at same time not possible but multilevel class inheritance is
possible
 C# support multiple interface inheritance
 Child class is a specialization of base class.
 Base classes are automatically instantiating before derived classes
 Parent class constructor executes before child class constructor.
 Constructor can be overloaded.

IMP- If parent class has overloaded constructor (one is with parameter and without parameter) then
parameter less constructer will be executing first.

How to control/define to execute constructor in parent class?

If parent class has multiple constructor, then we can use the base keywork in child class to define
which constructor will be executed.

Real-life example for Inheritance:

Example-Father and Son Relationship. Here son inherits Father physical properties, but father can't
get son physical properties.

Method hiding in C#

 Use the new keyword to hide a base class member. You get the compile warning if you miss
the new keyword.
 Different ways to invoke a hidden base class member from derived class.
o Use base keyword
o Cast child type to parent type and invoke the hidden member
o ParentClass PC=new ChildCalss()
PC.HiddenMethod();

IMP-Parent class reference variable can point to the child class object, but child class reference
variable cannot point to the parent class object. Because child class is specialization of base
class=means child class has all the capability of base class and additional features child class has

Point to remember: -

 A reserve keyword name “base ” can be used in derived class to call the base class method.
 Inheritance does not backwards.
o Derived class can be accessing all the base class method. But base class cannot
access derived class methods.
 Expect constructer and destructors, a class inherits everything from base class.
 In inheritance in C#, custom classes cannot derive from special built in C# classes like
System.ValueType, System.Enu etc…
 Circular dependency is not allowed in inheritance in C#. ClassA is derived from class ClassC
which was derived from ClassB and ClassB again derived from ClassA, Which clause circular
dependency in three classes, that is logically impossible.

public class ClassA:ClassC{}

public class ClassB: ClassA{}

public class ClassC:ClassB{}

What is the use of inheritance?


Inheritance allows programmers to create classes that are built upon existing classes, to specify a
new implementation while maintaining the same behaviors (realizing an interface), to reuse code
and to independently extend original software via public classes and interfaces.
Default access modifiers

1. Class- Internal
2. Class method- private
3. Interface -internal
4. Interface methods- public

C# Access Modifiers (With Examples) (programiz.com)

String and convert To string

The difference is Convert.ToString() method handles null whereas the ToString() doesn’t handle null
in C#.

Enum in C#

Enum is special kind of class that represent group of constant

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

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

Interface in c#.

Interface is a fully un-implemented class used for declaring a set of operations of an object. So we
can define an interface is a pure abstract class which allow us to define only abstract method.

IMP- Internal is the default access modifier of the interface.


What is the need of interface when we have a abstract class to define abstract method?

.net doesn’t support multiple inheritance with classes. So we use the interface as superclass to
develop abstraction for supporting multiple inheritance.

Is it necessary to implement all interface methods?


It is not necessary for a class that implements an interface to implement all its methods, but in this
case, the class must be declared as abstract.

Abstract class VS Interface

Both abstract class and interface are similarity both is incomplete and cannot created instance of
abstract class and interface.

 Abstract classes can have implementation for some of its member(method),but the interrace
can’t have implementations for any of its member.
Abstract example:

Interface Example

 Interface cannot have fields, but abstract class can have fields
 Abstract class have constructor. Interface cannot have constructor.
 A class can inherit from multiple interfaces at the same time, where as a class cannot inherit
from multiple classes at the same time.
 Abstract class member can have access modifiers whereas interface members cannot have
access modifiers.
 Abstract class mehtotds is by default private and interface methods is by default public
The Basis of C# Interface C# Abstract Class
comparison

Access Specifier In C#, Interface cannot have access In C#, an abstract class can have
specifier for functions. It is public by access specifier for functions.
default.

Implementation In C#, an interface can only have a An abstract class can provide
signature, not the implementation. complete implementation.

Speed The interface is comparatively slow. An abstract class is fast.

Instantiate Interface is absolutely abstract and An abstract class cannot be


cannot be instantiated. instantiated.

Fields Interface cannot have fields. An abstract class can have defined
fields and constants.

Methods Interface has only abstract methods. An abstract class can have non-
abstract methods.

So, in short, we would create an abstract class when want to move the common functionality of 2 or
more related classes into a base class and when, we don’t want that base class to be instantiated.
When we have the requirement of a class that contains some common properties or methods with
some common properties whose implementation is different for different classes, in that situation,
it's better to use Abstract Class then Interface.

Abstract class example

We have Hyundai and Toyota car which have same common functionality but different
implementation and have same common property

Like common function but different behaviour

1. Price
2. GetTotalSeat
3. Color

Common Property

1. Wheel
2. Check AC()
3. CallFacitlty()

 So here we define abstract class CAR


 Put all the common functionality in simple methods and all the methods whose
implementation is different but name is same. Make them Abstract method.

using System;
using System.Collections;
using System.Collections.Generic;

namespace oops1
{
public abstract class Cars
{

//put all the common functions but diffrent implementation in abstract method.
public abstract double price();
public abstract int getTotalSeat();
public abstract string colors();

//put all the common property in normal class


public string Wheel()
{
return "4 wheeler";

}
public string CheckAC()
{
return "AC is available";
}
public string CallFacility()
{
return "Call Facility supported";
}
}
}
Now, here is my Toyota class which is derived from Cars abstract class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace oops1
{
public class Toyota : Cars
{
public string DiscountPrice()
{
return "20% discount on buying Toyoya Cars";
}
public override double price()
{
return 1000000.00;
}
public override int getTotalSeat()
{
return 5;
}
public override string colors()
{
return "Red";
}

static void Main(string[] args)


{
Toyota Toy = new Toyota();
Console.WriteLine("-------Common property defined commonly in Cars Class----------");

Console.WriteLine(Toy.CallFacility());
Console.WriteLine(Toy.Wheel());
Console.WriteLine(Toy.CheckAC());
Console.WriteLine("-------Own property defined in Toyota class------------");
Console.WriteLine(Toy.DiscountPrice());
Console.WriteLine("-------Common method but implementation is diffrent defined in IExtra Int
erface------------");
Console.WriteLine("Total ONRoad Price:"+ Toy.price());
Console.WriteLine(Toy.getTotalSeat());
Console.WriteLine(Toy.colors());

Console.ReadLine();

}
}

1.
2. }
Interface example

Like we have car Hundai and Toyato calss which inharitace from the CAR class

using System;
using System.Collections;
using System.Collections.Generic;

namespace oops1
{
public class Cars
{

public string Wheel()


{
return "4 wheeler";

}
public string CheckAC()
{
return "AC is available";
}
public string CallFacility()
{
return "Call Facility supported";
}

}
Now, here is my Toyota class which is derived from Cars.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace oops1
{
public class Toyota : Cars
{

static void Main(string[] args)


{
Toyota Toy = new Toyota();

Console.WriteLine(Toy.CallFacility());
Console.WriteLine(Toy.Wheel());
Console.WriteLine(Toy.CheckAC());

Console.ReadLine();

}
}

}
Here is my Hyundai class which is derived from Cars.
using oops1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace oops1
{
public class Hyundai:Cars
{

static void Main(string[] args)


{
Hyundai dust = new Hyundai();

Console.WriteLine(dust.CallFacility());
Console.WriteLine(dust.Wheel());
Console.WriteLine(dust.CheckAC());

Console.ReadLine();

}
}

1. }
A new feature for the Hyundai car is Introduced called GPS which is not supported in Toyota cars.

Here if we define the abstract class and define GPS method and inherit it on Hyundai class and
implement the GPS method this approach give error because multiple class inheritance not possible
because Hundai already inherit from the CAR class

If we use the interface it will resolved our problem

1. interface INewFeatures
2. {
3. void GPS();
4.
5. }
6. using oops1;
7. using System;
8. using System.Collections.Generic;
9. using System.Linq;
10. using System.Text;
11. using System.Threading.Tasks;
12.
13. namespace oops1
14. {
15. public class Hyundai:Cars,INewFeatures
16. {
17. public void GPS()
18. {
19. Console.WriteLine("GPS supported.");
20.
21. }
22.
23.
24. static void Main(string[] args)
25. {
26. Hyundai hun = new Hyundai();
27.
28. Console.WriteLine(hun.CallFacility());
29. Console.WriteLine(hun.Wheel());
30. Console.WriteLine(hun.CheckAC());
31. hun.GPS();
32.
33.
34. Console.ReadLine();
35.
36.
37. }
38. }
39.
40.
41. }
For example refer https://www.c-sharpcorner.com/article/when-to-use-abstract-class-and-
interface-in-real-time-projects/

Interface use like we have some common method and some unique methods that we use
interface

What are the advantages of using interfaces?


This is the most commonly asked interview question. This interview question is being asked in
almost all the dot net interviews. It is very important that we understand all the concepts of
interfaces and abstract classes. Interfaces are very powerful. If properly used, interfaces provide all
the advantages as listed below.
1. Interfaces allow us to implement polymorphic behavior. Of course, abstract classes can also
be used to implement polymorphic behavior.
2. The Interfaces allow us to develop very loosely coupled systems.
3. Interfaces enable mocking for better unit testing.
4. The Interfaces enable us to implement multiple inheritances in C#.
5. Interfaces are great for implementing Inversion of Control or Dependency Injection.
6. The Interfaces enable parallel application development.

If a class inherits an interface, what are the 2 options available for that class?
Option1: Provide Implementation for all the members, inherited from the interface.
Option2: If the class does not wish to provide Implementation for all the members inherited from
the interface, then the class has to be marked as abstract.

What do you mean by “Explicitly Implementing an Interface”? Give an example?


If a class is implementing the inherited interface member by prefixing the name of the interface,
then the class is “Explicitly Implementing an Interface member”. The disadvantage of Explicitly
Implementing an Interface member is that the class object has to be typecasted to the interface
type to invoke the interface member. An example is shown below.
namespace Interfaces

interface Car

void Drive();

}
class Demo : Car

// Explicit implementation of an interface member

void Car.Drive()

Console.WriteLine("Drive Car");

static void Main()

Demo DemoObject = new Demo();

//DemoObject.Drive();

// Error: Cannot call explicitly implemented interface method

// using the class object.

// Type cast the demo object to interface type Car

((Car)DemoObject).Drive();

When to use Interface?


If your child classes should implement a certain group of methods/functionalities but each of the
child classes is free to provide its own implementation then use interfaces.

What is the abstract method?


A method that does not have the body is called an abstract method. It is declared with the modifier
abstract. It contains only the Declaration/signature and does not contain the implementation/ body
of the method. An abstract function should be terminated with a semicolon. Overriding of an
abstract function is compulsory.
When to use the abstract method?
Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar
role in different ways.
We cannot create an instance of an abstract class. So, what is the use of a constructor in an
abstract class?
Though we cannot create an instance of an abstract class, we can create instances of the classes that
are derived from the abstract class. So, when an instance of a derived class is created, the parent
abstract class constructor is automatically called.
Note: Abstract classes can’t be directly instantiated. The abstract class constructor gets executed
through a derived class. So, it is a good practice to use a protected access modifier with the abstract
class constructor. Using public doesn’t make sense.

An abstract method in an abstract class does not have any implementation, so what is the use of
calling it from the abstract class constructor?
If we want the abstract method to be invoked automatically whenever an instance of the class that is
derived from the abstract class is created, then we would call it in the constructor of the abstract
class.
Why can the abstract class not be instantiated?
Because it is not fully implemented in the class as its abstract methods cannot be executed. If the
compiler allows us to create the object for the abstract class, then we can invoke the abstract
method using that object which cannot be execute

Explain the differences between overriding methods and abstract methods in C#?
The concept of the abstract method is similar to the concept of method overriding because in
method overriding if a Parent class contains any virtual methods in it, then those methods can be re-
implemented under the child class by using the override modifier.
In a similar way, if a parent class contains any abstract methods in it, those abstract methods must
be implemented under the child class by using the same override modifier.
The main difference between method overriding and abstract method is in the case of method
overriding the child class re-implementing the method is optional but in the case of the abstract
method, the child class implementing the method is mandatory.

Interface example in BMW


We have one IWorkflowProduct.cs interface here we declare below mehtod.
 bool CreateTask(string TransactionType, string RequestCode, NameValueCollection
DataFieldCollection, string UserCred);
 bool ModifyTask(string RequestCode,NameValueCollection DataFieldCollection, string
UserCred);
 DataSet RetrieveTasks(string TransactionType);
DataSet RetrieveTasks(string TransactionType,SourceCode.K2ROM.WorklistCriteria
Criteria);
DataSet RetrieveTasks(string transactionType,
Diamond problem
The "diamond problem" is an ambiguity that arises when two classes B and C inherit from A, and
class D inherits from both B and C. If there is a method in A that B and C have overridden, and D does
not override it, then which class of the method does D inherit: that of B, or that of C? So this is an
ambiguity problem in multiple inheritances in c#. So that c# does not support multiple
inheritances. It also called an ambiguity problem in c#.

Abstraction

 In c#, Abstraction is a principle of object oriented programming language (OOP) and it is


used to hide the implementation details and display only essential features of the object.

 In Abstraction, by using access modifiers we can hide the required details of object and
expose only necessary methods and properties through the reference of object.
 In real time, laptop is the perfect example for abstraction in c#. A laptop which consists of
many things such as processor, RAM, motherboard, LCD screen, camera, USB ports, battery,
speakers, etc. To use it, we just need to know how to operate the laptop by switching it on,
we don’t need to know how internally all the parts are working. Here, the laptop is an object
which is designed to expose only required features by hiding its implementation details.
 Abstraction is a process of hiding work style of an object and showing only those information
which are required to understand the object. Abstraction means putting all the variables and
methods in a class which are necessary.
 The process of defining a class by providing the necessary and essential details of an object
to the outside world and hiding the unnecessary things is called abstraction in C#. It means
we need to display what is necessary and compulsory and need to hide the unnecessary
things to the outside world. In C# we can hide the member of a class by using private access
modifiers.

Encapsulation

 The process of binding the data and functions together into a single unit (i.e class) is called
encapsulations. Or we can say that the process of defining a class by hiding its internal data
member direct access from outside the class and providing its access only through public
expose methods or properties with proper validations and authentications Is called
encapsulation.
 The Data encapsulation is also called data hiding because by using this principle we can hide
the internal data from outside the class.
 https://dotnettutorials.net/lesson/encapsulation-csharp/

How can we implement encapsulation in c#?

1. By declaring the variables as private(to restrict its direct access from outside the class)
2. By defining one pair of public setter and getter methods or properties to access private
variables.

What is the problem if we don’t follow encapsulation in C# while designing a class?


If we don’t the encapsulation principle while designing the class, then we cannot validate the user-
given data according to our business requirement as well as it is very difficult to handle future
changes.
What is the difference between Abstraction and Encapsulation in C#?
Encapsulation is the process of hiding irrelevant data from the user or you can say Encapsulation is
used to protect the data. For example, whenever we buy a mobile, we can never see how the
internal circuit board works. We are also not interested to know how the digital signal converts into
the analog signal and vice versa. So from a Mobile user’s point of view, these are some irrelevant
pieces of information, This is the reason why they are encapsulated inside a cabinet.

Coming to abstraction in C#, It is just the opposite of Encapsulation. What it means, it is a


mechanism that will show only the relevant information to the user. If we consider the same mobile
example. Whenever we buy a mobile phone, we can see and use many different types of
functionalities such as a camera, calling function, recording function, mp3 player, multimedia, etc.
This is nothing but an example of abstraction in C#. The reason is we are only seeing the relevant
information instead of their internal working.

How u will explain abstraction vs encapsulation to non technical person?

Abstraction is used to hide the implementation details and display only essential features of the
object. Abstraction is a process of hiding work style of an object and showing only those information
which are required to understand the object. Abstraction means putting all the variables and
methods in a class which are necessary.

Encapsulation is a process of hiding all the internal details of an object from outside the word.It
restrict client from seeing its internal view where behavior of the abstraction is implemented

Abstraction Example
TV or Car remote is the also example of Abstraction.TV or Car remote is assembled from the
collection of circuits but they don't show to the user all circuits behind the remote, They only
provide remote to the user to use it. When the user presses the key on remote the channel gets
changed. They provide only necessary information to the user. This concept is called Data
Abstraction.
A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen,
wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know
how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker's works. You
just need to know how to operate the laptop by switching it on.

Non-Technical Example:

A capsule is the be st

example of encapsulation. A capsule is inside the wrapper and wrapper provide the security to the
capsule and wrapper is work as a container like class.

Coding example of abstraction and encapsulation

https://www.codeproject.com/Articles/1037139/Difference-between-Encapsulation-and-
Abstraction-i

Polymorphism
Technically we can say that when a function shows different behaviors when we passed different
types and number values, then it is called polymorphism. So behaving in different ways depending
on the input received is known as polymorphism i.e. whenever the input changes, automatically the
output or the behavior also changes.

Types of Polymorphism in C#
There are two types of polymorphism in C#
1. Static polymorphism / compile-time polymorphism / Early binding
2. Dynamic polymorphism / Run-time polymorphism / Late binding
The following diagram shows different types of polymorphisms in C# with their examples.
What is Compile-Time Polymorphism?
In the case of compile-time polymorphism, the object of class recognizes which method to be
executed for a particular method call at the time of program compilation and binds the method call
with method definition.
This happens in case of overloading because in case of overloading each method will have a different
signature and based on the method call we can easily recognize the method which matches the
method signature.

What is Runtime Polymorphism?


In the case of Runtime Polymorphism for a given method call, we can recognize which method has to
be executed exactly at runtime but not in compilation time because in case of overriding we have
multiple methods with the same signature

Overloading

It is process of creating multiple methods in a callses with same name but with a different signature.
In C# it is also possible to overload method in a derived classes which means, it allows us to create a
method in the derived class with the same name as the method name defined in the base class

So in C# functions or methods can be overloaded based on the number, type (int, float, etc), order,
and kind (Value, Ref or Out) of parameters.
The point that you need to keep in mind is the signature of a method does not include the return
type and the params modifiers. So it is not possible to overload a method just based on the return
type and params modifier.
namespace PolymorphismDemo
{
class Program
{
public void add(int a, int b)
{
Console.WriteLine(a + b);
}
public void add(float x, float y)
{
Console.WriteLine(x + y);
}
public void add(string s1, string s2)
{
Console.WriteLine(s1 + s2);
}
static void Main(string[] args)
{
Program obj = new Program();
obj.add(10, 20);
obj.add(10.5f, 20.5f);
obj.add("pranaya", "kumar");
Console.WriteLine("Press any key to exist.");
Console.ReadKey();
}
}
}

 You can not define more than one method with the same name, Order and the type of the
arguments. It would be compiler error.
 What happens when method signature is same and the return type is different?
The compiler will give error as the return value alone is not sufficient for the compiler to figure
out which function it has to call. Only if both methods have different parameter types (so, they
have the different signature), then Method overloading is possible.

When should we overload methods in C#?

If you want to execute the same logic but with different types of argument i.e. different types of
values, then you need to overload the methods.

What are the advantages of using method overloading in C#? Or what are the disadvantages if we
define methods with a different name?
If we overload the methods, then the user of our application gets comfort feeling in using the
method with an impression that he/she calling one method bypassing different types of values. The
best example for us is the system-defined “WriteLine()” method. It is an overloaded method, not a
single method taking different types of values.
When is a method considered as an overloaded method in C#?
If two methods have the same method name those methods are considered overloaded methods.
Then the rule we should check is both methods must have different parameter
types/number/order.
What is inheritance-based overloading?
A method that is defined in a class can also be overloaded under its child class. It is called
inheritance-based overloading.

7. Method Overriding
The process of re-implementing of parent class method in the child class with the same
prototype(same signature ) is called as Function/Method Overriding.

Overriding method always execute using the current class object (Child class).

When do we need to implement override method?

If super class logic did not fulfil the sub classes business requirement then sub class need to override
method with the required business logic.

How can we override a parent class method under child class?


If you want to override a parent class method in its child class, first the method in the parent class
must be declared as virtual by using the keyword virtual, then only the child classes get the
permission for overriding that method.

How did we execute the superclass method if it is overridden in sub-class?


Once we re-implement the parent class methods under the child class, then the object of the child
class calls its own methods but not its parent class method. But if you want to still consume or call
the parent class’s methods from the child class, then it can be done in two different ways.
By creating the parent class object under the child class, we can call the parent class methods from
the child class, or by using the base keyword, we can call parent class methods from the child class,
but this and base keyword cannot be used under the static block.

namespace PolymorphismDemo
{
class Class1
{
public virtual void show()
{
Console.WriteLine("Super class show method");
}
}
class Class2 : Class1
{
public override void show()
{
base.show();
Console.WriteLine("Sub class override show method");
}
}
class Program
{
static void Main(string[] args)
{
Class2 obj = new Class2();
obj.show();
Console.ReadKey();
}
}
}

A parent class method can be redefined under its child class using two different approaches.
1. Method Overriding.
2. Method Hiding.
In Method overriding, the parent class gives permission for its child class to override the method by
declaring it as virtual. Now the child class can override the method using the Override keyword as it
got permission from the parent. The parent class methods can be redefined under child classes even
if they were not declared as Virtual by using the ‘new’ keyword.
In method overriding a base class reference variable pointing to a child class object will invoke the
overridden method in the child class. In method hiding a base class reference variable pointing to a
child class object will invoke the hidden method in the base class.
For hiding the base class method from the derived class simply declare the derived class method
with the new keyword. Whereas in C#, for overriding the base class method in a derived class, we
need to declare the base class method as virtual and the derived class method as the override.
If a method is simply hidden then the implementation to call is based on the compile-time type of
the argument “this”. Whereas if a method is overridden then the implementation to be called is
based on the run-time type of the argument “this”. New is reference-type specific, overriding is
object-type specific.

What is the difference between a virtual method and an abstract method?


A virtual method must have a body whereas an abstract method should not have a body.

Can you access a hidden base class method in the derived class?
Yes, Hidden base class methods can be accessed from the derived class by casting the instance of the
derived class to an instance of the base class as shown in the example below.
public class BaseClass

public virtual void Method()

Console.WriteLine("I am a base class method.");

public class DerivedClass : BaseClass


{

public new void Method()

Console.WriteLine("I am a child class method.");

public static void Main()

DerivedClass DC = new DerivedClass();

((BaseClass)DC).Method();

In BMW project We have one functionality Cash posting which do the cash posting against the deal
to settle the deal or partial paid.
First we have Upload function which first upload the cash posting with confirm status and the sent
this request to the LCC roles to approve the request.
Some time requierent was change now client need to auto approval means at the time of uploading
function cash posting also approve.

8. String Immutability why/Whether string is mutable/immutable-

String is immutable.
String Immutability(Why)
String is reference data type in c#. A String is a sequential collections of character that is used to
represent a text.

Creation of string

Now, we will try to understand what happens when CLR reads the below statement which is written
to create a string.

1. string testString = "Siva"; // 4 characters

1. First, CLR checks the type of the data type. It is a reference type which will be stored into
heap memory.

2. Now, CLR need to reserve some amount of memory to store the string value. So it checks the
number of characters that exist in the string to; it is 4 (4x2 bytes = 8 bytes) characters.
3. A character array will be created into a heap with the size of 8 bytes and “Siva” will be stored
into memory. Let’s assume that the memory location of this is 101.

4. CLR will assign 101 as a memory reference to testString.

When you create a string, it is immutable. That means it is read-only. When something is immutable
or read-only, it means it cannot be changed at a later time

Why Strings are Immutable

An immutable object is defined as an object that cannot be changed after it has been created.

In C#, the CLR (Common Language Runtime) is responsible for determining where to store strings. a
string is an array of characters. The CLR implements an array to store strings. Arrays are a fixed size
data structure, meaning that they cannot be dynamically increased or decreased in size. Once an
array is assigned a size, the size cannot be changed. To make an array larger, the data must be
copied and cloned into a new array, which is put into a new block of memory by the CLR. If you edit
a string, you are really not modifying that string; rather, the CLR is creating a new memory reference
for the modified string, and the original string will get removed from memory via garbage collection.

9. Reflection

Reflection object are used for obtaining type information at runtime. The class that give access to
the metadata of a running program are in the System.Refelcation namespace.

Reflection provide object (of type Type ) that describe assemblies, modules and type.

The System.Reflection namespace contains classes that allow you to obtain information about the
application and to dynamically add types, values, and objects to the application.

Applications of Reflection
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.

Example of reflection using the GetType() method- inherited by all types from object base class.

int i = 42;
Type type = i.GetType();

Console.WriteLine(type);

Output

The output is: System.Int32.


The following example uses reflection to obtain the full name of the loaded assembly.

// Using Reflection to get information of an Assembly:


Assembly info = typeof(int).Assembly;

Console.WriteLine(info);

The output is: System.Private.CoreLib, Version=4.0.0.0, Culture=neutral,

Generic Class

Generic means the general form, not specific. In C#, generic means not specific to a particular data
type.

C# allows you to define generic classes, interfaces, abstract classes, fields, methods, static methods,
properties, events, delegates, and operators using the type parameter and without the specific data
type.

class DataStore<T>
{
public T Data { get; set; }
}

DataStore<string> strStore = new DataStore<string>();


strStore.Data = "Hello World!";
//strStore.Data = 123; // compile-time error

DataStore<int> intStore = new DataStore<int>();


intStore.Data = 100;
//intStore.Data = "Hello World!"; // compile-time error

KeyValuePair<int, string> kvp1 = new KeyValuePair<int, string>();


kvp1.Key = 100;
kvp1.Value = "Hundred";

KeyValuePair<string, string> kvp2 = new KeyValuePair<string, string>();


kvp2.Key = "IT";
kvp2.Value = "Information Technology";

In project we have one ManageComman abstract generic class. In this class we have method like
LogErrorMessage,ValidateDateFormat.

In this Generic class is use in different classes to log the error message or validate
the request.
1. Inherit and pass the T type parameter as data object classes
2. Access the method using this modifier.

10. Var Vs Dynamic in c#

Programming languages can normally be considered to be either statically typed or dynamically


typed. A static (not to be confused with the static keyword, used for classes) typed language
validates the syntax or checks for any errors during the compilation of the code. On the other hand,
dynamically typed languages validate the syntax or checks for errors only at run time. For example,
C# and Java are a static type and JavaScript is a dynamically typed language.

Var keyword

Variables declared with var are statically typed. Here type of variable is decided at the compile time.
Var should be initialized at the time of declaration. By looking at the assigned value, the compiler will
decide the variable type. As compiler knows the data type of the variable at compile time, errors will
be caught at that time only.

Example

1. var obj "c-sharp corner";

In the above sentence, obj will be treated as a string

1. obj = 10;

In the above line, the compiler will throw an error, as compiler already decided the type of obj as
String and assigned an integer value to string variable violating safety rule type.

Dynamic Keyword

Variables declared with dynamic were dynamically typed. Here, the type of variable declared is
decided at runtime. Variables which are declared as dynamic don't need to initialize the time of
declaration. The compiler won't know the variable type at the time of compiling, hence errors can't
be caught by the compiler while compiling. IntelliSense is not available since the type of variable will
be decided at runtime.
Example

1. dynamic obj = "c-sharp corner";

In the above code, obj will be treated as a string.

1. obj = 10;

The comipler will not throw any error, though obj is assigned to the integer value. The compiler will
create the type of obj as String and then it recreates the type of obj as an integer when we assign
an integer value to obj.

11. Can we use var/Dynamic as a return type of function

We cannot use var as parameter for any function but the dynamic type can be used as parameter for
any function. We cant create method with var return type but we can create a method whose return
type is dynamic.

12. Can we initialize var a=null

A var cannot be set to null since it needs to be statically typed.

13. Can we write custom extension methods

Yes we can write custom extension methods adding reference variable.

14. Factory is behavorial.Structural,Creationl

Factory pattern is Creational pattern as Gang of Four

15. When static constructor is invoked

A static constructor is used to initialize any static data, or to perform a particular action that needs to
be performed once only. It is called automatically before the first instance is created or
any static members are referenced.

16. Static VS singleton

similarities between Singleton vs Static class in C#

1. both singleton and static class can have only one instance of a copy of that variable in
memory throughout the whole application.
2. Both static class and singleton class implemented as thread safe.

Difference between singleton and static class

The most important point that you need to keep in mind is that Static is a language feature whereas
Singleton is a design pattern. So both belong to two different areas.

1. We cannot create an instance of a static class in C#. But we can create a single instance of a
singleton class and then can reuse that singleton instance.
2. When the compiler compiles the static class then internally it treats the static class as an
abstract and sealed class. This is the reason why neither we create an instance nor extend a
static class in C#.
3. The Singleton class constructor is always marked as private. This is the reason why we
cannot create an instance from outside the singleton class. It provides either public static
property or a public static method whose job is to create the singleton instance only once
and then return that singleton instance each and every time when we called that public
static property/method from outside the singleton class.
4. A Singleton class can be initialized lazily or can be loaded automatically by CLR (Common
Language Runtime) when the program or namespace containing the Singleton class is
loaded. whereas a static class is generally initialized when it is first loaded for the first time
and it may lead to potential classl oader issues.
5. It is not possible to pass the static class as a method parameter whereas we can pass the
singleton instance as a method parameter in C#.
6. In C#, it is possible to implement interfaces, inherit from other classes and allow inheritance
with Singleton class. These are not possible with a static class. So the Singleton class is more
flexible as compared to static classes.
7. We can clone the Singleton class object whereas it is not possible to clone a static class. It is
possible to dispose of the objects of a singleton class whereas it is not possible to dispose of
a static class.
8. We cannot implement the Dependency Injection design pattern using Static class because
the static class is not interface driven.
9. Singleton means a single object across the application lifecycle, so the scope is at the
application level. As we know the static class does not have any Object pointer, so the scope
is at the App Domain level.

https://dotnettutorials.net/lesson/singleton-vs-static-class/

Static vs sealed vs abstract

Static Class: Declared with Static keyword, methods in Static Class are also static along with
variables of the class.
This class cannot be instantiated, i.e we cannot have objects of this class. To access methods
of this class, you can directly use classname.method. Also this class cannot be inherited.

Sealed Class: Declared with Sealed keyword, which enables this class to seal all its variables,
methods and properties. No other class can inherit anything from this class or in other
words, this class cannot be inherited. But we can instantiate this class, i.e we can have any
number of objects of a sealed class.

Abstract Class: Declared with abstract keyword, this class is primarily created as a
Inheritable class. An abstract class enables other classes to inherit from this class, but forbids
to instantiate. One can inherit from an abstract class but we cannot create objects of an
abstract class. Abstract class can have abstract as well as non abstract methods. Abstract
methods are those which are not having method definition.

11. Same name/Signature method in 2 interface which are implemented in same class

We can create same name/signature method in 2 different interface and we can implemented
these method in same class to mentioned interface explicitly.

namespace Practice
{
interface IFirstInterface
{
void FirstName(String Name);
}
interface ISecondInterface
{
void FirstName(String Name);
}
class MyClass :IFirstInterface,ISecondInterface
{
public void FirstName(String Name)
{
Console.WriteLine("First Interface Name is "+Name+" ");
}
void ISecondInterface.FirstName(String strname)
{
Console.WriteLine("Second Interface Name is " + strname + "");
}
}

class Program
{

static void Main(string[] args)


{
MyClass myclass = new MyClass();
myclass.FirstName("Varsha");

ISecondInterface objsecondInterface = new MyClass();


objsecondInterface.FirstName("Vikrant");

Console.ReadLine();

}
}

12. Lazy Loading-

Object on demand is also called Lazy Loading. Lazy loading delay the initialization on object.

Lazy loading is a concept where we delay the loading of the object until the point where we need it.
Putting in simple words, on demand object loading rather than loading objects unnecessarily.

https://www.codeproject.com/Articles/652556/Can-you-explain-Lazy-Loading

13. Throw vs throw ex

throw : If we use "throw" statement, it preserve original error stack information. In exception
handling "throw" with empty parameter is also called re-throwing the last exception.
throw ex : If we use "throw ex" statement, stack trace of exception will be replaced with a stack
trace starting at the re-throw point. It is used to intentionally hide stack trace information.

Below example

If we use throw in Method 2, we have a full hierarchy, in other words FaultyMethod2, then Method2
and then Method1 along with the line numbers at which an exception occurred or was thrown. Also,
the target site is given as "FaultyMethod2".

Now let's change the "throw" to "throw ex" in Method2


Now please notice that in the stack trace, we see hierarchy as Method2, then Method1 along with
the line numbers at which an exception is thrown. Also, the target site is given as "Method2"

Thus, after looking at the output of the "throw" and "throw ex" we can say "throw" maintains the
full hierarchy in the stack trace and gives complete information about the exception occurred in the
code. Whereas "throw ex" pretends that exceptions occurred on the line where "throw ex" was
written and removes all the hierarchy above the method containing the "throw ex" expression

14. Using Statement

Using statements is used to work with an object in C# that inherit IDisposable interface.

IDisposable interface has one public method called Dispose that is used to dispose of the object.
When we use the using statement ,we don’t need to explicitly dispose the object in the code,

Use of Using statements:

1. Add the Namespace


2. Close the SQL connection
3. Web Service

These days, a web service call is often used in our applications. We can also use the using
statement when calling a web service. Once we call the web service if we forgot to dispose
of the object then the using statement helps in closing and disposing of the object
because web service objects are heavy.

15. Constructor Sequence

In C# constructor is a special method which is invoke automatically at the time of object creation.It is
used to initialize the data member of new object generally.

Order of Constructor and Destructor call in C# –


Order of execution of constructor and destructor call in c# inheritance: Constructor call is from top
to bottom i.e. from base class to derive class and destructor call is in reverse order i.e. from bottom
to top.

//Base class
class Base
{
public Base() { Console.WriteLine("Constructor: Base"); }
~Base() { Console.WriteLine("Destructor: Base"); }
}
//Derived class
class DerivedOne : Base
{
public DerivedOne() { Console.WriteLine("Constructor: DerivedOne"); }
~DerivedOne() { Console.WriteLine("Destructor: DerivedOne"); }

}
//Derived class
class DerivedTwo : DerivedOne
{
public DerivedTwo() { Console.WriteLine("Constructor: DerivedTwo"); }
~DerivedTwo() { Console.WriteLine("Destructor: DerivedTwo"); }
}

class Program
{
static void Main(string[] args)
{
Base o = new DerivedTwo();

}
}

Output:
Constructor: Base
Constructor: DerivedOne
Constructor: DerivedTwo
Destructor: DerivedTwo
Destructor: DerivedOne
Destructor: Base

16. Ref and Out Keyword

Both ref and out keyword is used to pass argument within method or function. Both indicate that an
argument\parameter is passed by reference.

Ref keyword is used to pass an argument as a reference. This means that value of the parameter is
change in the method, it gets reflected in the calling method. An argument that is passed using ref
keyword must be initialized in the calling method before is passed to the called method.

Out keyword is used to pass an argument as a reference, but argument can be passed without
assigned any value to it. An argument that is passed using an out keyword must be initialized in the
called method before it returns back to calling method. it is generally used when a method returns
multiple values

So, let’s simplify that. If we want to change an existing value of a variable inside a method, we are
going to use the ref keyword. But, if we want to assign a completely new value to the variable inside
a method, then we use the out keyword.
Example 1 for the Value Type
In this one, we are going to see the behavior of value type variables when we use those keywords:

class Program

public static void ChangeRef(ref int numberRef)

numberRef = 25;

Console.WriteLine($"Inside the ChangeRef method the numberRef is {numberRef}");

public static void ChangeOut( out int numberOut)

numberOut = 60;

Console.WriteLine($"Inside the ChangeOut method the numberOut is {numberOut}");

static void Main(string[] args)

int numberRef = 15;

Console.WriteLine($"Before calling the ChangeRef method the numberRef is {numberRef}");

ChangeRef(ref numberRef);

Console.WriteLine($"After calling the ChangeRef method the numberRef is {numberRef}");

Console.WriteLine();

int numberOut;

Console.WriteLine("Before calling the ChangeOut method the numberOut is unassigned");

ChangeOut(out numberOut);

Console.WriteLine($"After calling the ChangeOut method the numberOut is {numberOut}");


Console.ReadKey();

This all is pretty clear. If we use the ref or the out keyword on the value type variable, its original
value will change. But the difference is that with the out keyword we can use unassigned variables

1. Do not be confused with the concept of passing by reference and the concept of reference type.
These two concepts are not the same.

2. A value type or a reference type can be passed to method parameter by using ref keyword. There is
no boxing of a value type when it is passed by reference.
3. Properties cannot be passed to ref or out parameters since internally they are functions and not
members/variables.

17. Ref and out in method overloading

Both ref and out cannot be used in method overloading simultaneously. However, ref and out are
treated differently at run-time but they are treated same at compile time (CLR doesn't differentiates
between the two while it created IL for ref and out). Hence methods cannot be overloaded when
one method takes a ref parameter and other method takes an out parameter. The following two
methods are identical in terms of compilation.
class MyClass
{
public void Method(out int a) // compiler error “cannot define overloaded”
{
// method that differ only on ref and out"
}
public void Method(ref int a)
{
// method that differ only on ref and out"
}
}
However, method overloading can be done, if one method takes a ref or out argument and the other
method takes simple argument. The following example is perfectly valid to be overloaded.
class MyClass
{
public void Method(int a)
{
}
public void Method(out int a)
{
// method differ in signature.
}
}
Sr. Key ref keyword out keyword
No.

Purpose ref keyword is used when a called method out keyword is used when a called
1
has to update the passed parameter. method has to update multiple
parameter passed.

2 Direction ref keyword is used to pass data in bi- out keyword is used to get data in uni-
directional way. directional way.

Initialization Before passing a variable as ref, it is No need to initialize variable if out


3
required to be initialized otherwise keyword is used.
compiler will throw error.

4 Initialization In called method, it is not required to In called method, it is required to


initialize the parameter passed as ref. initialize the parameter passed as out.

18. Delegate

Delegate is a type safe function pointer. It means they hold the reference of a method or function
and the calls method for execution.

How many ways we can call a method in c#?

1. creating object of the call if it is a non static method.


2. Call through class name if it is static method.
3. Using delegates. Calling a c# method using delegate will be faster in execution compare to
by using an object or by using class name.

A function can have one or more parameters of different data types, but if we want to pass a
function as method parameter? How does C# handle the callback functions or event handler?

The answer is “delegate”.


We discussed that delegates are used to reference any methods that has the same signature as that
of the delegate.
A delegate is like a pointer to a function. It is a reference type data type and it hold the reference of
method. All the delegates are implicitly derived from system.delegate class.
Delegate hold the reference of method and function and then calls the method for execution.

There are three steps involved while working with delegates:

1. Declare a delegate
2. Instantiating a delegate
3. Invoke a delegate

<access modifier> delegate <return type> <delegate_name>(<parameters>)

public delegate void MyDelegate (string strmsg);

function signature must match with delegate signature

/ set target method


MyDelegate del = new MyDelegate(MethodA);
// or
MyDelegate del = MethodA;
// or set lambda expression
MyDelegate del = (string msg) => Console.WriteLine(msg);

Invoke the delegate

del.Invoke("Hello World!");
// or
del("Hello World!");

Passing Delegate as a Parameter


A method can have a parameter of the delegate type, as shown below.
Example: Delegate
public delegate void MyDelegate(string msg); //declaring a delegate

class Program
{
static void Main(string[] args)
{
MyDelegate del = ClassA.MethodA;
InvokeDelegate(del);

del = ClassB.MethodB;
InvokeDelegate(del);

del = (string msg) => Console.WriteLine("Called lambda expression: " + msg);


InvokeDelegate(del);
}

static void InvokeDelegate(MyDelegate del) // MyDelegate type parameter


{
del("Hello World");
}
}

class ClassA
{
static void MethodA(string message)
{
Console.WriteLine("Called ClassA.MethodA() with parameter: " + message);
}
}

class ClassB
{
static void MethodB(string message)
{
Console.WriteLine("Called ClassB.MethodB() with parameter: " + message);
}
}

Types of Delegates in C#:


Delegates are classified into two types such as
1. Single cast delegate
2. Multicast delegate
If a delegate is used for invoking a single method then it is called a single cast delegate or unicast
delegate. OR the delegates that represent only a single function is known as a single cast delegate.
If a delegate is used for invoking multiple methods then it is known as the multicast delegate. OR the
delegates that represent more than one function are called Multicast delegate.

Multicast Delegate
The delegate can points to multiple methods. A delegate that points multiple methods is called a
multicast delegate. The "+" operator adds a function to the delegate object and the "-" operator
removes an existing function from a delegate object.

Example

public delegate void Print(int value);

static void Main(string[] args)


{
Print printDel = PrintNumber;
printDel += PrintHexadecimal;
printDel += PrintMoney;

printDel(1000);

printDel -=PrintHexadecimal;
printDel(2000);
}

public static void PrintNumber(int num)


{
Console.WriteLine("Number: {0,-12:N0}",num);
}

public static void PrintMoney(int money)


{
Console.WriteLine("Money: {0:C}", money);
}

public static void PrintHexadecimal(int dec)


{
Console.WriteLine("Hexadecimal: {0:X}", dec);
}

Multicast delegate invoked the methods in the invocation list, in the same order in which they are
added.
If the delegate has a return type other than void and if the delegate is a multicast delegate. then
only the value of the last invoked method will be returned. Along the same lines, if the delegate has
an out parameter, the value of the output parameter will be the value assigned by the last method.
https://dotnettutorials.net/lesson/delegates-csharp/

When to use Delegate?

1. These are used to represent or refer to one or more functions.


2. These can only be used to define call-back methods.
3. In order to consume a delegate, we need to create an object to delegate.

What is the advantages of Dependency injection

Dependency Injection Benefits

 Reduced Dependencies.
 Reduced Dependency Carrying.
 More Reusable Code.
 More Testable Code.
 More Readable Code
It also reduces the risk that you have to change a class just because one of
its dependencies changed.

19. Difference between “readonly” and “const” keywork in C#

In C#, a const keyword is used to declare constant fields and constant local. The value of the
constant field is the same throughout the program or in other words, once the consent field is
assigned the value of this field is not be changed. In C#, constant fields and locals are not variables, a
constant is a number, string, null reference, boolean values.

In C#, Readony keyword is used to declare a read only variable. This keyword shows that you can
assign the variable only when you declare a variable or in a constructor of the same class in which it
is declared.

Const Variable in C#:


1. The keyword const is used to create a “constant” variable. It means it will create a variable
whose value is never going to be changed. In simple words, we can say that the variable
whose value cannot be changed or modified once after its declaration is known as a constant
variable.
2. Constants are static by default.
3. It is mandatory to initialize a constant variable at the times of its declaration.
4. The behavior of a constant variable is same as the behavior of static variable i.e. maintains
only one copy in the life cycle of class and initialize immediately once the execution of the
class start (object not required)
5. The only difference between a static and constant variable is that the static variable value
can be modified but a constant variable value can never be modified.

Read-only Variable in C#:


1. The variable which is declared by using the readonly keyword is known as a read-only
variable. The read-only variable’s value cannot be modified once after its initialization.
2. It is not mandatory or required to initialize the read-only variable at the time of its
declaration like a constant. You can initialize the read-only variables under a constructor but
the most important point is that once after initialization, you cannot modify the value.
3. The behavior of a read-only variable is similar to the behavior of a non-static variable. That
is, it maintains a separate copy for each object. The only difference between these two is
non-static variables can be modified while the read-only variables cannot be modified.
4. A constant variable is a fixed value for the complete class whereas a read-only variable is a
fixed value but specific to one object of the class.

READONLY KEYWORD CONST KEYWORD

In C#, readonly fields can be created using readonly In C#, constant fields are created using
keyword const keyword.

ReadOnly is a runtime constant. Const is a compile time constant.

The value of the const field can not be


The value of readonly field can be changed. changed.

It cannot be declared inside the method. It can be declared inside the method.

In readonly fields, we can assign values in declaration In const fields, we can only assign values
and in the constructor part. in declaration part.

It can be used with static modifiers. It cannot be used with static modifiers.

Mocking

Mocking is very useful concept when the project is distributed among many team members. The
fundamental idea behind mocking is to inject dependency and perform a unit test.

Mocking helps to improve unit tests by removing the outside dependencies which results in better,
faster, independent unit tests.

Please refer below link:

https://www.c-sharpcorner.com/UploadFile/dacca2/fundamental-of-unit-testing-understand-mock-
object-in-unit/
https://www.codeproject.com/Articles/30381/Introduction-to-Mocking

Lambdas Expression

Lambda expression are how anonymous function are created.

Lambda expressions are anonymous function that contain expressions or sequence of operators. All
lambda expression uses the lambda operator =>, that can be led as “goes to” or becomes.

The left side of lambda operator specifies the input parameter and right side hold the expression or
a code block that work with the entry framework. Usually lambda expressions are used as predicates
or instead of delegates (a type that references a method).

Expression Lambdas

Parameter => expression


Parameter-list => expression
Count => count + 2;
Sum => sum + 2;
n => n % 2 == 0

The lambda operator => divides a lambda expression into two parts. The left side is the input
parameter and the right side is the lambda body.

Output

246

What CLR does when a logical mistake occurred in the program?


This is one of the frequently asked Exception Handling Interview Questions in C#.
It creates an exception class object that is associated with that logical mistake and terminates the
current method execution by throwing that exception object by using the “throw” keyword.
So we can say an exception is an event that occurs during the execution of a program that disrupts
the normal flow of instruction execution.
Differences between Array and ArrayList

S
Array ArrayList
r

Array is strongly typed. This means that an array can store ArrayList can store any type of
1
only specific type of items\elements items\elements.

In arrays we can store only one datatype either int, string, In arraylist we can store all
2
char etc… the datatype values

ArrayList collection accepts


3 Array cant accept null
null

Arraylist belongs to
Arrays belong to System.Array namespace System.Collection
4
using System; namespaces
using System.Collections;

Example -
Example - ArrayList Arrlst = new
int[] intArray=new int[]{2}; ArrayList();
5
intArray[0] = 1; Arrlst.Add("Sagar");
intArray[2] = 2; Arrlst.Add(1);
Arrlst.Add(null);

Stack
 Stack Allow null and duplicate value.
 Push method is used to insert object in stack.
 Pop method is used to removed object form stack.
 If object is not present in stack and we are trying to remove it will throw an
exception i.e. System.InvalidOperationException
 Peek() method is used to return object from stack without removing it.
Queue

 Peek(): The peek() method of the Queue class is used to return the oldest object i.e.
the object present at the start of the Queue without removing it.
 Enqueue used to insert the object in queue.
 Dequeue delete object form queue.
ArrayList also contain null and duplicate value . We can add null value in array list using
below syntax:
var arlist1 = new ArrayList();
arlist1.Add(1);
arlist1.Add("Bill");
arlist1.Add(" ");
arlist1.Add(true);
arlist1.Add(4.5);
arlist1.Add(null);

Example of boxing and unboxing using arrary list.


https://dotnettutorials.net/lesson/advantages-and-disadvantages-of-collection/
Dictionary
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. In Dictionary,
the key cannot be null, but value can be. A key must be unique. Duplicate keys are not allowed
if we try to use duplicate key then compiler will throw an exception.What is the collection in c# and
which is the collection class?

HashTable
Hashtable will allow us to store duplicate values, but keys must be unique to identify the hashtable
values. In hashtable, the key cannot be null, but the value can be null. You
can access hashtable elements either by using keys or with a foreach loop.

Collection classes are specialized classes for data storage and retrieval

1. ArraryList
2. HashTable
3. SortedList
4. Stack
5. Queue

A generic collection is strongly typed (you can store one type of objects into it) so that we can
eliminate runtime type mismatches, it improves the performance by avoiding boxing and
unboxing.

.Net Collection/Non Generic Collection Generic Collection

Array list List (Generic)

Hash table Dictionary

Stack Generics

Queue Queues Generics


Nullable Type in C#

Value type can not accept the null value. For example int i=null give a compiler time error.

So to stored the null value in C# introduce Nullable type which is use to assign null value to
value type variable.

Nullable<int> i = null;

[Serializable]
public struct Nullable<T> where T : struct
{

? operator also use to define null value in C#

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

?? Operator

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

int? i = null;

int j = i ?? 0;

Console.WriteLine(j);

Output is 0.

Difference between Stack and Queue Data Structures


Stacks Queues

Stacks are based on the LIFO


principle, i.e., the element inserted Queues are based on the FIFO principle, i.e., the
at the last, is the first element to element inserted at the first, is the first element to
come out of the list. come out of the list.

Insertion and deletion in queues takes place from the


Insertion and deletion in stacks opposite ends of the list. The insertion takes place at
takes place only from one end of the rear of the list and the deletion takes place from
the list called the top. the front of the list.
Stacks Queues

Insert operation is called push


operation. Insert operation is called enqueue operation.

Delete operation is called pop


operation. Delete operation is called dequeue operation.

In stacks we maintain only one In queues we maintain two pointers to access the list.
pointer to access the list, called the The front pointer always points to the first element
top, which always points to the last inserted in the list and is still present, and the rear
element present in the list. pointer always points to the last inserted element.

Stack is used in solving problems Queue is used in solving problems having sequential
works on recursion. processing.

Difference between Web Service and REST

If we have overloaded method which have 3 add methods with different parameter. Please refer
below example
class Test
{
float myNum = 5.7F;

public void add(int a, int b)


{
Console.WriteLine("This is the integer method ",a,b);
}
public void add(float a, float b)
{
Console.WriteLine("This is the fload method ", a, b);
}
public void add(double a, double b)
{
Console.WriteLine("This is the double method ", a, b);
}

static void Main(string[] args)


{
Test test = new Test();
test.add(1.1, 1.1);
Console.ReadLine();
}

So if we have call add method and pass parameter like 1,1 then integer method will called.
If we passed parameters like 1.1, 1.1 then which method call add with float parameter or add with
double parameter.

Answer is double because float data type store fractional numbers. We should ent the folat vaue
with an “F”.

For example

float myNum = 5.75F;

Console.WriteLine(myNum);

Virtual method cannot be called using derived class object.

Single ton class example or which scenario we can use singleton pattern?

1. Used for Logging


2. Driver Object
3. Cashing
4. Thrad pool
5. Database connection.

Which C# component use interface segregation Principle \?


classes, interfaces also should have a single responsibility. That means we shouldn’t force any class
to implement any method(s) which they don’t require.

Which C# component use Open close principle.


Extension method is the example of open close principle.
LINQ

LINQ IN C#

LINQ or Language Integrated Query allows us to write queries for local as well as remote data
sources such as XML, SQL etc. LINQ will work on any collection class that gears the IEnumerable
interface. The GroupBy operator.

LINQ provides a uniform programming model (i.e. common query syntax) which allows us to work
with different data sources but using a standard or you can say unified coding style. As a result, we
don’t require to learn different syntaxes to query different data sources.

tor returns a group of elements from the given collection based on some key value.

IList<Student> studentList = new List<Student>() {


new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentID = 2, StudentName = "Steve", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", AgIe = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentID = 5, StudentName = "Abram" , Age = 21 }
};

var groupedResult = from s in studentList


group s by s.Age;

//iterate each group


foreach (var ageGroup in groupedResult)
{
Console.WriteLine("Age Group: {0}", ageGroup .Key); //Each group has a key

foreach(Student s in ageGroup) // Each group has inner collection


Console.WriteLine("Student Name: {0}", s.StudentName);
}

Find 2nd higest salary

var employee = Employees


.OrderByDescending(e => e.Salary)
.Skip(1)
.First();

If multiple employees may have equal salary and you wish to return an IEnumerable of all the
employees with the second-highest salary you could do:

var employees = Employees


.GroupBy(e => e.Salary)
.OrderByDescending(g => g.Key)
.Skip(1)
.First();

Var namesAndTotals = customers.

Select(c => new {

c.Name,

TotalOrders = c.Orders.

Where(o => o.OrderDate.Year == year).

Sum(o => o.Total)

});

Difference between LINQ and SQL

The main difference between LINQ and SQL is that LINQ is a Microsoft .net framework component,
which adds native data querying capability to .NET language Which SQL is standard language to store
and manage data in RDBMS.

LINQ provide syntax in language such as C# ,VN.NET etc.. to perform operations on the data
available in various data source and formats.It also reduces the mismatch and complexity between
the usual programming languages and databases. In short, LINQ is a structured query syntax built-
in .NET languages. On the other hand, DBMS is a software that makes it easier to manage data.
Additionally, RDBMS is a DBMS that is designed according to the relational model, and SQL is the
language that helps to perform operations such as insert, update, delete, select in the RDBMS.

IQuerable vs IEnumerable

Both IQuerable and IEnumerable used to hold the collection data and also use to perform
manipulation operations such as filtering, ordering, grouping etc.

IEnumerable:
1. IEnumerable is an interface that is available in the System.Collections namespace.
2. While querying the data from the database, the IEnumerable executes the “select
statement” on the server-side (i.e. on the database), loads data into memory on the client-
side, and then only applied the filters on the retrieved data.
3. So you need to use the IEnumerable when you need to query the data from in-memory
collections like List, Array, and so on.
4. The IEnumerable is mostly used for LINQ to Object and LINQ to XML queries.
5. The IEnumerable collection is of type forward only. That means it can only move in forward,
it can’t move backward and between the items.
6. IEnumerable supports deferred execution.
7. It doesn’t support custom queries.
8. The IEnumerable doesn’t support lazy loading. Hence, it is not suitable for paging like
scenarios.
IQueryable:
1. The IQueryable is an interface that exists in the System.Linq Namespace.
2. While querying the data from a database, the IQueryable executes the “select query” with
the applied filter on the server-side i.e. on the database, and then retrieves data.
3. So you need to use the IQueryable when you want to query the data from out-memory such
as remote database, service, etc.
4. IQueryable is mostly used for LINQ to SQL and LINQ to Entities queries.
5. The collection of type IQueryable can move only forward, it can’t move backward and
between the items.
6. IQueryable supports deferred execution.
7. It also supports custom queries using CreateQuery and Executes methods.
8. IQueryable supports lazy loading and hence it is suitable for paging like scenarios.

First VS Single in LINQ

Single() / SingleOrDefault() First () / FirstOrDefault()

Single() - There is exactly 1 result, an exception First() - There is at least one result, an
is thrown if no result is returned or more than exception is thrown if no result is returned.
one result.
FirstOrDefault() - Same as First(), but not
SingleOrDefault() – Same as Single(), but it can thrown any exception or return null when there
handle the null value. is no result.
Single() asserts that one and only one element First() simply gives you the first one.
exists in the sequence.

When to use When to use

Use Single / SingleOrDefault() when you sure Developer may use First () / FirstOrDefault()
there is only one record present in database or anywhere, when they required single value
you can say if you querying on database with from collection or database.
help of primary key of table.

Single() or SingleOrDefault() will generate a The First() or FirstOrDefault() method will


regular TSQL like "SELECT ...". generate the TSQL statment like "SELECT TOP
1..."

LINQ Providers.

1. LINQ to object- query an in memory object such as array, collection and generic collection.
2. LINQ to SQL- work with SQL server database.
3. LINQ to Dataset-
4. LINQ to Entities: The LINQ to Entities provider looks like LINQ to SQL. It means it is also an
object-relational mapping (ORM) framework that allows one to one, one to many, and many
to many mapping between the database tables and .NET Classes. The point that you need to
remember is, it is used to query any database such as SQL Server, Oracle, MySQL, DB2, etc.
Now, it is called ADO.NET Entity Framework.
5. LINQ to XML- work with the xml document.

Different way to write LINQ query

1. Query Syntax
2. Method Syntax
3. Mixed Syntax (Query + Method)

To write LINQ query we need below things

1. Data Source
2. Query
3. Exceution

Each query is a combination of 3 thigs

1. Initialization
2. Coding
3. Selection
MVC

ViewData and ViewBag and Temp Data

ViewData used to pass data from controller to view.


ViewData is a dictionary of object that are stored and retrieved using strings as key. . Return type of
ViewData is ViewDataDisctionary.
As you can see the ViewDataDictionary class implements the IDictionary interface. So we can say
that the ViewData in ASP.NET MVC is a weakly typed dictionary object. As it is a dictionary object,
so it is going to store the data in the form of key-value pairs where each key must be a string and
the value that we are passing to the dictionary is going to be stored in the form of an object type.

Below is the syntax of the ViewData:


4
// Storing data in ViewData
ViewData["YourData"] = "SomeData";

// Retrieving data from ViewData


string strData = ViewData["YourData"].ToString();

How to Pass and Retrieve data From ViewData in ASP.NET MVC?


The most important point that you need to remember is, as it stores the data in the form of an
object so while retrieving the data from ViewData type casting is required. If you are accessing string
data from the ViewData dictionary, then it is not required to typecast the ViewData to string type.
But it is mandatory to typecast explicitly to the actual type if you are accessing data other than the
string type from the ViewData.

ViewBag

The ViewBag in MVC is one of the mechanisms to pass data form controller to view.
ViewBag uses that dynamic property of the controller base class.

How to Pass and Retrieve data From ViewBag in ASP.NET MVC?


As the ViewBag is operating on the new dynamic data type. The advantage is that we do not require
typecasting while accessing the data from a ViewBag irrespective of the data that we are accessing.

// Storing data in ViewBag


ViewBag.YourData = "SomeData";

// Retrieving data from ViewBag


string strData = ViewBag.YourData;
TempData

As we already discussed in our previous articles, we can use ViewData, ViewBag, and strongly typed
model to pass the data from a controller action method to a view. Now, we will see another
approach to send the data from the controller action method to a view using the TempData.
The limitation of both ViewData and ViewBag is they are limited to one HTTP request only. So,
if redirection occurs then their values become null means they will lose the data they hold. In many
real-time scenarios, we may need to pass the data from one HTTP Request to the next subsequent
HTTP Request. For example, we may need to pass the data from one controller to another controller
or one action method to another action method within the same controller. Then in such situations
like this, we need to use TempData.

As you can see the TempDataDictionary class implements the IDictionary interface. So we can say
that the TempData in ASP.NET MVC is a dictionary object. As it is a dictionary object, so it is going to
store the data in the form of key-value pairs where each key must be a string and the value that we
are passing to the dictionary is going to be stored in the form of an object type.

How to Pass and Retrieve data From TempData in ASP.NET MVC:


The most important point that you need to remember is, as it stores the data in the form of an
object so while retrieving the data from TempData type casting is required. If you are accessing
string value from the TempData, then it is not required to typecast. But it is mandatory to typecast
explicitly to the actual type if you are accessing data other than the string type from the TempData.

Strongly type view

in strongly type view we pass model object as parameter to View() extension method.

In order to create a strongly typed view in ASP.NET MVC, we need to specify the model type within
the view by using the @model directive. As here, the Employee class is going to be the model so we
need to specify the model directive as shown below.
@model FirstMVCDemo.Models.Employee

ViewModel in MVC

In MVC single model object may can not contain all necessary data required . For example, a view
may require different model data. Then in such situations like this, we need to use the concept
ViewModel.

A ViewModel in ASP.NET MVC application is a model which contains more than one model data
required for a particular view. As this model is specific for a particular view, we call this as
ViewModel in MVC.

For example refer

https://dotnettutorials.net/lesson/view-model-asp-net-mvc/

Filter in MVC
What are Filters in ASP.NET MVC Application?

As of now, we discussed when a client makes a request, then that request comes to the Routing
Engine and then the Routing Engine navigates that Request to the Controller. The controller then
selects the appropriate action method to execute. So, it is the Controller action method which is
going to handle the incoming request and send the response back to the client who initially made
the request as shown in the below image.

But what will you do, if you want to execute some code or logic either before or after the action
method executed as shown in the below image?

If that is what you want to achieve then you need to use Filters in ASP.NET MVC application.

There are 5 filers in MVC

1. Authentication Filter (Introduced in MVC 5)


2. Authorization Filter
3. Action Filter
4. Result Filter
5. Exception Filter
Note: This is also the order of the execution of Filters if more than one filter is applied. But the point
that you need to remember is the Exception Filter can be executed at any point in time when there
is an unhandled exception occurred in your application.

What are the Predefined Filters?


Some of the filters are already built by the ASP.NET MVC framework and they are ready to be used.
For example
1. Authorize
2. ValidateInput
3. HandleError
4. RequireHttps
5. OutputCache, etc

We can configured filter in 3 level

1. Global Level

2. protected void Application_Start()


3. {
4. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
5. }
2. Controller Level

[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
//Code
}

3. Action level

public class UserController : Controller


{
[Authorize(Users = "User1,User2")]
public ActionResult LinkToLogin(string provider)
{
// Code
return View();
}
}

Authorization filter

By default all the action methods of all controllers can be accessed by both authenticated and
anonymous users. But If you want the action methods to be available only for the authenticated and
authorized users, then you need to use the Authorization Filter in MVC.

The Authorization Filter provides two built-in attributes such as Authorize and AllowAnonymous
which we can use as per our business requirement

2. Action Filter

Action filter executed before and after an action method executes. Action filter attribute can be
applied to an individual action method or controller .When an action filter is applied to a controller,
it will be applied to all the controller's action methods.
There are some action filder provided by MVC

1. OutputCashe- to use cache the output


2. HandleError- if any exception occurs it redirects the action to custom error page.

[HandleError(view=”Error.cshtml”)]
public ActionResult Index()
{
3. Authorize -authorized user to access the resource.

The OutputCache is a built-in action filter attribute that can be applied to an action method for
which we want to cache the output

[OutputCache(Duration=100)]
public ActionResult Index()
{
return View();
}

You can create a custom action filter in two ways, first, by implementing the IActionFilter interface
and the FilterAttribute class. Second, by deriving the ActionFilterAttribute abstract class.

The IActionFilter interface include following methods to implement:

 void OnActionExecuted(ActionExecutedContext filterContext)


 void OnActionExecuting(ActionExecutingContext filterContext)

4. How to send data from view to controller

We can pass data from view to controller using below 4 approah


 Using Traditional Approach
 Using FormCollection object
 Using the parameters
 Strongly type model binding to view

Traditional Approach

In this approach, we can use the request object of the HttpRequestBase class. This object contains
the input field name and values as name-value pairs in case of the form submit. So we can easily get
the values of the controls by their names using as indexer from the request object in the controller.
For example: Let's say you are having an input in the form with name 'txtName', then its values can
be retrieved in controller from request object like below:
Copy Code
string strName = Request["txtName"].ToString();

FromCollection
Through FormCollection: We can also get post requested data by the FormCollection object. This
object also has requested data as the name/value collection as the Request object.

For example:

Copy Code
[HttpPost]
public ActionResult Calculate(FormCollection form)
{
string strName = form["txtName"].ToString();
....................
}

Through Parameters:

We can also pass the input field names as parameters to the post action method by keeping the
names same as the input field names. These parameters will have the values for those fields and the
parameter types should be string. Also, there is no need to define the parameters in any specific
sequence.

For example:

Copy Code
[HttpPost]
public ActionResult Calculate(string txtName)
{
string strName = Convert.ToString(txtName);
.....................................
}

Strongly Type
Strongly typed model binding to view: Here, we need to create a strongly typed view which will bind
directly the model data to the various fields of the page.

For example:
Create a model with the required member variables.
Let's say we have a model named 'Person' with member variable named as 'Name'
Now pass the empty model to the view as parameter in the controller action.
For example:
Copy Code
public ActionResult GetName()
{
Person person = new Person();
return View(person);
}
i. Prepare the strongly typed view to display the model property values through html elements as
below:

For example:
Copy Code
<div><%= Html.Encode(person.Name) %></div>
ii. Create the action method that handles the POST request & processes the data.

For example:

[HttpPost]
public ActionResult GetPersonName(Person person)
{
return Content(person.Name.ToString());
}

2. Action Result

What is the Action method in MVC?

All the public method inside a controller which respond to the URL is know is Action method.

1. The action method must be public.


2. It cannot be overloaded
3. It cannot be a static method
4. ActionResult is a base class of all the result type action methods.

What is the Action Result in MVC?

Action result is the result of action method or return type of action method. The action result is the
abstract class. It is the base class of all types of result.

There are two method in the action result.


 Action Result
 Execute Result

Type of Action Result

There are different types of action results in ASP.NET MVC. Each result has a different type of result
format to view page. ActionResult is the base class of all the result type action method. The
following are the Result types that an action method can return in MVC.
1. ViewResult – Represents HTML and markup.
2. EmptyResult – Represents no result.
3. RedirectResult – Represents a redirection to a new URL.
4. JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX
application.
5. JavaScriptResult – Represents a JavaScript script.
6. ContentResult – Represents a text result.
7. FileContentResult – Represents a downloadable file (with the binary content).
8. FilePathResult – Represents a downloadable file (with a path).
9. FileStreamResult – Represents a downloadable file (with a file stream).

There are different type of result. These result are categorized into three sections:
These results are categorized into three sections:
1. Content-returning
2. Redirection
3. Status.

Content-returning:
These ActionResults are responsible for returning content to the browser or calling script. The
examples are as follows
1. ViewResult
2. PartialViewResult
3. FileResult
4. ContentResult
5. EmptyResult
6. JsonResult
7. JavaScriptResult

Redirection:
These ActionResults are responsible for redirecting to other URLs or actions. The examples are as
follows
1. RedirectResult
2. RedirectToRouteResult
3. RedirectToActionResultV
Status:
These ActionResults are responsible for returning status codes to the browser for it to use. The
examples are as follows
1. HttpStatusCodeResult
2. HttpUnauthorizedResult
3. HttpNotFoundResult

View Result
View result returns basic results to the view page. The View Result can return data to the View Page
through the model class. The view page is a simple HTML page. Here view page has a “.cshtml”
extension.

Partial View Result


We can also specify an action to return a partial view instead of a regular view: The Partial View
Result is returning the result to a Partial view page

File Result

The File Result returns different type of file format view when we implement the file download
concept in MVC using file result. Let us understand File Result with an example. Please modify the
HomeController as shown below.
public class HomeController : Controller
{
public FileResult Index()
{
return File("Web.Config", "text");
}
}
If you want to return a file from your action method then you need to use this File Result as the
return type of your action method. Moreover, depending on the overload version of the File you
use, you can specify what action the browser is going to take with the downloaded file.

Content Result
The Content Result in ASP.NET MVC returns different content format to the view like HTML format,
JavaScript format, and any other format.

Let us modify the HomeController as shown below to use Content Result in MVC.
public class HomeController : Controller
{
public ContentResult Index()
{
return Content("<h3>Here's a custom content header</h3>", "text/html");
}
}
Calling this action will display the h3 tag in the browser.

Redirect Result

f you wanted to redirect to a URL, then you can use RedirectResult, like this:
public class HomeController : Controller
{
public RedirectResult Index()
{
return Redirect("https://dotnettutorials.net");
}
}
That works great for redirecting to outside sites from the current application, but not so much for
redirecting to other pages within the same application. For that, we can use RedirectToRouteResult.
Redirect result is returning the result to a specific URL. It is rendered to the page by URL. If we
give the wrong URL, it will show 404-page errors.

RedirectToRoute Result in MVC


RedirectToRouteResult is used whenever we need to go from one action to another.
public class HomeController : Controller

public RedirectToRouteResult Index()

return RedirectToRoute(new { controller = "Home", action = "About" });

}
RedirectToAction Result in MVC
The RedirectToAction Result is returning the result to a specified controller and action method.
Controller name is optional in RedirectToAction method. If not mentioned, Controller name redirects
to a mentioned action method in the current Controller. Suppose action name is not available but
mentioned in the current controller, then it will show a 404 error page.
public class HomeController : Controller

public ActionResult Index()

return RedirectToAction("Login", "Account");

6. Routing in MVC

The ASP.NET Routing module is responsible for mapping the incoming browser requests (i.e. the
incoming URL) to a particular MVC controller action method. This mapping is done by the routing
rules defined for your application.

There are 2 types of Routing supported by Asp.net MVC

1. Conversion base routing

2. Attribute base routing

How does the Routing in ASP.NET Web Form?

In the asp.net application each and every URL should be match with sapcific .aspx file. example, a
URL http://dotnettutorials/employeeinfo.aspx must match with a physical file i.e.
employeeinfo.aspx that contains necessary code and HTML for rendering the response to the
browser. So in case of ASP.NET Web Forms, the URL pointing to the file must have its physical
existence.

Then ASP.NET Framework introduced the concept of Routing to eliminate the needs of mapping
each and every URL to a physical file. The Routing enables us to define the URL pattern that maps to
the request handler. This request handler can be a class or file.
In case of ASP.NET Webform application, the request handler is a file (i.e. aspx file) and in case of
ASP.NET MVC Framework, the request handler is the Controller Actions. For
example, http://dotnettutorials/employees can be mapped to
http://dotnettutorials/employeeinfo.aspx in ASP.NET Webforms application and the same URL can
be mapped to Employee Controller and Index action method in ASP.NET MVC application.

What is the route in asp.net MVC.

Route is handle the incoming requests to map the appropriate controller action method. In simple
word routing is pattern maching machnisum that handle the incoming request and figure out what
to do with that incoming request. All the configured routes of an ASP.NET MVC application stored in
the RouteTable and this Route table will be used by the Routing engine to determine the appropriate
handler class or file for an incoming request. We can register one or more URL patterns to the Route
table at Application_Start event.

How to configure Route?

Route is configured in the RouteConfig class which is in RourteConfig.cs file under the App_Start
folder. By Default MVC framework provide one default route.

namespace FirstMVCDemo
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default", //Route Name
url: "{controller}/{action}/{id}", //Route Pattern
defaults: new
{
controller = "Home", //Controller Name
action = "Index", //Action method Name
id = UrlParameter.Optional //Defaut value for above defined parameter
}
);
}
}
}

How to register route in asp.net.

After configuring the routes in RouteConfig class, you need to register it in


the Application_Start() event in the Global.asax file. So that it includes all your routes into the
RouteTable.
Global.asax
namespace FirstMVCDemo
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}

MVC framework evaluates each route in sequence. It starts with the first configured route and if
incoming URL doesn’t satisfy with the First URL pattern of the route then it will evaluate the second
route and so on.

Route Constraints

The Route Constraint in ASP.NET MVC Routing allows us to apply a regular expression to a URL
segment to restrict whether the route will match the request. In simple words, we say that Route
constraint is a way to put some validation around the defined route.

Suppose we have route and we want to restrict the incoming request URL with numirec id only.

routes.MapRoute(
name: "Default", //Route Name
url: "{controller}/{action}/{id}", //Route Pattern
defaults: new
{
controller = "Home", //Controller Name
action = "Index", //Action method Name
id = UrlParameter.Optional //Defaut value for above defined parameter
},
constraints :new { id = @"\d+" } //Restriction for id
);

What is the difference between Routing and URL Rewriting ?

URL rewriting is focused on mapping one URL (new URL) to another URL (old URL) while routing is
focused on mapping a URL to a resource.
URL rewriting rewrites your old URL to a new one while routing never rewrites your old URL to a new
one but it maps to the original route.

How is the routing table created in ASP.NET MVC?


When an MVC application first starts, the Application_Start() method in global.asax is called. This
method calls the RegisterRoutes() method. The RegisterRoutes() method creates the routing table
for the MVC application

Attribute Routing

Using the [Route] attribute to define routes is called Attribute Routing. It provides you more control
over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application.

How use attribute routing in MVC.

The first thing that you need to do is Enabling Attribute Routing in RouteConfig.cs class.

Need to add routes.MapMvcAttributeRoutes() method within RegisterRoutes() method


of RouteConfig.cs file.

And then add the Route attribute in the controller action mehtod

[HttpGet] [
Route("students/{studentID}/courses")]
public ActionResult GetStudentCourses(int studentID) {
}

What are the advantages of using Attribute Routing in ASP.NET MVC5?


1. It gives us more control over the URIs than convention-based routing. Creating URI patterns
like hierarchies of resources (For example, students have courses, Departments have
employees) is very difficult with convention-based routing.
2. Reduces the chances for errors, if a route is modified incorrectly in RouteConfig.cs then it
may affect the entire application’s routing.
3. May decouple controller and action names from route entirely.
4. Easy to map two routes pointing to the same action.

RoutePrefix attribute is used to specify the common route prefix at the controller level to eliminate
the need to repeat that common route prefix on each and every controller action method

Example

namespace AttributeRoutingDemoInMVC.Controllers
{
[RoutePrefix("students")]
public class StudentsController : Controller
{
static List<Student> students = new List<Student>()
{
new Student() { Id = 1, Name = "Pranaya" },
new Student() { Id = 2, Name = "Priyanka" },
new Student() { Id = 3, Name = "Anurag" },
new Student() { Id = 4, Name = "Sambit" }
};
[HttpGet]
[Route]
//This will be translated to /students
public ActionResult GetAllStudents()
{
return View(students);
}
[HttpGet]
[Route("{studentID}")]
//This will be translated to /students/2
public ActionResult GetStudentByID(int studentID)
{
Student studentDetails = students.FirstOrDefault(s => s.Id == studentID);
return View(studentDetails);
}
}
Controller in MVC

A controller in ASP.NET MVC is a class having a set of public methods. These public methods of the
controller are called action methods or simple actions. It is these action methods in MVC application
which is going to handle the incoming HTTP Requests.

View in MVC

In the MVC pattern, the view component contains the logic to represent the model data as a user
interface with which the end user can interact. Typically, it creates the user interface with the data
from the model which provided to it by the controller in an MVC application. So you can consider the
Views in ASP.NET MVC as HTML templates embedded with Razor syntax which generate HTML
content that sends to the client. the views are having “.cshtml” extension

Model in MVC

The Models in ASP.NET MVC application are the component which contains a set of classes that are
used to represent the business data as well as it also contains logic to manage the business data. So
in the simple word we can say that the model in ASP.NET MVC is used to manage the domain data
i.e. the state of the application in memory.

7. Authentication in MVC

Authentication is nothing but a process that ensures and confirms a user’s identity. In other words,
we can say that it is a process to validate someone against some data source.

What is Authorization?
Authorization is a security mechanism which is used to determine whether the user has access to a
particular resource or not. The most point that you need to remember is, authentication happens
first, then only authorization

Type of authentication

1. Forms Authentication: In this type of authentication the user needs to provide his
credentials through a form.
2. Windows Authentication: Windows Authentication is used in conjunction with IIS
authentication. The Authentication is performed by IIS in one of three ways such as basic,
digest, or Integrated Windows Authentication. When IIS authentication is completed, then
ASP.NET uses the authenticated identity to authorize access
3. Passport Authentication: It is a centralized authentication service (paid service) provided by
Microsoft which offers a single logon and core profile services for member sites.
4. None: No Authentication provided. This is default Authentication mode

Form Authenticatin

In web.config file of your application, you can specify the Authentication mode as shown below.
Form authentication

Implementing Forms Authenticatin in MVC:


The Forms Authentication is available in System.Web.Security namespace. In order to implement
the Forms Authentication in MVC application, we need to do the following three things
1. Set the Authentication mode as Forms in the web.config file
2. We need to use FormsAuthentication.SetAuthCookie for login
3. Again we need to use FormAuthentication.SignOut for logout

What is the use of Form Authentiction SetAutCookie.


Creates an authentication ticket for the supplied user name and adds it to the cookies collection of
the response, or to the URL if you are using cookieless authentication.

SignOut
The SignOut method removes the forms-authentication ticket information from the cookie or the
URL if CookiesSupported is false . You can use the SignOut method in conjunction with the
RedirectToLoginPage method to log one user out and allow a different user to log in.

8. Token base Authentication in MVC

How token base authentication work

1. The user enters his credentials (i.e. the username and password) into the client (here client
means the browser or mobile devices, etc).
2. The client then sends these credentials (i.e. username and password) to the Authorization
Server.
3. Then the Authorization Server authenticates the client credentials (i.e. username and
password) and generates and returns an access token. This Access Token contains enough
information to identify a user and also contains the token expiry time.
4. The client application then includes the Access Token in the Authorization header of the
HTTP request to access the restricted resources from the Resource Server until the token is
expired.

Steps to create token base authentication

1. Create required database table like user details user name and password
2. Create the Empty application.
3. Add the required references from NuGet packages into your application.
1. Microsoft.Owin.Host.SystemWeb
2. Microsoft.Owin.Security.OAuth
3. Microsoft.Owin.Cors
4. Newtonsoft.json
For adding the above references from NuGet, Go to Solution Explorer > Right Click on the
References > Click on Manage NuGet Packages > Search for
the Microsoft.Owin.Host.SystemWeb,
Microsoft.Owin.Security.OAuth, Microsoft.Owin.Cors and Newtonsoft.json and install.

4. Add the ADO.NET entity model with userMaster table and the Validate method that
take the username and password as input parameter and validate its.
5. Add a class for validating the user credentials asking for tokens- here add to class in
our application and need to write logic to validate the user credential and generate
the token. We need to inherit class from OAuthAuthorizationServerProvider and
then need to override
ValidateClientAuthentication and GrantResourceOwnerCredentials method.

ValidateClientAuthenticaiton - The ValidateClientAuthentication method is used


for validating the client application.

GrantResourceOwnerCredentials - The GrantResourceOwnerCredentials method is


used to validate the client credentials (i.e. username and password). If it found the
credentials are valid, then only it generates the access token. The client then using
this access token can access the authorized resources from the Resource Server.

6. Add the OWINStartup class.

Now we need to add the OWINStartup class where we will configure the OAuth
Authorization Server. This is going to be our authorization server.

To do so, go to the Solution Explorer > Right Click on Project Name form the Solution
Explorer > Add > New Item > Select OWIN Startup class > Enter the class name
as Startup.cs > and then click on the Add button as shown in the below image.

Understanding the Owin Startup class code:

Here we created a new instance of the OAuthAuthorizationServerOptions class and then set
its options as follows:

1. Here, we set the path for generating the tokens


as “http://localhost:portnumber/token”. Later we will see how to issue an HTTP
Post request to generate the access token.
2. We have specified the expiry time for the access token as 24 hours. So if the user
tried to use the same access token after 24 hours from the issue time, then this
request will be rejected and HTTP status code 401 will be returned.
3. We also specified the implementation on how to validate the client credentials for
users asking for the access tokens in the custom class
named MyAuthorizationServerProvider.

Finally, we passed the options to the extension


method UseOAuthAuthorizationServer which will add the authentication middleware to the
pipeline.

9. Model Binding
The ASP.NET MVC Model Binding allows us to map HTTP request data with a model. It is the
process of creating .NET objects using the data sent by the browser in an HTTP request.

Model binding is a well-designed bridge between the HTTP request and the C# action
methods. It makes it easy to work with data on forms (views) because POST and GET are
automatically transferred into a data model we specify. ASP.NET MVC uses default binders
to complete this behind the scene.

To bind POST data we use following 2 approach.

 UpdateModel
 TryUpdateModel

UpdateModel -function capture the posted form data.In order to do this, please modify the
Create (HttpPost) action method as shown below.

[HttpPost]
public ActionResult Create()
{
if (ModelState.IsValid)
{
EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
Employee employee = new Employee();
UpdateModel<Employee>(employee);
employeeBusinessLayer.AddEmmployee(employee);
return RedirectToAction("Index");
}
return View();
TryUpdateModel
This is also use for capture the posted from data.

Now let’s understand how to use the TryUpdateModel function in ASP.NET MVC. Modify the create
(HttpPost) action method as shown below. Here we use TryUpdateModel() instead of
UpdateModel().
[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post()
{
EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
Employee employee = new Employee();
TryUpdateModel(employee);
if (ModelState.IsValid)
{
employeeBusinessLayer.AddEmmployee(employee);
return RedirectToAction("Index");
}
else
{
return View();
}
}

The difference is UpdateModel() throws an exception if validation fails whereas TryUpdateModel()


will never throw an exception. The similarity is both the functions are used to update the Model with
the Form values and perform the validations.

https://stackoverflow.com/questions/102558/biggest-advantage-to-using-asp-net-mvc-vs-web-
forms

10. Global Filter

You can apply filters at a global level in the Application_Start event of the global.asax.cs file by using
default FilterConfig.RegisterGlobalFilters() method. The global filters will be applied to all the
controller and action methods of an application.

11. MVC Life cycle

When the client makes a request, and if it is the first request to the application then
the Application_Start event is going to be fired. the Application_Start event calls
the RegisterRoutes Method of the RouteConfig class which will fill the RouteTable with the routes
defined for your application. Then the Request comes to the Routine module.

1. Routing module

The aim of the Routing Module in ASP.NET MVC Application is very simple. It just maps the
incoming request i.e. URL to a Route and then selects the HttpHandler which is associated with the
Route to handle that Request.
As shown in the above image, we can say that the Routing Module is the first module in the
ASP.NET MVC Request Processing Pipeline which receives the incoming request made by the client.
Once it receives the incoming request, then it tries to find a matching URL pattern defined in the
Route Table. If it does not find any matching URL pattern in the Route table then it simply returns
a 404 HTTP Status code to the client.
On the other hand, if it found a matching URL Pattern in the Route table, then it selects the HTTP
Handler (a handler that implements the IHttpHandler interface) which is associated with
that Route and then forward that request to the corresponding handler.

2. MvcHandler

The purpose of the MVC Handler in the ASP.NET MVC application is to create the Controller
Instance which is going to process the current request. MVCHandler take the RequestContext object
as its parameter From URL it get controller name and pass request to the controller.

3. Controller

The purpose of the Controller in ASP.NET MVC Request Processing Pipeline is to call
the ActionInvoker method of the Controller class to deal with the current request.

In the ASP.NET MVC application, the Controller class implements the IController interface as well as
it also inherits from the ControllerBase class. The ControllerBase class exposes the Execute method
which is called by the MvcHandler by providing the RequestContext object as a parameter.

Once the Execute method is called, then it calls the ExecuteCore method of the ControllerBase class.
It gets action method name from RequestContext and pass to Action invoker

4. Action Invoker

The Role of Action Invoker in ASP.NET MVC Request Life Cycle is to execute the Action Method
passed to it by the controller.

The ActionInvoker class implements the IActionInvoker interface. The IActionInvoker interface has
a single method i.e. InvokeAction
The ControllerActionInvoker calls the FindAction method to find the information about the Action
method which is going to be executed.

The ActionInvoker then calls the Authentication filters to verify if the user is authenticated or not. If
the user is an authenticated user then it calls the authorization filters to check whether the user is
authorized to this action method or not.
If the user is an authorized user then the ActionInvoker calls the Model Binder object to map the
request parameters to the Action Method parameters. This process is called Model Binding in the
ASP.NET MVC application.
Then it calls the Action Filters to add the pre and post-processing logic. Finally,
the ControllerActionInvoker calls the InvokeAction method to execute the action method and
returns the ActionResult.

4. Result Exection

The Role of Result Execution in ASP.NET MVC application is to render the view as a web page to the
client who initially made the request.

Once the Result is generated, then the Result Filters are going to be applied before sending the Final
Response to the browser.

How to pass data from controller to controller in MVC

Using TempData we can pass data from controller to controller

What is the MVC

The ASP.NET MVC is an open-source web application development framework from Microsoft that
is based on the MVC (Model-View-Controller) architectural design pattern which provides a clean
separation of code. This is the most customizable and extensible platform or framework provided by
Microsoft.

The Request flow for the ASP.NET MVC framework is as follows:


In the ASP.NET MVC application when the client makes a request for a resource from the browser
then that request is handled by the Routing engine and then the routing engine navigates that
request to the appropriate Controller. Then the controller plays its role and executes the action
method based on the user action and if needed then it works with the model object in order to serve
the request. Once it works with the model, then it passes that model to a view, and that view
transforms that model and generates an appropriate response that is rendered to the client.

How to make a Non-Action method in ASP.NET MVC?


By default, the ASP.NET MVC framework treats all public methods of a controller class as action
methods. If you do not want a public method to be an action method, you must mark that method
with the NonActionAttribute attribute.
[NonAction]

public void DoSomething()

{
// Method logic

}
Can you change the action method name?
We can also change the action method name by using the ActionName attribute. Now action
method will be called by the name defined by the ActionName attribute.
[ActionName("DoAction")]

public ActionResult DoSomething()

//TODO: return View();

How to restrict an action method to be invoked only by HTTP GET, POST, PUT or DELETE?
By default, each and every action method can be invoked by an HTTP request (i.e. GET, PUT, POST,
and DELETE). But you can restrict an action to be invoked only by a specific HTTP request by applying
HttpGet or HttpPost or HttpPut or HttpDelete attribute.

What are the Layouts in ASP.NET MVC?


Layouts are used to maintain a consistent look and feel across multiple views within the ASP.NET
MVC application. As compared to Web Forms, layouts serve the same purpose as master pages but
offer a simple syntax and greater flexibility. A basic structure of layout is given below:
<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<meta name="viewport" content="width=device-width" />

<title>@ViewBag.Title</title>

@Styles.Render("~/Content/css")

@Scripts.Render("~/bundles/modernizr")

</head>

<body>

@RenderBody() @Scripts.Render("~/bundles/jquery")

@RenderSection("scripts", required: false)


</body>

</html>

What is the view engine in asp.net MVC?

View Engine is responsible for rendering the view into Html form to the browser. ASP.NET MVC
supports web form(.aspx) and Razor View (.cshtml).

View Engine is used to convert HTML + programming language to pure HTML. View can contain C#
and HTML code. Once the view renders on the browser, the C# code written on the view is
converted into pure html format. To Convert C# code pure HTML is the job of ViewEngine.

diffracted attribute routing on controller and action method

roteprfix on controller and route on action method

To insert,retrive and update data in MVC below method are used.

1. AddEmployee
2. UpdateEmployee
3. GetAllEmployee

JavaScript/jQuery

1. What is the Promises?

JavaScript is single-threaded long-running operations that block other operations. In


JavaScript code is executed synchronously that is in sequential order that we saw in the
previous article of callback one. Synchronous means the code is executed one by one like
one line is executed then the next line is executed and so on. This means each statement has
to wait for the previous statement to finish executing. Long-running JavaScript functions can
make the UI or server unresponsive until the function has returned. This can make a terrible
user-experience.
Asynchronous operation in JavaScript breakup long operation into shorter ones so other
operations can execute. Asynchronous delayed execution by postponing the heavy
operation to the end of the event loop, to give event handlers the ability to respond.
Asynchronous code takes statements outside of the main program flow, allowing the code
to run without blocking and waiting for the result or other to finish. Anything that needs to
wait for the promise to proceed, we need to put this in.then().

What is Promise?
In JavaScript promise is the same as a promise we make in real life. When we make a
promise in real life, it is assured that we are going to do keep in the future. As promises can
only be made for the future.

In JavaScript, a Promise is used for performing asynchronous operations. It represents a


result that may be available now, or in the future or never. Promises are easy to manage
when dealing with multiple asynchronous operations.
Where to use Promises
When we are using API and want to make an asynchronous call to remote web services and
requesting some data from web service then the JavaScript promise promises us to get data
from web services and we can use it in the future. It is used for handling asynchronous
events and It’s mostly used for handling the asynchronous HTTP requests

A promise has three states:


1. Pending: A promise starts in the pending state which says that the promise has not
yet completed and ends in either fulfilled(success) state or rejected(fail) state.
2. Fulfilled: The operation has finished, and the promise is fulfilled with a value.
3. Rejected: An error has occurred during the operation, and the promise is rejected
with an error.

The Constructor syntax for a promise object:


let promise=new Promise((resolve, reject) => { … })

https://dotnettutorials.net/lesson/javascript-promise/

2. What is Colures
 A Closures is nothing but a function inside the function.
 In other words, a closure gives you access to an outer function’s scope from an inner
function.
 Closures are nothing but Stateful Function

what is the use of such isolated stateful functions (i.e. closures). The simplest answer to this
question is, closures help us to implement object-oriented programming concepts in
JavaScript.

3. Namespaces in Javascript

Namespace like the container which contain classes. In javascript you can achieve the same
functionality as namespace by creating nested object.
In any modern day application, Namespace is a must to have because at the end, we need
third party libraries and components.
Unfortunately JavaScript doesn’t provide namespace by default. So anything
(function, method, object, variable) we create in JavaScript is global and we continue
polluting that global namespace by adding more to that.
But the good news is that we can create namespace in JavaScript and that too very easily.
As we know, in JavaScript everything is an object and creating an object is very simple. We
can achieve namespace very easily with some minor tweaks.

Let's See How JavaScript Makes All Things Global


//declare a function
function calculateTax(item) {
return item.price * 1.40;
}

var product = function (cost) {

this.cost = cost;
this.getCost = function(){
return this.cost;
};
};

function doTaxCalculations() {

var p = new product(100);


alert(calculateTax(p.getCost()));
}

In the above code, the two functions and the class, all three are settled down in the global space.
It's a simple code base but it contains 3 global items (calculateTax, product, doTaxCalculations).
These three will really put us in trouble if we are using 3rd party libraries and they also contain the
same name.
Like if it is used before other library, it will be overridden by Library and vice versa.

JavaScript Sample Namespace

In JavaScript, it is nothing but a single global object which will contain all our functions, methods,
variables and all that. Here ‘MYAPPLICATION‘ is acted as a JavaScript namespace and the only global
object which contains all other items.

var MYAPPLICATION = {
calculateTax: function (item) {
return item * 1.40;
},
product: function (cost) {
this.cost = cost;
this.getCost = function(){
return this.cost;
};
},
doTaxCalculations: function () {
var p = new MYAPPLICATION.product(100);
alert(this.calculateTax(p.getCost()));
}
}

To access any of the methods or variables, you need to fetch it through the MYAPPLICATION.

var newProduct = new MYAPPLICATION.product(200);


alert(p.getPrice());

Not only single namespace like the above one, but we can create nested JavaScript Namespace as
well.
Let's look at a sample of nested JavaScript Namespace.

4. Design Pattern

Design patterns are generally sets of standardized practices used in the software development
industry. Design Patterns represent the solutions given by the community to general problems faced
in every-day tasks regarding software development.

Explain the advantages of Java design pattern?


o The Design Patterns are reusable in multiple projects.
o The Design Patterns provide a solution that helps to define the system architecture.
o The Design Patterns capture software engineering experiences.
o The Design Patterns provide transparency to the design of an application.
o They are testified and well-proved since they have been built upon the knowledge and
experience of expert software developers.

Creational patterns

o Factory method/Template
o Abstract Factory
o Builder
o Prototype
o Singleton

Structural patterns

o Adapter
o Bridge
o Filter
o Composite
o Decorator
o Facade
o Flyweight
o Proxy

Behavioral patterns

o Interpreter
o Template method/ pattern
o Chain of responsibility
o Command pattern
o Iterator pattern
o Strategy pattern
o Visitor pattern

J2EE patterns

o MVC Pattern
o Data Access Object pattern
o Front controller pattern
o Intercepting filter pattern
o Transfer object pattern

5. JQuery Selector

jQuery selectors allow you to select and manipulate HTML element(s).

jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types,
attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in
addition, it has some own custom selectors.

you will start with selector function $() in the jQuery.

$("p")
The # Selector

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.

An id should be unique within a page, so you should use the #id selector when you want to find a
single, unique element.

$("#test")

Example

When a user clicks on a button, the element with id="test" will be hidden:

Example

$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});

The .class Selector

The jQuery .class selector finds elements with a specific class.

$(".test")

https://www.w3schools.com/jquery/jquery_selectors.asp

6. JavaScript Scoping

Scope determines the accessibility (visibility) of variables.

JavaScript Function Scope


In JavaScript there are two types of scope:
 Local scope-Variable declared within JavaScript function become local variable. That is only
accessed within funtion
 Global scope- A variable declared outside a function, becomes GLOBAL. A global variable
has global scope: All scripts and functions on a web page can access it.

JavaScript has function scope: Each function creates a new scope.Scope determines the accessibility
(visibility) of these variables.
Variables defined inside a function are not accessible (visible) from outside the function.

7. Null and Undefined in javascript

Undefined
It means a variable declared, but no value has been assigned a value.
For example,

var demo;
alert(demo); //shows undefined
alert(typeof demo); //shows undefined

null
Whereas, null in JavaScript is an assignment value. You can assign it to a variable.
For example,

var demo = null;

alert(demo); //shows null

alert(typeof demo); //shows object

SQL Server

Merged keywork in SQL

The MERGE statement selects the rows from one or more tables (called Source table),
and based on conditions specified, INSERT or UPDATE data to another table (called
Target table).

MERGE INTO TargetTable AS T


USING SourceTable AS S
ON T.id=S.id
WHEN MATCHED --When T. ID = S.ID behind the above, the ID of the ID is 1, 2 is
updated.
THEN UPDATE SET T.[DESC]=S.[DESC]
WHEN NOT MATCHED --There is no ID in the target table, in the source table, then
insert the relevant data
THEN INSERT VALUES(S.id,S.[DESC])
WHEN NOT MATCH

1. SQL ACID Properties

 Atomicity - The atomicity acid property in SQL. It means either all the operations (insert,
update, delete) inside a transaction take place or none. Or you can say, all the statements
(insert, update, delete) inside a transaction are either completed or rolled back.
 Consistency: This SQL ACID property ensures database consistency. It means, whatever
happens in the middle of the transaction, this acid property will never leave your database in
a half-completed state.

o If the transaction completed successfully, then it will apply all the changes to the
database.
oIf there is an error in a transaction, then all the changes that already made will be
rolled back automatically. It means the database will restore to its state that it had
before the transaction started.
o If there is a system failure in the middle of the transaction, then also, all the changes
made already will automatically rollback.
 Isolation: Every transaction is individual, and One transaction can’t access the result of other
transactions until the transaction completed. Or, you can’t perform the same operation using
multiple transactions at the same time.
 Durability: Once the transaction completed, then the changes it has made to the database
will be permanent. Even if there is a system failure, or any abnormal changes also, this SQL
acid property will safeguard the committed data.

2. SQL Server joins

Joins in SQL server are used to retrieve data from 2 more related table. In general, tables are
related to each other using foreign key constraints. An SQL JOIN is used to combine rows from
two or more tables based on a common field between them.

What is the default JOIN in SQL Server?


The default join of joins is INNER JOIN.
What is the default join of outer join?
The default join of the outer join is a full outer join.
Explain about EQUI Join in SQL Server:
When we retrieve the data from the table based on equality condition then it is known as EQUI
join. (Use equal “=” operator only). It is NON-ANSI format join. Hence when we make a query for
join using an equality operator, then that join query comes under EQUI join.

 Inner Join
Inner join returns only the matching rows between both the tables. Non-matching rows
are eliminated. The inner join is used to retrieve matching data from both the tables.
 Outer Join
The OUTER JOIN is an extension of INNER JOIN or EQUI JOIN. In an inner join, the user
will get matching data only from the tables i.e. the user will lose un-matching data from
the tables. So to overcome the above problem we use the outer join mechanism

Outer join again classified in to three types


o Left Outer Join -It retrieves matching data from both the tables and also un-
matching data from the left side table only. Un-matching data take null value in
this case.
o Right Outer Join-It retrieves matching data from both the tables and also un-
matching data from the right side table.
o Full outer join-t retrieves matching data and also un-matching data from both
tables at a time.
 Cross Join

If two or more tables are combined with each other without any condition we call it a
Cartesian or cross join. When we join the records without any condition is known as
CROSS JOIN. In cross join, each record of a table is joins with each record of another
table. Cross Join should not have an ON clause
 Non Equi join
When we retrieve the information from the tables with any condition except equality
condition then it is known as NON-EQUI JOIN. We may use <, >, <=,>=, <!,>!, AND, OR,
NOT, etc except “=” operator.
 Self Join
Joining a table by itself is called a self-join. When we have some relation between the
columns within the same table then we use the self-join mechanism. When we
implement a self-join mechanism we should create the alias for the table. We can create
any number of aliases for a single table. Self-join is not a different kind of join.

https://dotnettutorials.net/lesson/sql-server-joins-interview-questions-answers/

Differences between UNION and UNION ALL in SQL Server:


Both UNION and UNION ALL are used to combines the result-set of two or more select queries into a
single result-set. The difference between these two is UNION removes duplicate rows whereas
UNION ALL does not. When use UNION, to remove the duplicate rows, the SQL server has to do a
distinct sort which is time-consuming. For this reason, the UNION ALL is much faster than UNION.

3. Stored Procedure

When we create a stored procedure, the syntaxes are checked while creating the procedure or we
can say at the design pattern. When we execute the procedure for the first time, the best plan is
selected and is cached in memory. And after that whenever we execute the stored procedure, the
query execution plan is taken from the cache rather than creating again and again and executed.

What is a Stored Procedure in SQL Server?


A SQL Server Stored Procedure is a database object which contains pre-compiled queries (a group of
T-SQL Statements). In other words, we can say that the Stored Procedures are a block of code
designed to perform a task whenever we called.

Index in SQL
1. It is a database object which is used to speed up the querying process by providing query
access to rows in the data table.
2. When we create an index on any column SQL Server internally maintains a separate table
called index table so that when any user trying to retrieve the data from the existing table
depends on index table SQL Server directly go to the table and retrieve required data very
quickly.
3. In a table, we can use a maximum of 250 indexes. The index type refers to the way the index
is stored internally by SQL Server.
4. Index are created on tables and views.

Indexes divided into 2 parts

 Clustered Index
 Non-Clustered Index

Clustered Index

1. In the case of a clustered index, the arrangement of the data in the index table will be the
same as the arrangement of the data of the actual table.
2. Example: The index we find the start of a book.
3. When a table has a clustered index then the table is called a clustered table.
4. If a table has no clustered index its data rows are stored in an unordered structure.’
5. A table can have only one clustered index in it which will be created when the primary key
constraint used in a table.
6. A clustered index determines the physical order of data in a table. For this reason, a table
can have only one clustered index.

What is Composite Clustered Index in SQL Server?


It is possible in SQL Server to create the clustered index with multiple columns and if we do so, then
it is called a composite clustered index.

CREATE CLUSTERED INDEX IX_Employee_Gender_Salary ON Employee(Gender DESC, Salary ASC)

Non-Clustered Index

1. In the case of a non-clustered index, the arrangement of data in the index table will be
different from the arrangement of the actual table.
2. A non-clustered index is analogous to an index in a textbook. The data is stored in one place,
the index is another place. The index will have pointers to the storage location of the data.
3. Since, the non-clustered index is stored separately from the actual data a table can have
more than one non clustered index, just like how a book can have an index by chapters at
the beginning and another index by common terms at the end.
4. In the index itself, the data is stored in an ascending or descending order of the index key
which does not in any way influence the storage of data in the table.
5. In a table, we can create a maximum of 249 non clustered indexes.

We can create more then one non clustered index in table.

In SQL Server we can create a maximum of 249 non clustered indexes for a table

CREATE NONCLUSTERED INDEX IX_tblOrder_ProductId


ON dbo.tblOrder (ProductId)
INCLUDE ([Id],[CustomerId],[ProductName])
GO

When SQL Server uses Indexes?


1. SQL Server uses indexes of a table provided the select or update or delete statement
contained “WHERE” condition in them and moreover the where condition column must be
an indexed column.
2. If the select statement contains an “ORDER BY” clause also indexes will use.

When should we create indexes on a table?


1. We need to create an index on a table column provided those columns are frequently used
in where condition or order by clause.
2. It is not advised creating an index on each and every column because a number of indexes
can degrade the performance of the database also because every modification we make on
the data should be reflected in all the index tables.
What is the first thing you will check for if the query below is performing very slowly?

SELECT * FROM tblProducts ORDER BY UnitPrice ASC

Check if there is an Index created on the UntiPrice column used in the ORDER BY clause. An
index on the UnitPrice column can help the above query to find data very quickly. When we ask
for sorted data, the database will try to find an index and avoid sorting the results during the
execution of the query. We control sorting of data by specifying a field, or fields, in an ORDER BY
clause, with the sort order as ASC (ascending) or DESC (descending).

5. Triggers in SQL

Triggers are nothing but they are logic’s like stored procedures that can be executed automatically
before the Insert, Update or Delete happens in a table or after the Insert, Update, or Delete happens
in a table. In simple words, we can say that, if you want to execute some pre-processing or post-
processing logic before or after the Insert, Update, or Delete isn a table then you need to use
Triggers.

However, the difference between a trigger and a stored procedure is that the trigger is attached to a
table and is only fired when an INSERT, UPDATE or DELETE operation occurred whereas stored
procedures are not attached to a specific table and can be executed explicitly by making a call to the
stored procedure. In addition to that, triggers can also execute stored procedures.

There are two types of triggers. They are as follows:


1. Instead of Triggers: The Instead Of trigger fires in SQL Server instead of the triggering action.
That is instead of the DML statements such as Insert, Update, and Delete, this trigger is
going to be fired.
2. After Triggers: The After Triggers fires in SQL Server execute after the triggering action. That
is once the DML statement (such as Insert, Update, and Delete) completes its execution, this
trigger is going to be fired.

Types of Triggers in SQL Server:


There are four types of triggers available in SQL Server. They are as follows:
1. DML Triggers – Data Manipulation Language(trigger in insert,update,delete.select).
CREATE TRIGGER trInsertEmployee
ON Employee
FOR INSERT
AS
BEGIN
PRINT 'YOU CANNOT PERFORM INSERT OPERATION'
2. ROLLBACK TRANSACTION
3. END

4. DDL Triggers – Data Definition Language


5. CLR triggers – Common Language Runtime
6. Logon triggers

Where the Triggers are Created in SQL Server?


In SQL Server, the Triggers are created within the Trigger folder

How can we copy the data from one table to another?


This is one of the most frequently asked SQL Server Interview Questions and the interviewer
basically asked to write the query. When we copy the data from one table to another table then the
two tables should contain the same structure.

When we copy the data from one table to another table we use insert and select query. Tables
always independent objects that mean a table does not depend on other tables.

diagram, the injector class creates an object of the service class and injects that object to a client
class. In this way, the Dependency Injection pattern separates the responsibility of creating an object
of the service class out of the client class.

Difference between Stored procedure and Function?

How to create a new table from an existing table or in how many ways we can create a new table
from an existing table?
If required we can create a new table from an existing table as below.
Syntax1: (with all column from an existing table)
SELECT * INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
Example: SELECT * INTO NEWEMPLOYEE FROM EMPLOYEE
When we execute the above query it will create a new table with all records from an existing table.
Syntax2: (with specific columns from an existing table)
SELECT <REQUIREDCOLUMN> INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
Example: SELECT EID, SALARY INTO SPECEMP FROM EMPLOYEE
When we execute the above query it will create a new table with the specific column data from an
existing table.
Syntax3: (creating a new table without data)
SELECT * INTO <NEW TABLE NAME> FROM <OLD TABLE NAME> WHERE 1 = 0
Example: SELECT * INTO DUMMYEMP FROM EMPLOYEE WHERE 1 = 0
OR
SELECT <REQUIRED COLUMNS> INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
SELECT EID, SALARY INTO TAB1 FROM EMPLOYEE WHERE 1 = 0
How to create a new table from an existing table or in how many ways we can create a new table
from an existing table?
If required we can create a new table from an existing table as below.
Syntax1: (with all column from an existing table)
SELECT * INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
Example: SELECT * INTO NEWEMPLOYEE FROM EMPLOYEE
When we execute the above query it will create a new table with all records from an existing table.
Syntax2: (with specific columns from an existing table)
SELECT <REQUIREDCOLUMN> INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
Example: SELECT EID, SALARY INTO SPECEMP FROM EMPLOYEE
When we execute the above query it will create a new table with the specific column data from an
existing table.
Syntax3: (creating a new table without data)
SELECT * INTO <NEW TABLE NAME> FROM <OLD TABLE NAME> WHERE 1 = 0
Example: SELECT * INTO DUMMYEMP FROM EMPLOYEE WHERE 1 = 0
OR
SELECT <REQUIRED COLUMNS> INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
SELECT EID, SALARY INTO TAB1 FROM EMPLOYEE WHERE 1 = 0

What is the Cursor?


A cursor is a database object used by applications to manipulate data in a set on a row-by-row basis,
instead of the typical SQL commands that operate on all the rows in the set at one time.

A cursor in SQL is a temporary work area created in system memory when a SQL statement is
executed. A SQL cursor is a set of rows together with a pointer that identifies a current row. It is a
database object to retrieve data from a result set one row at a time. It is useful when we want to
manipulate the record of a table in a singleton method, in other words, one row at a time. In other
words, a cursor can hold more than one row but can process only one row at a time. The set of rows
the cursor holds is called the active set.
In order to work with a cursor we need to perform some steps in the following order:
1. Declare cursor
2. Open cursor
3. Fetch row from the cursor Process fetched row Close cursor
4. Deallocate cursor

What is a NOLOCK?
This is one of the most frequently asked SQL Interview Questions. Using the NOLOCK query
optimizer hint is generally considered good practice in order to improve concurrency on a busy
system. When the NOLOCK hint is included in a SELECT statement, no locks are taken when data is
read. The result is a Dirty Read, which means that another process could be updating the data at the
exact time you are reading it. There are no guarantees that your query will retrieve the most recent
data.

What is the SQL Profiler?


This is one of the most frequently asked SQL Server Interview Questions. SQL Profiler is a graphical
tool that allows system administrators to monitor events in an instance of Microsoft SQL Server. You
can capture and save data about each event to a file or SQL Server table to analyze later. For
example, you can monitor a production environment to see which stored procedures are hampering
performance by executing too slowly.

Temp table interview questions


What are Temporary tables?
SQL Server provides the concept of the temporary table which helps us in a great way. These tables
can be created at runtime and can do all kinds of operations that one normal table can do. But,
based on the table types, the scope is limited.
Permanent tables get created in the database we specify and remain in the database permanently
until we delete (drop) them. On the other hand, temporary tables get created in the TempDB
database and are automatically deleted, when they are no longer used
What are the 2 types of Temporary Tables in SQL Server?
1. Local Temporary Tables- Local temp table only available to the current connection to the
user and they are automatically delete user disconnect from instance. Table Name start with
#. It is smiler to creating permanent table
For example:
CREATE TABLE #PersonDetails(Id Int, Name Varchar(50))

2. Global Temporary Tables- Global Temporary tables name starts with a double hash (“##”).
Once this table has been created by a connection, like a permanent table it is then available
to any user by any connection. It can only be deleted once all connections have been
closed.The Global Temporary Tables are visible to all the connections of the SQL Server and
are only destroyed when the last connection referencing the table is closed.

Multiple users across multiple connections can have Local temporary tables with the same
name but Global Temporary Table Names should be unique and if we inspect the name of
the Global Temporary Table in the object explorer there will be no random numbers suffixed
at the end of the table name.

Can you please explain when to use a temp table in SQL Server?
When we want to perform many operations on the data in a specific table in the database, we can
load the data into a temporary table and then we can perform operations on the temporary table.
Loading data into a temporary table speeds up the process because all the operations are performed
locally on the client. Use of the Temporary Tables reduces the load on both the network and server
as all the interaction with temporary tables occurs on the Client.
1. When we are doing a large number of row manipulation in stored procedures.
2. This is useful to replace the cursor. We can store the result set data into a temp table, then
we can manipulate the data from there.
3. When we are having a complex join operation.
4. A Temporary Table variable can be very useful when used with stored procedures to pass
input/output parameters or to store the result of a table-valued function.

In which database, the temporary tables get created?


TEMPDB database.

What is SQL Query Optimization?


Ans. Query Optimization is the process of writing the query in a way so that it could execute quickly.
It is a significant step for any standard application.

Q:-2. What are some tips to improve the performance of SQL queries?
Ans. Optimizing SQL queries can bring substantial positive impact on the performance. It also
depends on the level of RDBMS knowledge you have. Let’s now go over some of the tips for tuning
SQL queries.
1. Prefer to use views and stored procedures in spite of writing long queries. It’ll also help in
minimizing network load.

2. It’s better to introduce constraints instead of triggers. They are more efficient than triggers and
can increase performance.

3. Make use of table-level variables instead of temporary tables.

4. The UNION ALL clause responds faster than UNION. It doesn’t look for duplicate rows whereas the
UNION statement does that regardless of whether they exist or not.

5. Prevent the usage of DISTINCT and HAVING clauses.

6. Avoid excessive use of SQL cursors.

7. Make use of SET NOCOUNT ON clause while building stored procedures. It represents the rows
affected by a T-SQL statement. It would lead to reduced network traffic.

8. It’s a good practice to return the required column instead of all the columns of a table.

9. Prefer not to use complex joins and avoid disproportionate use of triggers.

10. Create indexes for tables and adhere to the standards.

@table and temp table

What is the difference between a Temporary Table and a Table variable?


1. A table variable is created in the memory whereas a temporary table is created in the
TempDB. But if there is memory pressure, the pages belonging to a table variable may be
pushed out to tempdb.
2. Table variables cannot be involved in transactions, logging or locking. This makes the table
variable faster than a temporary table.
3. We can pass the table variable as a parameter to functions and stored procedures, whereas
we cannot do the same with a temporary table.
4. The temporary table can have indexes and constraints, whereas a table variable can only
have a primary index. If speed is an issue Table variable can be faster, but if there are a lot of
records, or there is a need to search the temporary table based on a clustered index, then a
Temporary Table would be better. If we have less than 100 rows generally use a table
variable. Otherwise, use a temporary table. This is because SQL Server won’t create statistics
on table variables.

We can apply Culster ,non cluster index Primary key constraint or Unique Keon temp tab

Drop Delete and truncate


TRUNCATE
TRUNCATE SQL query removes all rows from a table, without logging the individual row deletions.
TRUNCATE is faster than the DELETE query.

DELETE
SQL DELETE query deletes all records from a database table. To execute a DELETE query, delete
permissions are required on the target table. If you need to use a WHERE clause in a DELETE, select
permissions are required as well.

DROP
DROP table query removes one or more table definitions and all data, indexes, triggers, constraints,
and permission specifications for those tables. DROP command requires to ALTER permission on the
schema to which the table belongs, CONTROL permission on the table, or membership in the
db_ddladmin fixed database role.

How to handle transaction in SQL ?

We use Begin transaction,rollback transaction, commit transaction.

What is normalization?
Database normalization is a data design and organization process applied to data structures based
on rules that help build relational databases. In relational database design the process of organizing
data to minimize redundancy. Normalization usually involves dividing a database into two or more
tables and defining relationships between the tables. The objective is to isolate data so that
additions, deletions, and modifications of a field can be made in just one table and then propagated
through the rest of the database via the defined relationships.

What are the different normalization forms?


This is one of the frequently asked SQL Server Interview Questions.
1NF: Eliminate Repeating Groups: Make a separate table for each set of related attributes, and give
each table a primary key. Each field contains at most one value from its attribute domain.
2NF: Eliminate Redundant Data: If an attribute depends on only part of a multi-valued key, remove
it to a separate table.
3NF: Eliminate Columns Not Dependent On Key: If attributes do not contribute to a description of
the key, remove them to a separate table. All attributes must be directly dependent on the primary
key
https://dotnettutorials.net/lesson/database-normalization-sql-server/

What is De-normalization in SQL Server?


De-normalization is all about combining the data into one big table rather than going and fetching
data from multiple tables. In de-normalization, we have duplicate data, redundancy data,
aggregated data, etc. i.e. we actually violated the three normal forms.
It does not mean that when you want faster searches you start applying de-normalization i.e. if you
have three tables, let’s combine them and make it one table. That is not the way. For de-
normalization,

What is a View in SQL Server?


A view is nothing more than a saved SQL query. A view can also be considered as a virtual table. So,
we can think of a view either as a compiled SQL query or a virtual table. As a view represents a
virtual table it does not physically store any data by default. When we query a view we actually,
retrieve the data from the underlying database tables.

What is a simple view or Updatable view?


1. The view which is created basing on the columns of a single table is known as the simple
view.
2. We can perform all DML operations on a simple view so that a simple view is also called an
updatable view or dynamic view.
What is a complex View in SQL Server?
1. When we create a view on more than 1 table then it is known as the complex view.
2. On a complex view, we cannot perform DML operations so that a complex view is also called
a non-updatable or static view.

How to create view using 2 different table for different database

create view V_test


as
select table1.*,
table2.*
from [MVC_DB].[dbo].Employee table1 inner join [WebAPI].[dbo].Employees table2 on
table1.EmployeeId=table2.ID

Select 2nd highest salary

select Max(Salary) from Employee //use to retrieve max salary

select Max(Salary) as Salary


from Employee where Salary <(Select Max(Salary) from Employee)

WITH T AS
(
SELECT *,
DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk
FROM Employee
)

SELECT Name
FROM T
WHERE Rnk=2;

3rd Highes salar

SELECT MAX(Salary) AS salary


FROM Employee
WHERE Salary < (SELECT MAX(Salary)
FROM Employee
WHERE Salary < (SELECT MAX(salary)
FROM Employee)
)
https://www.geeksforgeeks.org/sql-query-to-find-second-largest-salary/

What is a synonym in SQL Server


In SQL Server, a synonym is an alias or alternative name for a database object such as a
table, view, stored procedure, user-defined function, and sequence. A synonym provides you with
many benefits if you use it properly.

USE [TDFERU]
GO

/****** Object: Synonym [dbo].[BMWCS_ASSOC_SERVICE] Script Date: 21.04.2021 16:53:13


******/
CREATE SYNONYM [dbo].[BMWCS_ASSOC_SERVICE] FOR [TCSRU].[dbo].
[V_BMWCS_ASSOC_SERVICE]

GO

How to retrieve 2 tables data without using join?


If the column is same then we can use Union and Union all

AND

SELECT * FROM T_INT_BANK_RECEIVED_DATA A,T_INT_CRS_CREDIT_FACILITY B

CTE in SQL

CTE stands for Common Table Expressions. It was introduced with SQL Server 2005. It is a temporary
result set and typically it may be a result of complex sub-query. Unlike the temporary table, its life is
limited to the current query. It is defined by using WITH statement. CTE improves readability and
ease in maintenance of complex queries and sub-queries.

Why to use a CTE


In SQL, we will use sub-queries to join the records or filter the records from a sub-query. Whenever
we refer the same data or join the same set of records using a sub-query, the code maintainability
will be difficult. A CTE makes improved readability and maintenance easier.

The CTE query start with a “With” and is followed by the expression name. e will be using this
expression name in our select query to display the result of our CTE Query and be writing our CTE
query definition.

WITH expression_name [ ( column_name [,...n] ) ]

AS ( CTE_query_definition )

To view the CTE result we use a Select query with the CTE expression name.

Select [Column1,Column2,Column3 …..] from expression_name

Or

Select * from expression_name

CTE and Temp table

1. Temp Tables are physically created in the tempdb database. These tables act as the normal table
and also can have constraints, an index like normal tables.
2. CTE is a named temporary result set which is used to manipulate the complex sub-queries data. This
exists for the scope of a statement. This is created in memory rather than the Tempdb database.
You cannot create an index on CTE.
3. Table Variable acts like a variable and exists for a particular batch of query execution. It gets
dropped once it comes out of a batch. This is also created in the tempdb database but not the
memory.
we can use CTE in CREATE, UPDATE, DELETE and create View but within that scope. If we create the
CTE in a Stored Procedure, I can’t use it in another Stored Procedure. So what we can say is that CTE
is a derived table; it’s a temporary result set.

Difference between JOIN and UNION in SQL Server:


JOINS and UNIONS are two different things. However, this question is being asked very frequently
now. UNION combines the result-set of two or more select queries into a single result-set whereas
JOINS retrieves data from two or more tables based on logical relationships between the tables.

ADO.NET
Ado.Net Classes

1. Data Set class-Represent the subset of database.


2. DataTable class= represent the table in the database.
3. DataRow-Represet the row in the table.
4. DataAdopter object
5. DataReader object
6. DBCommont and DBConnection object.

Connected and Disconnected architecture in Ado.net

In Connected architecture, the connection must be open to access the data retrieve from the
database. It was built on the classes connection,command,Data reader and transaction.

In Disconnect architecture, the data retrieve from database can be accessed even when connection
to be database was closed It was built on classes connection, dataadapter, commandbuilder and
dataset and dataview.

DataSet

It is a type of disconnected architecture. Disconnected architecture means, you don’t need


to connect always when you want to get data from the database. You can get data from
dataset; basically DataSet is a collection of datatables. We can store the database table,
view data in the DataSet and can also store the xml value in dataset and get it if required.

To achieve this you need to use DataAdapter which work as a mediator between Database
and DataSet.

Example

1. public DataSet GetEmployeeData()


2. {
3. SqlConnection conString = new SqlConnection("myconnection"
);
4. conString.Open();
5. SqlCommand cmdQuery = new SqlCommand("Select * from Employ
ee", conString);
6. SqlDataAdapter sda = new SqlDataAdapter(cmdQuery);
7. DataSet dsData = new DataSet();
8. sda.Fill(dsData);
9. return dsData;
10. }

DataReader

It is a connected architecture, which means when you require data from the database you
need to connect with database and fetch the data from there. You can use if you need
updated data from the database in a faster manner. DataReader is Read/Forward only that
means we can only get the data using this but we cannot update or insert the data into the
database. It fetches the record one by one.

Example

1. static void HasRows(SqlConnection connection)


2. {
3. using (connection)
4. {
5. SqlCommand command = new SqlCommand("SELECT CategoryID
, CategoryName FROM Categories;",connection);
6. connection.Open();
7. SqlDataReader reader = command.ExecuteReader();
8. if (reader.HasRows)
9. {
10. while (reader.Read())
11. {
12. Console.WriteLine("{0}\t{1}", reader.GetI
nt32(0),reader.GetString(1));
13. }
14. }
15. else
16. {
17. Console.WriteLine("No rows found.");
18. }
19. reader.Close();
20. }
21. }

Stored procedure Recursive


Recursive stored procedure refers to a stored procedure which calls by itself until it reaches some
boundary condition. This recursive function or procedure helps the programmers to use the same
set of code n number of times.
What TransactionScope is

Yesterday I was stuck with some logic to maintain a single transaction in a multi DML operation in SQL
Server and Oracle Database. I mean to say that I had to set a transaction on a single click where an
insert or update was to be done in a SQL database and an insert or update was to be done in a Oracle
Database. After extensive research I finally got the solution from the MSDN. I want to explain my
experience with a small example.

Namespace Name: System.Transactions.TransactionScope

Definition: TransactionalScope makes your code block Transactional.

You can easily maintain one transaction for multiple databases or a single database with multiple
connectionstrings, using TransactionScope.

When you use TransactionScope there is no need to close any Database connections in the middle.

Just make an object of the TransactionScope class with using. Write all your code in this block and
after completion of all your operations call "objTransactionscope.complete()". Ensure one thing; you
should write a try/catch block in the TransactionScope block.

Syntax to use TransactionScope

using (TransactionScope transactionScope = new TransactionScope())


{
try
{
method1() // Oracle DML operation
method2() // Sql DML operation
method3() // Oracle DML operation
// transactionScope.complete()
// transactionScope.Dispose();
}
catch (TransactionException ex)
{
transactionScope.Dispose();
MessageBox.Show("Transaction Exception Occured");
}
}

Now if an exception occurrs in method1(), method2() or method3() then it will catch the exception in
the catch block and all the operations will be rolled back automatically. There is no option to call a
rollback manually in TransactionScope.

SqlTransaciton class is use to define transction in ado.net

Nested query in SQL


A Subquery or Inner query or a Nested query is a query within another SQL query and embedded
within the WHERE clause.4
Entity Framework
The Entity Framework is an object-relational mapper (O/RM) that enables .NET developers to work
with a database using .NET objects. It eliminates the need for most of the data-access code that
developers usually need to write.”

ADO.NET code to perform CRUD operations with the underlying database. For this, we need to
create a connection with the database, open the connection, create a DataSet to fetch or submit the
data to the database, and convert the data from the DataSet to .NET objects or vice-versa to apply
our business rules. Actually, this was a time-consuming, cumbersome, and error-prone process.
Microsoft has provided a framework called “Entity Framework” to automate all these database
related activities for our application if we provided the necessary details to the Entity Framework.

ORM(Object Relational Mapper)

It is the framework automatically created classes based on database tables and vise versa is also true
that is, it can also generate necessary SQL to create database tables based on classes.

Context Class in Entity framework

This is the primary class that is responsible for interacting with data as object
is System.Data.Entity.DbContext. The context class in Entity Framework is a class that derives
from DBContext in EF 6 and EF Core. It is an important class in Entity Framework, which represents a
session with the underlying database.

The context class is used to query or save data to the database. It is also used to configure domain
classes database-related mappings, change tracking settings, caching, transactions, etc

Entity class in Entity Framework


An entity in Entity Framework is a class that is included as a DbSet<TEntity> type property in the
derived context class. Entity Framework maps each entity to a table and each property of an entity
to a column in the database.

Types of entity classes


1. POCO - Plain OLD CLR object – it used existing domain objects with data model objects. he
POCO data classes which are mapped to entities are defined in a data model. A POCO entity
is a class that doesn’t depend on any framework-specific base class. It is like any other
normal .NET CLR class

These POCO entities support most of the same query, insert, update, and delete behaviors as entity
types that are generated by the Entity Data Model. The following is an example of an Employee
POCO entity.
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Gender { get; set; }
public Nullable <int> Salary { get; set; }
public Nullable <int> DepartmentId { get; set; }
public virtual Department Department { get; set; }
}
2. Dynamic proxy entities
The Dynamic Proxy is a runtime proxy class that wraps the POCO entity.

Development Approach in entity framework

1. Database first
2. Code-First
3. Model – First

Database first approach

We can use the Database First Approach if the database schema already existing. In this approach,
we generate the context and entities for the existing database using the EDM(Entity data model
wizard ) wizard. This approach is best suited for applications that use an already existing database.

we can say that the entity framework will create the model classes based on tables and
columns from the relational database.

Code first approach

Code first approach is used when we do not have existing database for application. In the code-
first approach, you start writing your entities (domain classes) and context class first and then create
the database from these classes using migration commands.

Model-First Approach of Entity Framework:

This approach is very much similar to the Code First approach, but in this case, we use a visual EDMX
designer to design our models. So in this approach, we create the entities, relationships, and
inheritance hierarchies directly on the visual designer and then generate entities, the context class,
and the database script from your visual model.

Choose entity framework approach


Domain object and entity class.

the domain object defines the business object and it's properties and methods. It's used to
manipulate and move the data within the processing system. The Entity object exists to take
those domain properties and map them to a persistent storage object, such as a database table.

How to call Web API.

1. Create object of HttpClient


2. using (var client = new HttpClient())
3. {
4. client.BaseAddress = new
Uri("http://localhost:64189/api/");
5. //HTTP GET
6. var responseTask = client.GetAsync("student");
7. responseTask.Wait();
8.
9. var result = responseTask.Result;
10. if (result.IsSuccessStatusCode)
11. {
12. var readTask =
result.Content.ReadAsAsync<IList<StudentViewModel>>();
13. readTask.Wait();
14.
15. students = readTask.Result;
16. }

And in BMW
using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(handler))
{
Logger.AddToLog("Call WIT Start ResOne
User_Name:Pass :" + strWIT_USER_NAME + " : " + strWIT_USER_PASS, Severity.Information,
LogGroup.LA);
client.BaseAddress = new Uri(WitVehicleBasic);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue(

"Basic",

Convert.ToBase64String(

System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}",
strWIT_USER_NAME, strWIT_USER_PASS))));

var response =
client.GetAsync(WitVehicleBasic).Result;
Logger.AddToLog("Call WIT Hitted",
Severity.Information, LogGroup.LA);
if (response.IsSuccessStatusCode)
{
}

Post

using (var client = new HttpClient(handler))


{

client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/jason"));
var responseUpload =
client.PostAsync(String.Format(CallValidateDealerURL), content).Result;

Logger.AddToLog(
"INT190 Response IsSuccessStatusCode: " +
Convert.ToString(responseUpload.IsSuccessStatusCode),
Severity.Information, LogGroup.LA);
if (responseUpload.IsSuccessStatusCode)
{
returnData =
responseUpload.Content.ReadAsStringAsync().Result;
//MS Logger.AddToLog("INT100 response Return Data: " +
Convert.ToString(returnData), Severity.Information, LogGroup.LA);
objApiResponseModel =
JsonConvert.DeserializeObject<ValidateDealerResponse>(returnData);
}

Synchronous basically means that you can only execute one thing at a
time. Asynchronous means that you can execute multiple things at a time and you don't have to
finish executing the current thing in order to move on to next one.

AJAX communicates with the server using XMLHttpRequest object. ... User sends a request
from the UI and a javascript call goes to XMLHttpRequest object. HTTP Request is sent to
the server by XMLHttpRequest object. Server interacts with the database using JSP, PHP,
Servlet, ASP.net etc.
Call server side method from javascript function via asp button?

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
function funTest() {
alert('in the javascript function...');
document.getElementById('btnTestHidden').click();
}
</script>
</head>
<body>
<form id="form1" runat="server">

<input id="btnTest"
runat="server"
type="submit"
value="Test"
onclick="funTest()" />

<asp:Button ID="btnTestHidden"
runat="server"
Text="this is btnTestHidden - later it will be display:none"
style="display:block"
onclick="btnTestHidden_Click" />

</form>
</body>
</html>

Difference between Patch and put

Patch request says that we would only send the data that we need to modify without modifying or
effecting other parts of the data. Ex: if we need to update only the first name, we pass only the first
name. PUT is for complete entity replacement whereas PATCH is to partially update the entity.

Difference between Post and Get

The tow most common Http methods are Get and Post

Get is used to request data form a specified resource

query string (name/value pairs) is sent in the URL of a GET request:

POST is used to send data to a server to create/update a resource.


The data sent to the server with POST is stored in the request body of the HTTP request:

GET method is used to appends form data to the URL in name or value pair. If you use GET, the
length of URL will remain limited. It helps users to submit the bookmark the result. GET is better for
the data which does not require any security or having images or word documents.

POST is a method that is supported by HTTP and

depicts that a web server accepts the data included in the body of the message. POST is often used
by World Wide Web to send user generated data to the web server or when you upload file.

You might also like