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

OOPs -

1. Object Oriented programming (OOP) is a programming paradigm that work on


the concept of classes and objects.

2. OOP helps to maintain the code with DRY ("Don't Repeat Yourself") principle,
and makes the code easier to maintain, modify and debug.

3. Basically, Don't Repeat Yourself" (DRY) principle is about reducing the repetition
of code. Means common for the application, and place them

at a single place and reuse them instead of repeating it.

Class -

1. Class is a user-defined data type, which holds its own data members and
member functions, which can be accessed and used by creating an instance of that

class. The variables inside class definition are called data members and the
functions are called member functions.

2. In a class we can create many objects as you like.

Object -

1. An object is an instance of a class through which we access the methods of that


class. "New" keyword is used to create an object. A class that creates an

object in memory will contain the information about the methods, variables,
and behaviour of that class.

Encapsulation –

1. Encapsulation simply means binding object state(fields) and


behaviour(methods) together. If you are creating class, you are doing encapsulation.

Abstraction –
1. Abstraction is a process where you show only “relevant” data and “hide”
unnecessary details of an object from the user.

2. It’s a process of hiding the implementation details and displaying the essential
features.

Polymorphism –

1. When a message can be processed in different ways it is called polymorphism.

2. Polymorphism means providing an ability to take more than one form.

3. There are 2 types of polymorphism:

a. Compile time polymorphism also known as Overloading.

b. Run time polymorphism also known as Overriding.

Method overloading / Compile time polymorphism / Static Polymorphism -

1. Creating multiple methods in a class with the same name but with different
parameters and different types is called method overloading.

2. Its gives compile time error.

Method overriding / Runtime polymorphism / Dynamic polymorphism

Runtime polymorphism is achieved by inheritence principle. Means create a


virtual method in base class with same signature and same return type and

override a same method in derived class with same signature and same type.

Access Specifiers –

1. Public can be accessible outside the class through object reference.

2. Private can be accessible inside the class only through member functions.
3. Protected can be just like private but accessible in derived classes also through
member functions.

4. Internal can be visible inside the assembly. Accessible through objects.

5. Protected Internal can be visible inside the assembly through objects and in
derived classes outside the assembly through member functions.

Constructor –

1. Constructor is a special method of the class that will be automatically invoked


when an instance of the class is created.

2. The main use of constructors is to initialize private fields of the class while
creating an instance for the class.

3. When you have not created a constructor in the class, the compiler will
automatically create a default constructor in the class.

4. The default constructor initializes all numeric fields in the class to zero and all
string and object fields to null.

5. A class can have any number of constructors but not of same type.

6. A constructor does not have any return type, not even void.

7. A static constructor can’t be a parameterized constructor.

8. Within a class you can create only one static constructor.

There are 5 types of constructors -

• Default Constructor

• Parameterized Constructor

• Copy Constructor

• Static Constructor

• Private Constructor

Private Constructor –
• Private constructor is a special instance constructor which is used in a class that
contains static member only.

• If a class has one or more private constructor and no public constructor then
other classes is not allowed to create instance of this class this mean

you can neither create the object of the class nor it can be inherit by other class.

• The main purpose of creating private constructor is to restrict the class from
being instantiated when it contains every member as static.

Note - No, object of a class having private constructor can not be instantiated from outside of
the class.

Use of Private Constructor –

• It is used to stop object creation of a class.

• It is used in Singleton class.

• It is used to stop a class to be inherited.

Static constructor –

• Static constructor is a special constructor that gets called before the first object
of the class is created.

• It is used to initialize any static data, or to perform a particular action that needs
to be performed once only.

• The time of execution of static constructor is not known. But, it is definitely


before the first object creation – may be at the time of loading assembly.

• A static constructor can’t be a parameterized constructor.

• Within a class you can create only one static constructor.

Static Class -

It is the type of class that cannot be instantiated, in other words, we cannot create an
object of that class using the new keyword and the

class members can be called directly using their class name.


Static Member -

The static member is callable on a class even when no instance of the class has been
created. The static member is always accessed by the class name,

not the instance name.

Copy Constructor in C#

The constructor which creates an object by copying variables from another object is
called a copy constructor.

The purpose of a copy constructor is to initialize a new instance to the values of an


existing instance.

public employee(employee emp)

name=emp.name;

age=emp.age;

Interface -

1. An interface looks like a class, but it has no implementation.

2. The only thing it contains is declarations of events, indexers, methods and/or


properties.

3. An Interface is an abstract class which has only public abstract methods, and the
methods only have the declaration and not the definition.

These abstract methods must be implemented in the inherited classes.

4. Interfaces have all the methods having only declaration but no definition
5. In an interface class, all the methods are public.

6. The Interface in C# is a fully un-implemented class used for declaring a set of


operations of an object.

7. The abstract method means a method without body or implementation.

Abstract Class -

1. An abstract class is a special kind of class that can’t be instantiated.

2. An abstract class is only inherited from but can’t be instantiated.

4. An abstract class may have private methods.

5. Abstract classes are declared using the abstract keyword. Objects cannot be
created for abstract classes. If you want to use it then it must be

inherited in a subclass. You can easily define abstract or non-abstract methods


within an Abstract class. The methods inside the abstract class can

either have an implementation or no implementation.

6. You can’t create an object of Abstract Class.

8. An abstract class can never be sealed or static or private or virtual.

9. An abstract class can have abstract as well as non abstract methods.

10. The abstract keyword can be used with class, methods, properties, indexers and
events.

11. Abstract members can only be declared inside an abstract class.

12. A concrete class can’t inherit more than one abstract class, in other words
multiple Inheritance is not possible.

Why do we use abstract class?

An abstract class is used if you want to provide a common, implemented functionality


among all the implementations of the component.

Abstract classes will allow you to partially implement your class,

Why can Abstract class not be Instantiated?


• If the compiler allows us to create the object for the abstract class, then you can
invoke the abstract method using that object which cannot be

executed by CLR at runtime.

• Hence, to restrict the calling of abstract methods, the compiler does not allow
you to instantiate an abstract class.

Which type of members can you define in an Abstract class?

You can define all static and non-static members including properties, fields, indexers
and also abstract methods.

Why Does An Abstract Class Needs A Constructor?

1. Constructor Chaining is a concept when a constructor calls another constructor in the


same class or its base class.

2. We can call the Abstract class's constructor through constructor chaining.

Which type of members can you define in an Abstract class?

You can define all static and non-static members including properties, fields, indexers
and also abstract methods.

Difference between Interface and Abstract Class in C#?

• A class can implement any number of interfaces but a subclass can at most use
only one abstract class.

• An abstract class can have non-abstract methods (concrete methods) while in


case of interface, all the methods have to be abstract.

• In an abstract class, all data members or functions are private by default while in
an interface all are public, we can’t change them manually.
• In an abstract class, we need to use abstract keywords to declare abstract
methods, while in an interface we don’t need to use that.

• An abstract class can’t be used for multiple inheritance while the interface can
be used as multiple inheritance.

• An abstract class use constructor while in an interface we don’t have any type of
constructor.

Collection -

ArrayList ArrayList stores objects of any type like an array. However,


there is no need to specify the size of the ArrayList like with an array as

it grows automatically.

SortedList SortedList stores key and value pairs. It automatically arranges


elements in ascending order of key by default. C# includes both, generic

and non-generic SortedList collection.

Stack Stack stores the values in LIFO style (Last In First Out). It
provides a Push() method to add a value and Pop() & Peek() methods to retrieve

values. C# includes both, generic and non-generic Stack.

Queue Queue stores the values in FIFO style (First In First Out). It keeps
the order in which the values were added. It provides an Enqueue() method

to add values and a Dequeue() method to retrieve


values from the collection. C# includes generic and non-generic Queue.

Hashtable Hashtable stores key and value pairs. It retrieves the values by
comparing the hash value of the keys.

BitArray BitArray manages a compact array of bit values, which are


represented as Booleans, where true indicates that the bit is on (1) and false

indicates the bit is off (0).


Type of Collection -
Type of generic -

Array list
List (Generic)

Hash table
Dictionary

Stack

Queue

Generics - 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.

Difference between Dictionary vs HashTable

Dictionary

Dictionary is generic type Dictionary<TKey,TValue>

Dictionary class is a strong type < TKey,TValue > Hence, you must specify the data types
for key and value.

There is no need of boxing/unboxing.

When you try to access non existing key dictionary, it gives runtime error.

Dictionary maintains an order of the stored values.

There is no need of boxing/unboxing, so it is faster than Hashtable.

Hashtable

Hashtable is non-generic type.


Hashtable is a weakly typed data structure, so you can add keys and values of any object
type.

Values need to have boxing/unboxing.

When you try to access non existing key Hashtable, it gives null values.

Hashtable never maintains an order of the stored values.

Hashtable needs boxing/unboxing, so it is slower than Dictionary.

Difference between const vs readonly

1. Constant is a variable where declaration and initialization at the same time. When
value is constant at compile time and can not change a value

throughtout the entire program.

2. Readonly is a keyword where we can change a value during a runtime or we can


assign at a runtime but ony through non-static constructor.

What are events and delegates?

An event is a message sent by a control to notify the occurrence of an action. However it


is not known which object receives the event. For this reason,

.NET provides a special type called Delegate which acts as an intermediary between the
sender object and receiver object

Can multiple catch blocks be executed?

No, Multiple catch blocks can't be executed. Once the proper catch code executed, the
control is transferred to the finally block and then the code that

follows the finally block gets executed.


Difference between public, static and void?

All these are access modifiers in C#.

Public declared variables or methods are accessible anywhere in the application.

Static declared variables or methods are globally accessible without creating an instance
of the class. The compiler stores the address of the method

as the entry point and uses this information to begin execution before any objects are
created.

And Void is a type modifier that states that the method or variable does not return any
value.

Difference between ref & out parameters?

An argument passed as ref must be initialized before passing to the method whereas
out parameter needs not to be initialized before passing to a method

Can “this" be used within a static method?

We can't use ‘This' in a static method because we can only use static variables/methods
in a static method.

What are value types and reference types?

Value types are stored in the Stack whereas reference types stored on heap.
Value types: int, enum , byte, decimal, double, float, long

Reference Types: string , class, interface, object.

What's the difference between the System.Array.CopyTo() and System.Array.Clone()?

The Clone() method returns a new array (a shallow copy) object containing all the
elements in the original array.

The CopyTo() method copies the elements into another existing array.

Both perform a shallow copy.

A shallow copy means the contents (each array element) contains references to the
same object as the elements in the original array.

A deep copy (which neither of these methods performs) would create a new instance of
each element's object, resulting in a different, yet identical object.

Properties in C# -

• Properties are members that provide a flexible mechanism to read, write or


compute the values of private fields.

• In other words by property we can access private fields.

• It uses methods to access and assign values to private fields called accessors.

• The Get and Set portions or blocks of a property are called accessors.

Differences between System.String and System.Text.StringBuilder classes?

String - System.String is immutable. When we modify the value of a string variable, then
a new memory is allocated to the new value and the previous memory

allocation released.
StringBuilder - System.StringBuilder was designed to have a concept of a mutable string
where a variety of operations can be performed without allocation

separate memory location for the modified string.

Difference between "is" and "as" operators in c#?

"is" operator is used to check the compatibility of an object with a given type, and it
returns the result as Boolean.

"as" operator is used for casting of an object to a type or a class.

Singleton design pattern in C#?

In a singleton pattern, a class can only have one instance and provides an access point
to it globally.

Eg:

Public sealed class Singleton

Private static readonly Singleton _instance = new Singleton();

There are various ways to implement a singleton pattern in C#. The following are the
common characteristics of a singleton pattern.

Private and parameterless single constructor

Sealed class.

Static variable to hold a reference to the single created instance

A public and static way of getting the reference to the created instance.
Dependency Injection in c# -

1. .NET supports the dependency injection (DI) software design pattern, which is a
technique for achieving Inversion of Control (IoC) between classes

and their dependencies.

2. A dependency is an object that another object depends on.

3. It allows us to develop loosely-coupled code. The intent of Dependency Injection is to


make code maintainable. Dependency Injection helps to reduce the

tight coupling among software components. Dependency Injection reduces the hard-
coded dependencies among your classes by injecting those dependencies at

run time instead of design time technically.

Type of Injection -

1. Constructor Injection.

2. Property Injection.

3. Method Injection.

Extenision Method -

Extension methods enable you to add methods to existing types without creating a new
derived type, recompiling, or otherwise modifying the original type.

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.


Delegate -

1. Delegates allow to create an object which object have the reference of any
parameter.

2. A Delegate can be defined as a delegate type. Its definition must be similar to


the function signature.

3. A delegate can be defined in a namespace and within a class.

4. They have a signature and a return type. A function that is added to delegates
must be compatible with this signature.

5. Delegates can point to either static or instance methods.

6. Once a delegate object has been created, it may dynamically invoke the
methods it points to at runtime.

Anonymous Type –

Anonymous types allow us to create new types without defining them. This is a way of
defining read-only properties in a single object without having to

define each type explicitly.

We can create anonymous types by using “new” keyword together with the object
initializer.

Example

1. var anonymousData = new

2. {

3. ForeName = "Jignesh",

4. SurName = "Trivedi"

5. };

6. Console.WriteLine("First Name : " + anonymousData.ForeName);

Web API
It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not.
Most HTTP APIs we write are not RESTful. This framework implements

HTTP protocol specification and hence you hear terms like URIs, request/response
headers, caching, versioning, various content types(formats).

Note: I have not used the term Web Services deliberately because it is a confusing term
to use. Some people use this as a generic concept, I preferred to

call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft
like Web API. However it implements another protocol called SOAP.

What is REST and RESTful in C#?

REST -

REST stands for REpresentational State Transfer , It is a style of a software architecture


that basically exploits the existing technology and protocols

of the web.

It is used to develop WEB API which enable interaction between client and server.

Data format of rest is based on HTTP request.

RESTFULL -

RESTful is typically used to refer to web services implementing such an architecture.

It is a web application that follows the Rest infrastruction.

Data format of restful is based on JSON, HTTP and Text.

Difference between convert.tostring() and tostring()?


"Convert" function handles NULLS, while "i.ToString()" does not it will throw a NULL
reference exception error. So as good coding practice using "convert"

is always safe.

Token Based Authentication in Web API?

Token-based authentication is a process where the client application first sends a


request to Authentication server with a valid credentials.

The Authentication server sends an Access token to the client as a response. This token
contains enough data to identify a particular user and it has an

expiry time. The client application then uses the token to access the restricted resources
in the next requests until the token is valid. If the Access

token is expired, then the client application can request for a new access token by using
Refresh token.

For generate token

we have to add the following references :

Microsoft.Owin.Host.SystemWeb

Microsoft.Owin.Security.OAuth

Microsoft.Owin.Cors

Allow Anonymous users - No authetication or token is needed for this.

Var vs Dynamic -

Var -

It is a statically typed.
Ex -

var a = 999;

a = "this is a string." if we assign an integer value to a var then we cannot


assign a string value to it.

Dynamic -

it is a dynamic type.

var a = 999;

a = "this is a string." we use dynamic instead of var, it will not only compile, but
will also work at run-time.

Dispose vs Finalize -

The dispose() method releases the unmanaged resources that are held by an object of the class.
The unmanaged resources are files, data connections, etc.

The method dispose() is declared in the interface IDisposeable and it is implemented by the
class by implementing the interface IDisposable.

The method dispose( ) is invoked by the user.

The method dispose( ) is faster and instantly disposes an object.

The method dispose( ) is defined in the interface IDisposable interface.

The programmer has to implement it manually when you are creating a custom class that will be
used by others.

public void Dispose( ){

// Dispose code here

The method finalize( ) is invoked by the garbage collector.


The method finalize is slower as compared to dispose.

the method finalize() must not be accessible from outside the class, and it must only be
accessible to the garbage collector.

protected void finalize( ){

// finalization code here

?????

IEnumerable vs IQuerable -

IEnumerable

IEnumerable exists in the System.Collections namespace.

IEnumerable is suitable for querying data from in-memory collections like List, Array and
so on.

While querying data from the database, IEnumerable executes "select query" on the
server-side, loads data in-memory on the client-side and then filters the data.

IEnumerable is beneficial for LINQ to Object and LINQ to XML queries.

IQueryable

IQueryable exists in the System.Linq Namespace.

IQueryable is suitable for querying data from out-memory (like remote database,
service) collections.
While querying data from a database, IQueryable executes a "select query" on server-
side with all filters.

IQueryable is beneficial for LINQ to SQL queries.

SOLID Principles -

SOLID principles are the design principles that enable us to manage most of the
software design problems.

S: Single Responsibility Principle (SRP) - SRP says "Every software module should have
only one reason to change".

This means that every class, or similar structure, in your code should have only
one job to do.

Everything in that class should be related to a single purpose. Our class should
not be like a Swiss knife wherein if one of them needs to be changed

then the entire tool needs to be altered.

O: Open closed Principle (OCP) - The Open/closed Principle says "A software
module/class is open for extension and closed for modification".

L: Liskov substitution Principle (LSP) - "you should be able to use any derived class
instead of a parent class and have it behave in the same manner without

modification.

It ensures that a derived class does not affect the behavior of the parent class,
in other words,, that a derived class must be substitutable for its base class.

I: Interface Segregation Principle (ISP) - Its states that clients should not be forced to
implement interfaces they don't use.
D: Dependency Inversion Principle (DIP) - Dependency Inversion Principle (DIP) states
that high-level modules/classes should not depend on low-level

modules/classes. Both should depend upon abstractions. Secondly, abstractions


should not depend upon details. Details should depend upon abstractions.

4. What are the several return types in ASP.Net Web API?

A: The various return types in ASP.Net Web API are:

IHttpActionResult

HttpResponseMessage

Void

Other Type – string, int, or other entity types.

5. What is ASP.Net Web API routing?

A: It is the process that determines the action and controller that should be called.

The ways to incorporate routing in Web API include:

Attribute based routing

Convention based routing

6. What are Media type formatters in Web API?

A: The Media type formatter in Web API include:

MediaTypeFormatter – It is the base class that helps to handle serializing and


deserializing strongly-typed objects.

BefferedMediaTypeFormatter – It signifies a helper class to allow asynchronous


formatter on top of the asynchronous formatter infrastructure.

7. What is the CORS issue in Web API?


A: CORS is the acronym for Cross-Origin Resource Sharing. CORS solves the same-origin
restriction for JavaScript. Same-origin means a JavaScript only makes

AAJAX call for web pages within the same-origin.

You have to install the CORS nuget package by using Package Manager Console to
enable CORS in Web API.

Open WebAPIConfig.cs file

add config.EnableCors();

Add EnableCors attribute to the Controller class and define the origin.

[EnableCors(origins: “”, headers: “*”, methods: “*”)].

How to secure an ASP.Net Web API?

Authentication

Authorization

Maintaining Session

Token Based Authorization

What are the differences between HTTP Get and HTTP Post?

A: GET and POST are two important verbs of HTTP.

Parameters of GET are included in the URL; while parameters of POST are included in
the body

GET requests do not make any changes to the server; while POST does make changes to
the server

How can we handle errors in Web API?


A: Handling errors or exceptions in Web API can be done with the help of the following
classes –

Using HttpResponseException –This exception class helps to return the HTTP status code
specified in the exception Constructor.

Using HttpError – This exception class helps to return meaningful error code to the
client as HttpResponseMessage.

Using Exception filters – Exception filters help in catching unhandled exceptions or


errors generated in Web API and they can be used whenever the controller

action method throws the unhandled error.

How to implement Basic Authentication in ASP.Net Web API?

A: Basic Authentication in ASP.Net Web API can be implemented where the client sends
a request with an Authorization header and word Basic.

In Basic Authentication, the Authorization header contains a word Basic followed by a


base 64 encoded string.

The syntax for Basic Authentication –

Authorization: Basic username: password

What is REST?

A: REST stands for Representational State Transfer. This is an architectural pattern that helps in
exchanging data and treats all the services as resources

and a client can access these resources by using HTTP protocol methods which include PUT, GET,
POST, and DELETE.

What are the differences between ASP.NET MVC and ASP.NET Web API?

A: MVC is used to create web applications that can return views as well as data; while ASP.NET
Web API is used to create restful HTTP services simply, which returns

only data and no view.


In MVC, the request is mapped to the actions name; while the request is mapped to the actions
based on HTTP verbs in Web API.

Explain media Formatters in Web API 2

A: These are classes that are responsible for response data. The Web API understands the
request data format as well as sends data in the format as expected

by the clients

How to enable attribute routing?

A: To enable attribute routing, MapHttpAttributeRoutes(); method can be called in the


WebApi config file.

public static void Register(HttpConfiguration config)

// Web API routes

config.MapHttpAttributeRoutes();

// Other Web API configuration not shown.

What is the namespace for IHttpActionResult return type in Web API?

A: System.Web.Http.Results namespace

How to register an exception filter globally?

You can use the following code to register an exception filter globally –
GlobalConfiguration.Configuration.Filters.Add (new
MyTestCustomerStore.NotImplExceptionFilterAttribute());

What is Program.cs ?

Program.cs is where the application starts. Program.cs class file is entry point of our application
and creates an instance of IWebHost which hosts a web application.

What is Content Negotiation in WEB API?

Content Negotiation is a mechanism that allows a user to decide what kind of response he want
to get from the API.

To get JSON response pass "application/json" in Accept Header.

To get XML response pass "application/xml" in Accept Header.

More Explanation:

Suppose, a developer is friendly with JSON and he wants that all of the API response should be
in JSON format, then he just need to send an "Accept" header with "application/json" value. Web API
will read this header and will provide all the response in JSON format.

The same thing applies for XML as well. To get all response in XML format, developer need to
pass "application/xml" in "Accept" header of API request.

Content Negotiation is a mechanism that allows a user to decide what kind of response he want
to get from the API.
Client should have the ability to decide in which format they want the response – whether they
want the response in XML or JSON etc.

This is called Content Negotiation.

How Content Negotiation Works

There are two main headers which hold the responsibility of content negotiation

1. Content-Type

2. Accept

JSON is the default format of the Web API,

Enable HTTPS in Web API

Create a Custom CustomRequireHttpsAttribute class & inherit with AuthorizationFilterAttribute


override OnAuthorization method

if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)

actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Found);

actionContext.Response.Content = new StringContent

("<p>Use https instead of http</p>", Encoding.UTF8, "text/html");

You need to register the CustomRequireHttpsAttribute in the Register() method of the


WebApiConfig class in WebApiConfig.cs file which is present in the App_Start folder

as shown below.

config.MapHttpAttributeRoutes();
Difference between "throw" and "throw ex" in C#

throw - Its gives original error stack information with empty parameter

throw ex - Its having stack trace method to give

https://stackoverflow.com/questions/31089221/what-is-the-difference-between-put-post-and-
patch

Difference between task and thread ?

Task -

A Task represents some asynchronous operation and is part of the Task Parallel Library,
a set of APIs for running tasks asynchronously and in parallel.

A task can have multiple processes happening at the same time.

We can easily implement Asynchronous using ’async’ and ‘await’ keywords.

A Task is a higher level concept than Thread.

Thread -

Threads can only have one task running at a time.

Difference between size and length?

html 5 tags

You might also like