0% found this document useful (0 votes)
6 views84 pages

Interview QA

The document provides an overview of SQL commands, including DDL, DML, TCL, and DCL, along with their specific functions. It explains the differences between commands like DELETE, TRUNCATE, and DROP, as well as concepts such as primary keys, normalization, joins, and stored procedures. Additionally, it covers various SQL functions, temporary tables, and the distinctions between stored procedures and functions.

Uploaded by

shubhamjkadam190
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views84 pages

Interview QA

The document provides an overview of SQL commands, including DDL, DML, TCL, and DCL, along with their specific functions. It explains the differences between commands like DELETE, TRUNCATE, and DROP, as well as concepts such as primary keys, normalization, joins, and stored procedures. Additionally, it covers various SQL functions, temporary tables, and the distinctions between stored procedures and functions.

Uploaded by

shubhamjkadam190
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

SQL
1. What are Different Types of SQL Commands? Or Explain DDL, DML, TCL Commands.
- There are different commands which we use to communicate with the database to perform specific
tasks.
Data Definition Language (DDL) –
Commands which affects on schema or structure
These SQL commands are used for creating, modifying, and dropping the structure of
database objects. (i.e. affects on schema or structure)
These commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.

Data Manipulation Language (DML) –


Commands which affects on data / row / record
These SQL commands are used for storing, retrieving, modifying and deleting data. (i.e.
affects on data)
These commands are SELECT, INSERT, UPDATE and DELETE.

Transaction Control Language (TCL) –


Commands to control multiple dependent queries
These SQL commands are used for managing changes affecting the data.
These commands are COMMIT, ROLLBACK.

Data Control Language (DCL) –


Commands to control permissions
These SQL commands are used for providing security to database objects.
These commands are GRANT and REVOKE.

2. Difference Between Delete, Truncate and Drop commands?


Delete
- Delete is a DML command.
- The DELETE command is used to remove rows from a table.
- A WHERE clause can be used to only remove some rows if no WHERE condition is specified,
all rows will be removed.
- We can undo the delete operation by using ROLLBACK transaction command.
- This operation causes all DELETE Triggers to fire on a table.

Truncate
- TRUCATE is a DDL command and it is faster.
- TRUNCATE removes all rows from a table.
- The operation cannot be rolled back and no triggers will be fired.
- Truncate command also reset identity.

Drop
- Drop is a DDL command.
- The DROP command Removes a Table from the database.
- All the tables' rows, indexes and privileges will also be removed.
- No DML triggers will be fired.
- The Drop operation cannot be rolled back.

[Reason why Truncate is faster? :- When you type DELETE, all the data get copied into the Rollback
Tablespace first then delete operation get performed. Thats why when you type ROLLBACK after

MODIFIED BY SHUBHAM LAMBAT


2

deleting a data, you can get back the data and this process take time. But when you type TRUNCATE,
it removes data directly without copying it into the Rollback Tablespace. Thats why TRUNCATE is
faster. Once you Truncate you can't get back the data.]

3. What is Difference Between Primary key and Unique key?


- Both unique key and Primary key are used to enforce uniqueness in the column records.
- We can find 2 differences in both the keys :
I. We can have a Single Primary Across the Table whereas we can have Multiple Unique
Key across the Table.
II. Primary Key does not allow NULL value whereas Unique key allows a single NULL value.

4. What is Cascading Referential Integrity?


- If you delete or update records in primary key table and there are dependent records in foreign
key table then cascading referential integrity comes in picture.

- We have the following options when setting up Cascading referential integrity constraint
A. No Action:
This is the default behavior.
It will not allow to delete or update record from primary key table.
B. Cascade:
It will delete or update records from primary key table as well as from foreign key table.
C. Set NULL:
It will delete or update records from primary key table and set null value in foreign key
table.
D. Set Default:
It will delete or update records from primary key table and set default value in foreign key
table.

5. What is Composite key in SQL?


- A primary key that is made by the combination of more than one column is known as a
composite key. / Primary key over more than one or more Columns
- That can be used to uniquely identify each row in the table when the columns are combined
uniqueness is guaranteed, but when it taken individually it does not guarantee uniqueness.
- Sometimes more than one attributes are needed to uniquely identify an entity.

6. Can we Insert Identity Column Value Explicitly? If Yes, then How?


- Yes. We can explicitly insert identity value whenever required.
- We can use Identity_Insert to achieve this.
- SET IDENTITY_INSERT tblName ON
- After Inserting A Value You Have To Off Identity_Insert

7. What is Different Way to Get Last Generated Identity Column Value?


- There are three ways to fetch last generated identity column value.
SCOPE_IDENTITY() – Returns the last identity value that is created in the same session and in
the same scope.

@@IDENTITY –Returns the last identity value that is created in the same session and across any
scope.

IDENT_CURRENT('tblName') – Returns the last identity value that is created for a specific table
across any session and any scope.

MODIFIED BY SHUBHAM LAMBAT


3

8. What Will be the Value of Identity Column Value if All Rows Deleted From the Table? Will
it Reset to Default Values Automatically? If No Then, How to Reset Identity Column Seed
and Increment Value to Default Values?
- If all rows get deleted from table but still we able to see last generated identity value.
- We can reset this identity column value to default value by using DBCC CHECKIDENT command.
DBCC CHECKIDENT(tblName, RESEED, 0)

9. What is Normalization in SQL? Why do we Need of Normalization? What are Different


Forms of Normalization? Explain 1st , 2nd and 3rd Normal Form.
- Database normalization is the step by step process to design a better database.
- Remove duplication (redundancy)
1NF
1. The data in each column should be atomic. (There should not be comma separated values).
2. The table does not contain any column repeating groups.
3. Every record should identify uniquely (i.e. every record should have primary key).

2NF
1. The table satisfy all the conditions of 1NF.
2. Identify groups and split into multiple tables.
3. Create relationship between these tables using foreign keys.

3NF
1. The table satisfy all the conditions of 1NF and 2NF.
2. Remove all columns (attributes) that are not fully dependent upon the primary key.

10. Difference Between Where and Having Clause?


- WHERE clause can be used with – Select and Update statements, Whereas HAVING clause
can only be used with the Select statement.
- WHERE filters rows before aggregation (GROUPING) Whereas HAVING filters groups after
the aggregations are performed.
- Aggregate functions cannot be used in the WHERE clause Whereas aggregate functions can be
used in HAVING clause.

11. What is Join? What are the Different Types of Joins Available in SQL? Explain them.
- JOINS are used to retrieve data from two or more tables based on logical relationships between
these tables.
- Basically, there are 3 types of joins available in SQL.
1. Inner Join
2. Outer Join which again classified to 3 subtypes
A. Left Outer Join
B. Right Outer Join
C. Full Outer Join
3. Cross Join

Inner Join –
Inner joins return only the common records from both the tables.

Left Outer Join –


Left outer join returns common records from both tables as well as uncommon records from left
table.

MODIFIED BY SHUBHAM LAMBAT


4

Right Outer Join –


Right outer join returns common records from both tables as well as uncommon records from
right table.
Full Outer Join –
Full outer join returns common and uncommon records from both tables.
Cross Join –
Cross join returns Cartesian product of the tables involved in the join.

12. What is Self-Join? Can you Write a Query Using Self Join with one Scenario?
- Joining a table with itself is called as SELF JOIN.
- SELF JOIN is not a different type of JOIN.
- It can be classified under any type of JOIN - INNER, OUTER or CROSS Joins.

13. What are Different ways to Replace NULL Values?


- We can replace NULL value using 3 different options:
A. Using ISNULL function
B. Using Case statement
C. Using Coalesce () function - COALESCE () returns the first non-NULL value.
[Please prepare for the syntax also]

14. What is Difference Between Union and Union ALL?


- UNION and UNION ALL are used to combine the result-set of two or more SELECT queries.
- For UNION and UNION ALL to work, the Number, the Data types, and the order of the columns
in the select statements should be same.
- UNION removes duplicate rows and gives distinct sort whereas UNION ALL does not that’s
why UNION ALL is Much Faster Than UNION

15. Difference Between Join and Union?


- JOINS and UNIONS are different things.
- UNION are used to combine the result-set of two or more SELECT queries into a single result-set
whereas JOINS are used to retrieve data from two or more tables based on logical relationships
between the tables.
- In short, UNION Combines Rows from 2 or More Tables whereas JOINS Combine Columns
from 2 or More Table.

16. What is a Sub Query? What are its Various Types? Explain Correlated and Non-
Correlated Sub query?
- A subquery is nothing but the simple select query that returns a single value and can be nested
inside a SELECT, UPDATE, INSERT, or DELETE statement.
- Subqueries are always enclosed in parenthesis called inner queries and the query containing the
subquery called outer query.
- There are two types of subqueries :
Non Correlated Sub Query :
- Outer query depends on inner query.
- Inner query runs first.
- Inner query executes once.

Correlated Sub Query :


- Inner query depends on outer query.
- Outer query runs first.
- Inner query runs multiple times till the records are there in outer query.

MODIFIED BY SHUBHAM LAMBAT


5

17. What are Stored Procedures? Explain its advantages?


- For writing business Logic
- If we have a situation, where we can write the same query again and again then we can save
that specific query as a stored procedure and call it just by its name.
Advantages:
1. Execution Plan Retention and Reusability - Stored Procedures are compiled and their
execution plan is cached and used again, when the same SP is executed again. Although adhoc
queries also create and reuse plan, the plan is reused only when the query is textual match and
the datatypes are matching with the previous call. Any change in the datatype or you have an
extra space in the query then, a new plan is created.
2. Reduces Network Traffic - You only need to send, EXECUTE SP_Name statement, over
the network, instead of the entire batch of adhoc SQL code.
3. Code Reusability and Better Maintainability - A stored procedure can be reused with
multiple applications. If the logic has to change, we only have one place to change, where as
if it is inline SQL, and if you have to use it in multiple applications, we end up with multiple
copies of this inline SQL. If the logic has to change, we have to change at all the places, which
makes it harder maintaining inline SQL.
4. Better Security - A database user can be granted access to an SP and prevent them from
executing direct "select" statements against a table. This is fine grain access control which
will help control what data a user has access to.
5. Avoids SQL Injection attack - SP's prevent SQL injection attack.

18. Write SQL Statement to Call a Stored Procedures with Return


value. - Let s say there is Stored Procedure usp_PersonIdByName .
- We can call this procedure as :
Declare @Id int
Execute @Id = usp_PersonNameById A iket
Print @Id

19. Write SQL statement to call a Stored Procedures with Output Parameter.
- Let s say there is stored procedure usp_PersonNameById with @Name output parameter.
We can call this procedure as :
Declare @Name varchar(50)
Execute usp_PersonNameById 2, @Name Out
Print @Name

20. What is Difference Between Return values and Output Parameter in Stored Procedures?
- Using return values, we can return only one value of type integer whereas output parameters
can return multiple values of any type.
- We always prefer, using output parameters over return values.

21. What is Difference Between Cast and Convert functions?


- To convert one data type to another, CAST and CONVERT functions can be used.
- CONVERT () function has an optional style parameter whereas CAST () function lacks
this capability.
- Convert provides more flexibility than Cast. For example, it's possible to control how you want
DateTime datatypes to be converted using styles with convert function.
- Cast is based on ANSI standard and Convert is specific to SQL Server. So, if portability
is a concern and if you want to use the script with other database applications, use Cast ().

MODIFIED BY SHUBHAM LAMBAT


6

22. What are Deterministic and Non-Deterministic Functions in SQL?


- Deterministic functions always return the same result any time they are called with a specific set
of input values.
Examples: Sum (), AVG (), Square (), Power () and Count ()
- Nondeterministic functions may return different results each time they are called with a specific
set of input values.
Examples: GetDate() and RAND()

23. What is RAND () Function? What if you Pass it a Parameter e.g. RAND (1)?
- Rand () function is a non-deterministic function i.e. every time called gives new value between
0 and 1.
- But if we provide the seed value, the function becomes deterministic, as the same value gets
returned for the same seed value.

24. What are functions in SQL? What are Different Types of Functions? Explain.
- Functions are block of SQL statement which are used to perform some computational logic.
- There are 3 different types of functions are available in SQL :
1. Scalar Function:
- Scalar functions always return a single scalar value.
- The returned value can be of any data type except text, ntext, image, cursor, and
timestamp.
2. Inline Table Valued Function:
- The Inline Table Valued function returns a table but we cannot customize the schema of
returned table.
- Inline table valued function cannot have begin and end body.
- It is faster than multi statement table valued unction
3. Multi Statement Table Valued Function:
- The multi statement table valued function returns a table and we can customize the
schema of returned table.
- The multi statement table valued function can have begin and end body.

25. What are Differences Between Stored Procedures and Functions?


- Store procedures are used for business logic (Insert, Update, Delete on Records) Whereas
Functions are used for computational logic (Calculations).
- Store procedures cannot call in select statement Whereas Functions can call in select statement.
- We can do Error handling in Store procedures Whereas we can’t do error handling in Functions.
- We can Perform Transection in Store procedures Whereas we can’t Perform Transection in
Functions.
- We can create temporary tables inside Store procedure Whereas we can’t create temporary
tables inside Functions.
- We need not to write return statement in Store Procedure Whereas it is compulsory to write
return statement inside Function.
- Store procedure can call Store Procedure & Function Whereas Function can only call Function.

26. What are Temporary Tables? What are Different Types.


- Temporary tables are just like the permanent tables.
- Temporary tables get created in the TempDB and automatically deleted when the session
created temporary table gets closed.
- In SQL Server, there are 2 types of Temporary tables –
1. Local Temporary tables
2. Global Temporary tables.

MODIFIED BY SHUBHAM LAMBAT


7

Difference Between Local and Global Temporary Tables:


1. Local Temp tables are prefixed with single pound (#) symbol Whereas global temp tables are
prefixed with double pound (##) symbols.
2. SQL Server appends some random numbers at the end of the local temp table name Whereas
this is not done for global temp table names.
3. Local temporary tables are only visible to that session of the SQL Server which has created it,
Whereas Global temporary tables are visible to all the SQL server sessions.
4. Local temporary tables are automatically dropped, when the session that created the
temporary tables is closed Whereas Global temporary tables are destroyed when the last
connection that is referencing the global temp table is closed.

[Link] are Table Variables?


- Table variable Dose Not take Participate in transection That’s Why it Is Faster Than Temp Table
- Table Variable Execute in Batch. (Execute All Query at A time.)
- It Is Store in Memory But if There is a Memory Pressure Then It Is store in tempDb.
- Table variable is a special data type that can be used to store a result set for processing at a later
time.
- Table is primarily used for temporary storage of a set of rows returned as the result set of a
table-valued function.
- Functions and variables can be declared to be of type table. table variables can be used in
functions, stored procedures.
- Syntax if interviewer ask to write:
DECLARE @userData
TABLE( name varchar(30)
NOT NULL, City
varchar(30) NOT NULL
);

INSERT INTO @userData


SELECT name, city FROM Employees

28. What is CTE in SQL? Can you write a syntax to create a CTE?
- CTE means common table expression.
- A CTE is a temporary result set, that can be referenced within a SELECT, INSERT, UPDATE,
or DELETE statement that immediately follows the CTE.
- CTE Should Be use With Next Immediate Statement
Syntax :
WITH CTE_name (Column1, Column2, ..)
AS
( CTE_query )

Select * from CTE_Name

29. What are Differences Between Temporary Tables & Table Variables?
- Temporary tables can be stored in TempDB Whereas Table variables can be stored in memory
but if there is a memory pressure table variables can be stored in TempDB.
- Temporary tables participate in transaction Whereas Table variables does not participate in
transaction this makes table variable faster than a temporary table.
- You cannot pass Temporary table as parameter Whereas you can pass Table variable as
parameter to store procedure and function.
- A temporary table can have indexes Whereas a table variable can only have a primary index.

MODIFIED BY SHUBHAM LAMBAT


8

30. What is Difference Between INSERT INTO and SELECT INTO statements?
- Both the statements are used to copy data from one table to another table.
- For INSERT INTO statement it is mandatory to create the table and then fire insert into query
whereas for SELECT INTO statement table creation is not needed this query automatic generates
the table and copy the data.

Syntax for INSERT INTO :


- Insert into tblName values col Value, col Value,…
Or
INSERT INTO @targetTblName

SELECT col1, col2 FROM sourceTblName


[We need to create @targetTblName with required columns before firing this query otherwise it
will going to through error.]

Syntax for SELECT INTO :


SELECT col1, col2 INTO targetTblName FROM sourceTblName
[This query automatically generates targetTblName with copied columns and data.]

31. What are Indexes? Types of Indexes? Advantages and Disadvantages of Indexes?
- Indexes are used by queries to find data from tables quickly.
- Indexes are created on tables and views.
- The existence of the right indexes, can drastically improve the performance of the query.
- If there is no index to help the query then the query engine checks every row in the table from the
beginning to the end this is called as Table Scan and table scan is bad for performance.

There are 2 types Indexes in SQL:

1. Clustered Index:
- A clustered index determines the physical order of data in a table.
- For this reason, a table can have only one clustered index.
- Its Store in Same Memory / Same table
- Create Only On Cluster Index On One Table

2. Non-Clustered Index:
- We can Create Multiple Non-Cluster On Table
- And It Can Not Store in Same table It Take Another Memory Space to store.
- It Is taking Extra Space or Storing Purpose
- The data is stored in one place and the index is stored in another place.
- Since, the non-clustered index is stored separately from the actual data, a table can have more
than one non clustered index.
- The index will have pointers to the storage location of the data.

Difference between Clustered and Non-Clustered Index:


1. Only one clustered index per table, where as you can have more than one non clustered index
2. Clustered index is faster than a non-clustered index, because, the non-clustered index has to
refer back to the table, if the selected column is not present in the index.
3. Clustered index determines the storage order of rows in the table, and hence doesn't require
additional disk space, but whereas a Non-Clustered index is stored separately from the table,
additional storage space is required.

MODIFIED BY SHUBHAM LAMBAT


9

Disadvantages of Indexes:
 Additional Disk Space: Clustered Index does not, require any additional storage. Every Non-
Clustered index requires additional space as it is stored separately from the table. The amount of
space required will depend on the size of the table, and the number and types of columns used in the
index.
 Insert Update and Delete Statements can Become Slow: When DML (Data Manipulation
Language) statements (INSERT, UPDATE, DELETE) modifies data in a table, the data in all the
indexes also needs to be updated. Indexes can help, to search and locate the rows, that we want to
delete, but too many indexes to update can actually hurt the performance of data modifications.

32. What is Covering Index?


- If all the columns that we have requested in the SELECT clause of query, are present in the index,
then there is no need to look up in the table again. The requested columns data can simply be returned
from the index.
- A clustered index, always covers a query, since it contains all of the data in a table. A composite
index is an index on two or more columns. Both clustered and non-clustered indexes can be composite
indexes. To a certain extent, a composite index, can cover a query.
- We can include multiple Colum in Index.

33. Scenario: Interviewer may give you a table and a query and ask you for on which column
should I create a Clustered Index and Why? Let’s say there is a Employee table with Id Column
as a Primary Key :

We have below Query in SP which is Very Slow :


SELECT Id, Name, Salary, Gender from Employee Where Salary BETWEEN 2500 AND 50000
- This query has more focus on Salary column so we should have something over Salary column
which will help this query to execute faster.
- Firstly we can go ahead and create a non clustered index on Salary Column and we will check the
results. If this works then we are good but if this fails then we have to go with creating Clustered
Index on Salary by removing Clustered Index from Primary Key Id Column. Which will definitely
helps this query to run faster.

34. What are Views? Indexed View? Advantages of Views?


- A view is nothing more than a saved SQL query.
- A view can also be considered as a virtual table.
- When we try to retrieve data from the view, the data is actually retrieved from the underlying base
tables. So, a view is just a virtual table it does not store any data, by default.
- However, when we create an index, on a view, the view gets materialized. This means, the view is
now, capable of storing data. In SQL server, we call them Indexed views.

Advantages of using views:


1. Views can be used to reduce the complexity of the database schema, for non-IT users. For
example, the view can hide the complexity of joins. Non-IT users, finds it easy to query the view,
rather than writing complex joins.
2. Views can provide row and column level security.

MODIFIED BY SHUBHAM LAMBAT


10

Row Level Security:


For example, I want an end user, to have access only to IT Department employees. If I grant him
access to the underlying tblEmployees and tblDepartments tables, he will be able to see, every
department employees. To achieve this, I can create a view, which returns only IT Department
employees, and grant the user access to the view and not to the underlying table.

Column Level Security:


Salary is confidential information and I want to prevent access to that column. To achieve this, we
can create a view, which excludes the Salary column, and then grant the end user access to these
views, rather than the base tables.

35. Can we Update Underlying Base Tables through View? [Tricky question] Depending on
your answer he can ask you Single/Multiple base tables?
- Yes. We can update the base tables through a view if there is single underlying base table.
- For a view based on multiple base tables we can use instead of trigger to correctly update the base
table values.

36. What are Triggers? Different types of Triggers?


- A trigger is a special type of stored procedure that automatically fires against some action
occurs in the database server.
- There are different types of triggers:
1. DML Triggers which are again divided into Instead of Triggers and After Triggers
2. DDL Triggers
3. Logon Triggers.

DML Triggers :
- DML triggers are fired whenever data is modified using INSERT, UPDATE and DELETE events.
- DML triggers can be again classified into 2 types.
1. After or For triggers
- After trigger will be fired and executed after performing the Insert, Update and Delete
actions successfully.

2. Instead of triggers
- Instead Of trigger allow you to skip an Insert, Update and Delete actions on table and
execute other statements defined in the trigger instead.

DDL Triggers :
- DDL triggers fire in response to DDL events i.e. for CREATE, ALTER and DROP (Table,
Function, Index, Stored Procedure etc...).

Logon Triggers :
- As the name implies Logon triggers fire in response to a LOGON event.
- Logon triggers fire after the authentication phase of logging in finishes, but before the user session is
actually established.

Logon triggers can be used for


1. Tracking login activity
2. Restricting logins to SQL Server
3. Limiting the number of sessions for a specific user

MODIFIED BY SHUBHAM LAMBAT


11

37. What are Different Magical/Special Tables Available in Triggers?


- There are 2 magical tables available while working with triggers:
1. INSERTED Table
- When you add a new row in a table then a copy of the row will be made into inserted
table which only a trigger can access.

2. DELETED Table
- When you delete a row from a table then a copy of the row will be made into deleted
table which only a trigger can access.

38. Can I save Activities of User on my Database? If Yes then How?


- Yes. We can save all activities of a user on a specific database or on all databases from a server.
- We can use DDL Trigger on a database or on a server to log the activities of user in a particular
table
[Note : Interviewer may ask you to write a syntax for creating database or server scoped DDL
Trigger.]

39. Can we Limit Connections for a Particular user? If Yes then How?
- Yes. We can limit the connections for a particular user.
- We can use Logon Triggers to achieve this.
[Note : Interviewer may extend his question by asking how to create that trigger. Remember the
syntax of creating LOGON Trigger.]

40. How Error Handling done in SQL? Have you done Error Handling in your Project?
- We use Try Catch block just like C# language to catch and handle the exceptions in SQL.
- We cannot use try catch blocks in functions.
- If we have to through error to calling application then we use RAISERROR function in catch
block.
- Also we specify ROLLBACK command in catch block when we are dealing with transactions.
- RAISEERROR Function is use to throw exception directly to the calling application.
Syntax of RAISEERROR Function is
RAISERROR('Error Message', ErrorSeverity, ErrorState)
- Severity and State are integers. In most cases, when you are returning custom errors, the
severity level is 16, which indicates general errors that can be corrected by the user.
- ErrorState is also an integer between 1 and 255. RAISERROR only generates errors with state
from 1 through 127.

41. What are Transactions in SQL? What all Commands used in Transaction?
- A transaction is a group of commands that change the data stored in a database.
- A transaction is treated as a single unit.
- A transaction ensures that, either all of the commands succeed, or none of them. If one of the
commands in the transaction fails, all of the commands fail, and any data that was modified in the
database is rolled back. In this way, transactions maintain the integrity of data in a database.
Transaction processing follows these steps:
1. Begin a transaction.
2. Process database commands.
3. Check for errors.
If errors occurred,
rollback the transaction,
else,
commit the transaction
- We use Commit command to commit the changes permanently to database and Rollback
command to Rollback the changes on any error while working with transactions.
MODIFIED BY SHUBHAM LAMBAT
12

42. What are Row_Number(), Rank(), Dense_Rank() functions?


Row_Number function
- Returns the sequential number of a row starting at 1
- In Row_Number function ORDER BY clause is required.
- In Row_Number function PARTITION BY clause is optional.
- Syntax : ROW_NUMBER() OVER (ORDER BY Col1, Col2)

Rank function
- Rank function skips rankings if there is a tie.
- In Rank function ORDER BY clause is required.
- In Rank function PARTITION BY clause is optional.
- Syntax : Rank() OVER (ORDER BY Col1, Col2)

Dense_Rank function
- Dense_Rank function does not skips rankings if there is a tie.
- In Dense_Rank function ORDER BY clause is required.
- In Dense_Rank function PARTITION BY clause is optional.
- Syntax : Dense_Rank() OVER (ORDER BY Col1, Col2)

43. What is Pivot and UnPivot in SQL?


- In short, PIVOT operator turns ROWS into COLUMNS whereas UNPIVOT turns COLUMNS into
ROWS.

44. How to Delete Duplicates Rows from Table.


with cte1
as
(
select Name,
ROW_NUMBER() over (partition by Name order by Name) As
RowNumber from sample1
)

delete from cte1


where RowNumber >1

45. How to Find nth Highest Salary from Employees Table (Explain Different Ways).

1st way using SubQuery :


SELECT TOP 1 SALARY
FROM (
SELECT DISTINCT TOP N SALARY
FROM EMPLOYEES
ORDER BY SALARY DESC ) RESULT ORDER BY SALARY

MODIFIED BY SHUBHAM LAMBAT


13

2nd way using CTE :


WITH CTE AS
(
SELECT SALARY,
DENSE_RANK() OVER (ORDER BY SALARY DESC) AS DENSERANK
FROM EMPLOYEES
)
SELECT DISTINCT SALARY
FROM CTE
WHERE DENSERANK = N

[Please note we can use Row_Number() function over Dense_Rank() but if there are duplicates
then Dense_Rank() function gives correct output.]

46. What are ACID Properties in SQL?


- All transaction must obey ACID properties.
- Atomicity : All statements in the transaction either completed successfully or none of them will
execute. But in any case not left half done.
- Consistency : A database is initially in a consistent state and it should remain consistent after
every transaction.
- Isolation : If the multiple transaction are running concurrently they should not be affected by
each other. Most database uses locking to maintain transaction isolation.
- Durability : Once a change in database is made it remain permanent in the case of any software
or hardware failure.

47. What is LOCK in SQL?


- To avoid concurrency problem lock is used.
- Concurrency problem means multiple transactions can access table at same time.
- Lock can be applied on database, table, row.

48. What is SQL Profiler?


- SQL server profiler is a tracing tool provided by Microsoft.
- It is used to trace activities and operations executed on a specific database or table or query.

49. How to Optimize SQL Query?


- Select fields instead of using Select *
- Avoid Select Distinct Use Group by to all fields in the query to create distinct results.
- Use Where instead of Having to define filters.
- Proper Indexes runs query faster for this create index on those columns which can be used in
where or group by clause.
- Avoid corelated sub queries as it search row by row.
- Use temporary table to handle bulk data.

50. What is Deadlock?


- Deadlock is special concurrency problem in which two transaction block the progress of each
other.

51. How to Avoid Deadlock?


- Ensure the database design is properly normalized.
- Keep transaction as short as possible.
- Reduce the number of round trips between your application and sql server by using store
procedure.

MODIFIED BY SHUBHAM LAMBAT


14

52. Table Hints in SQL?


- Hint instructs the database engine on how to execute the query.
- Ex. a hint may tell the engine to use or not to use an Index.
- NoLock Hint : Allows SQL to read data by ignoring any locks this improves query performance.
- Rowlock Hint : That instructs database that it should keep locks on a row scope.

53. What are Cursors in SQL? Can you tell me What all Steps are Followed while using Cursors?
- If there is ever a need to process the rows, on a row-by-row basis, then cursors are your choice.
- Cursors are very bad for performance, and should be avoided always.
- Most of the time, cursors can be very easily replaced using joins.

- There are different types of cursors in SQL server as listed below.


1. Forward-Only
2. Static
3. Keyset
4. Dynamic

We use below steps while using the cursors :


- Declare the cursor
- Open statement
- Fetch the row from the result set into the variable
- @@Fetch_Status to check if result set still has rows
- Release the row set Deallocate the resources associated with the cursors.

[Note : If interviewer ask where did u use cursors in your project? Ans : I have never came across
situation where I can implement cursors in my project. Again they are bad over performance.

MODIFIED BY SHUBHAM LAMBAT


15

C#
1. Purpose of Main () Method? Scenario with Writing one more Main () Method?
• Every program needs an entry point to execute.
• This Main() method is an entry point where program starts its execution.
• Main() method is by default private and static.
• As C# is a case sensitive language it means Main(), main(), MAIN() these method names are
treated as different.

2. What is Datatype Conversion? What is Different way of Type Conversion?


• Datatype conversion is nothing but converting one data type to another data type Example.
Converting an int value to a float value or vice versa.
• There are 2 different types of Datatype conversion

1) Implicit Conversion – Compiler automatically does a conversion.


 When there is no loss of data.
 When there is no chance of exception/error
2) Explicit Conversion – When compiler fails for automatic conversion, we have to do
conversion explicitly.
 Type cast operator
 Convert class operator
 Parse/TryParse operator
 Is/as keyword

If interviewer asks to explain with example, then give below example


Converting from a smaller datatype to bigger datatype for example int to float in this case
there is no loss of information or there is no chance of any exception so compiler will
automatically do a conversion which is implicit type conversion.
But if we reverse this case let’s say converting a float value to int then there is definitely a
loss of information means int variable will not be able to hold fractional part and also there is a
chance of Overflow Exception. So compiler will not perform implicit conversion and we have to
use explicit cast here.

3. What are Different Ways of Explicit Type Conversions?


• There are different ways to achieve explicit type conversion –
• Type casting.
float a = 10;
int b = (int) a;

• Using of Convert class.


float a = 10;
int b = Convert.ToInt32(a);

• Using as Keyword.
object a = "some string";
string b = a asstring;

We can use Parse and TryParse methods when we need to convert a string to other types like
int, bool, float etc.

4. What is Difference Between Cast Operator and Convert Class?


• Cast operator handles the exceptions whereas Convert class does not handle and throws the
exceptions like Overflow Exception, Format Exception etc.
MODIFIED BY SHUBHAM LAMBAT
16

5. What is Difference Between Parse and TryParse Methods?


If the number is in a string format you have 2 options - Parse() and TryParse()
• Parse() method throws an exception if it cannot parse the value whereas TryParse() method
returns a bool indicating whether it succeeded or failed.
• We can use Parse() if we are sure the value will be valid, otherwise use TryParse()

6. What are Value Types and Reference Types in C#? Give Some Examples?
Value Type
 In value type actual value get stored on stack.
 When value type goes out of scope it will remove actual value from stack.
 Value type does not hold null values but it can achieve using nullable type.
 Ex. Integer, Boolean, Struct, etc..

Reference Type
 In reference type references get stored on stack and actual value(object) get stored on heap.
 When references goes out of scope it will just removes references from stack and actual value
(object) is there in heap.
 Ex. String, Object, Class, etc..

7. What is Boxing and Unboxing Operation?


Boxing
• Converting value type to reference type called boxing. This is an implicit conversion.
int i = 10;
object o = i;
Unboxing
• Converting reference type to a value type called unboxing. This needs an explicit cast.
object o = 100;
int j = (int) o;
Boxing and unboxing are performance wise expensive processes. So it is good to avoid boxing
and unboxing if not really needed.

8. What is Object Type?


• The Object Type is the ultimate base class for all data types in C#.
• When a value type is converted into object type called boxing whereas when an object type is
converted into a value type called unboxing.
• The object type values can be assigned to any other types. However, before assigning values
it needs type conversion.

9. What is Var Type?


• There is no need to mention the data type when declaring a variable with var.
• We have to compulsorily initialize the value when we are declaring a variable with var.
• Also, its value cannot be null at the time of initialization. var a=10;
var z = "CSharp";
• Var type only used as local variable we cannot use it as class level fields or as method
parameters.
• The main reason behind introducing var type is the introduction of anonymous types in C#

Interviewer might extend his question further asking What are Anonymous Types?
• Anonymous types allow to create a new type without defining them.
• Type Without Name. Ex :-new{};
• They are extensively used in LINQ expressions whenever you want to return only a few
properties from its properties.
Ex. var person = new {Id = 101, Name = "ABC"};
MODIFIED BY SHUBHAM LAMBAT
17

10. What is Difference Between Var and Object Type and Dynamic Keyword?
Var
• It is compile time variable and does not require boxing and unboxing.
• Since Var is a compile time feature, all type checking is done at compile time only.
• Once var has been initialized we can’t change type stored in it.
• It is implicit Type Local variable
• We can use when we don’t know the type of value.
• Using var keyword less readability.
var test = 10; // after this line test has become of integer type
test == test + 10; // No error
test == "hello"; // Compile time error as test is an integer type

Object
• Each object in C# is derived from object type, either directly or indirectly.
• It is compile time variable and require boxing and unboxing for conversion and it makes it slow.
• You can change value type to reference type and vice versa.
object test = 10;
test = test + 10; // Compile time error
test = "hello"; // No error, Boxing happens here

Dynamic
• It is run time variable and not require boxing and unboxing.
• You can assign value to dynamic and also can change value type stored in same.
• All errors on dynamic can be discovered at run time only.
• We can also say that dynamic is a run time object which can hold any type of data.

dynamic test = 10;


test = test + 10; // No error
test = "hello"; // No error, neither compile time nor run time

11. What is Array?


 Array is a collection of similar datatypes.
 Array elements are accessed by Index.
 Index starts from 0.
 Array size is fixed and its size cannot grow automatically.
 If you try to access index which is not there it throws exception like “Index Out of Range
Exception”.

12. Ternary operator in C#?


• Ternary operator is replacement of if else statement.
• Syntax :- condition ? first expression : second expression;

13. What is looping in C#?


• Looping is a way to execute block of code multiple times depending upon condition.
• In looping Initialization, Condition and Updating are important things.
• There are four different loops in C#
a) while
b) do while: Gives guarantee that it will be executed once
c) for: for loop is forward as well as backward also
d) foreach: foreach loop is only forward

MODIFIED BY SHUBHAM LAMBAT


18

14. What is Nullable types? And Null Coalescing operator?


• In C#, types are divided into 2 broad categories.
• Value Types - int, float, double, structs, Enum etc.
• Reference Types – Interface, Class, delegates, arrays etc.
• Value type does not hold null values but it can achieve using nullable type.
• Example: - int? i = null;
• Nullable types is the bridge between C# types and Database types.
(for example, in SQL int type can hold null values and in C# by default int is non nullable.)

Interviewer might ask you what is NULL coalescing operator –


If we want to convert from a nullable type to non-nullable type then we can Null coalescing
operator.
int? i = null; // here i is nullable type
int j = i ?? 0; // as j is non nullable type it cannot hold null value.
So, here if i value is null then 0 will be assign to j or else i value.

15. Purpose of Break, Continue, Return Keywords?


• The Break statement terminates the closest enclosing loop. (i.e. take cursor out of Loop).
• The Continue statement skips further statement and passes control to the next iteration.
• The Return statement gives cursor back to the calling method.
• If the return statement is inside a try catch block and there is finally block exists, then finally
block will be executed before control returns to the calling method.

16. What is Static and Instance Members of Class?


Static
• We use static keyword with Class and Class members.
• Static members are accessed with class name.
• There will be only a single copy of static members regardless of how many instances of the class
are created.
• When we write static keyword with class then it will restrict to create object of that class.

Non Static Members or Instance Members


• We can access non-static members by creating the object of the class.
• There will be different copies of these members with every objects.

17. What are different Method Parameters in C#?


There are 4 different types of method parameters:
Pass by Value
• Any parameter value changes in called method does not reflect in calling method.

Reference Parameters
• Any parameter value changes in called method will reflect in calling method.
• It is mandatory to initialize value in calling method before passing to method.
• It is not mandatory to assign value in called method before leaving a method.

Output Parameters
• Any parameter value changes in called method will reflect in calling method.
• Internally ref and out keyword works same.
• It is mandatory to assign value in called method before leaving a method.
• It is not mandatory to initialize value in calling method before passing to method.
• By default, method can return only a single value. If we want to return more than one value
from a method then we can use output parameters.

MODIFIED BY SHUBHAM LAMBAT


19

Parameter Arrays
• If a method has array as input parameter, then we can use params keyword with that parameter.
• Advantages of using parameter arrays are we can pass comma separated values instead of creating
and passing array as argument.
• Also, we can call that method without passing any parameter i.e. We can achieve optional
method parameter using parameter arrays.

18. What are all Ways Available in C# to Make Method Parameters as Optional?
There are different ways we can make a parameter as optional parameter:
Parameter Arrays
• We can use parameter arrays to make optional parameter as it allows us to call method without
passing value for params parameter.

Default Value
• We can specify default values to parameters to make them optional.
• If we are specifying default values then it should be from right to left.

Optional Attribute
• We can use [OptionalAttribute] with parameter to make it optional.

19. What is a Class?


• A class is complex custom type.
• Class contains data members and members functions.
• Class is By Default Internal
• Class Contain Constructor, Method, Function Destructor Etc.

Data Members
 Any field writing inside a class can referred as a data member.
 We can write n number of class field in class.

Member Function
 Any method or function inside a class is nothing but the member function.

20. What is Object?


 Object is a runtime entity of class.
 We can create n number of objects of a class.
Student s = new Student ();
s is a reference variable of type Student who is pointing to the object type Student.

21. What is Purpose of Constructor? How it Differs from Normal Member Function?
• The purpose of constructor is to initialize class fields.
• Constructors are automatically called when we create object of a class.

• There are Different Types of constructors we can write inside a class like
1) Parameter less Constructor (Default)
2) Parameterized Constructor
3) Copy Constructor
4) Static Constructor

• Compiler automatically provides a default parameter less constructor but if there is


parameterized constructor then we have to explicitly write default parameter less constructor.

MODIFIED BY SHUBHAM LAMBAT


20

22. What is Purpose of Static Constructor? When it will get Called?


• Static constructors are used to initialize static fields of a class.
• Static constructors are called only once regardless of how many instances of the class are
created.
• Static constructors are automatically called when
I. We access static member.
II. We create object of derived class.

23. What is use of “this” and “base” keywords?


• this keyword refers to current instance of a class. If we want to access any instance member
of class, we can access them by using this keyword.
• base keyword is used to refer the instance of base class. If we want to access or call constructor
or any other instance member from base class, we can use base keyword.

24. What is OOPS? What are the Main Pillars of OOPS?


 OOPS stands for Object Oriented Programming System.
 The main pillars of OOPS are
1) Inheritance
2) Polymorphism
3) Abstraction
4) Encapsulation

25. What is Inheritance what are uses of Inheritance?


• Inheritance is the ability to create a class from another class when there is a is a
relationship.
• Inheritance provides us code reusability means we can use the existing properties and
functionalities of the base class into derived classes.
• Inheritance provides a specialization it means a derived class is a specialized class which has all
properties of base class as well as its own properties.
• Inheritance provides extensibility it means we can easily plug a new type without affecting
the existing functionalities.

26. What is Polymorphism? What are types of Polymorphism?


• Polymorphism is nothing but a single thing having multiple forms.
• There are two types of polymorphism
1) Compile time Polymorphism
– Method Overloading
– Operator Overloading
2) Runtime Polymorphism
– Method Overriding

27.
What is Method Overloading? On what basis a Method can be Overloaded?
• Method overloading is a compile time polymorphism means it checks at compile time.
• Same method name having different forms called method overloading.
• Method can be overloaded on the basis of
1) Number of Parameter
2) Types of Parameters
3) Order of Parameter
4) Kinds of Parameter
 Method cannot be overloaded on the basis of
1) Return Type
2) Ref and Out Keyword
3) Using Params
MODIFIED BY SHUBHAM LAMBAT
21

28. Can Method Overloaded on Basis of Just Return Type? if no, then why?
• No. Method cannot be overloaded just on basis of return type.
• Return type is not considered in method signature while method overloading.
• This behavior is by design and it is because to avoid confusion of a developer that what will be
the output of the method if the method is same and just changed with the return type.

29. Can Method Overloaded with Out and Ref?


• Method cannot be overloaded just on basis of ref and out keyword.
• At compile time both ref and out refers as same and internally both works same.
• so, compiler does not allow us to overload a method just on basis of ref and out parameter.

30. Can Method Overloaded with Params (Parameter Arrays), why?


• We cannot overload a method just on basis of params keyword.
• Compiler does not find any difference in normal array parameter and a parameter array at compile
time.

31. What is Method Overriding? Why it is called Runtime Polymorphism?


• If base class and derived class contain same method then base class reference variable pointing
to a derived class object will call derived class override method.
• In order to override a method in derived class that method should be virtual or abstract or override
in base class.
• Method overriding is called as runtime polymorphism because which method will get called is
decided at runtime based on the type of object.

32. What is difference Between Method Overloading and Method Overriding?


• Method overloading and method overriding both are the types of polymorphism.
• Method overloading is a compile time polymorphism because at compile time only it is known
that which overloaded method will get invoke on execution.
• Method overriding is a runtime polymorphism because which method will get called is decided
at runtime based on the type of object.

33. What is Method Hiding? Scenario of object Creation and Calling Methods.
• If base and derived class contain same method then a base class reference variable pointing to
a derived class object will call base class method is called method hiding.
• If we don’t provide new keyword in derived class method then compiler will give us a warning
that if hiding is intentional then use new keyword.
• We use new keyword in derived class method because method hiding is intentionally.

34 What are Properties? Why should we use Properties? What is Auto-Implemented


Properties?
• Properties are used to encapsulate and protect the private fields.
• We can write custom logic to validate the user data before it is actually assigned to or retrieved
from private fields.
• Using get and set access modifiers we can create Read Only, Write Only and Read Write
Properties depending on our requirement.

• Auto implemented properties, with this feature we do not need to declare a separate private
field for a property.
• Framework automatically creates a private field for the declared property.
Ex. Public string Name { get; set; }

MODIFIED BY SHUBHAM LAMBAT


22

35. What are Indexers?


• Indexers are used to design our indexed based class objects just like an array.
• Indexer we write like Property.
• We create Indexers by using “this” keyword.
• Indexer is pointing / targeting the object of that class.
• We can overload the indexers just like we overload a method.
• In real time, Session object, Data Table object, Rows Object uses indexers to access the values.

• Ex :
string Name = i1[101];
[Link] (Name); o/p :- Shubham Lambat

36. What is Difference Between Class and Struct?


• A struct is a value type and they get stored on the stack whereas class is reference type and they
get stored on the heap.
• Struct gets immediately destroyed from the memory once they go out of scope whereas for class
only reference variable gets destroyed after it goes out of scope and the actual object get released
by garbage collector.
• Struct cannot have destructors whereas a class can have destructors

37. What is Encapsulation and Abstraction? When Abstraction and Encapsulation comes
in Project Development?
• Abstraction is a concept of showing necessary information to outside world.
• Encapsulation is a concept of hiding unnecessary information from outside world.
• Abstraction comes at design level Whereas Encapsulation comes at implementation
level.
• If we talk in terms of coding perspective, Public fields show Abstraction and Private
fields shows Encapsulation.

38. What are Interfaces? What are Advantages using Interfaces?


• Interfaces are just like classes but they just have declarations and not implementations.
• Object of interface is not possible but an interface reference variable can point to a class object
which implements that interface.
• Interface we can use as a base class.
• Interface contain incomplete member like abstract class.
• If a class implementing an interface, it is mandatory for that class to provide
implementation to all the interface members.
• We cannot write fields, constructor Property inside Interface.
• Interface member are by default public.
• Class inherits the Interface but Interface cannot inherit the class.
• By default, we can’t use any access specifier for interface members and we cannot specify
even a public
• Multiple class inheritance is not possible in C# but we can achieve it with interfaces.
• Interfaces are used to implement SOLID principles and Design patterns.

• Syntx :-
interface Print
{
void printA();
void printB();
}

MODIFIED BY SHUBHAM LAMBAT


23

39. What is Explicit Interface Implementation? When there will be need of Implementing
Interface Explicitly.
• When we are implementing 2 or more interfaces in a class and those interfaces are having
same method signature.
• Then we have to implement those interfaces explicitly in order to give implementation to all of
the interfaces.
• We have to prefix interface name with method name while implementing interface
explicitly.
• This implemented methods by default public. We cannot specify any other access modifier
even a public.
• To call particular method we have 2 approaches –

• Creating interface reference variable pointing to class object


• Creating a class object and then type casting as interface and invoking a method.

40. What are Abstract Classes? Can it be Instantiated?


• Abstract Means Incomplete.
• Abstract classes are created with abstract keyword.
• Abstract classes are used as base types.
• They are just like concrete classes but they contain both abstract and non-abstract members.
• Abstract members mean members with just declarations.
• Object of abstract class is not possible but an abstract class reference variable can point to a
derived class object.
• When we inherit abstract class then it is mandatory to implement abstract members in derived
class.

41. Can Abstract class have a Constructor? When it will get called?
• Yes. Abstract class can contain constructors.
• Abstract class constructors get called before derived class constructor call.

42. What is Sealed Class?


• Sealed class are prevented from inheritance it means Sealed classes cannot be used as base class.
• It Prevent to accessing in a child class.
• Rest of things are same as normal class.
• Sealed keyword is use for stop Inheriting.
• We can apply Sealed Keyword to ‘overridden’ method only.
• Sealed Method not apply on normal method and virtual method.
• Syntax :-
public sealed override void print (){ }

43. What is Difference between Interface and Abstract class? When to use Interface over
Abstract Class or Vice Versa.
• Interface cannot have definition for any of its member whereas abstract class can have definition
for its members (non-abstract member).
• Interfaces cannot have fields whereas abstract class can contain field.
• By default, access specifier for interface members is public and we cannot specify any other
even a public whereas abstract class members access specifiers can be changed.
• If there is situation that all the derived classes have different implementation but we have to
provide same method signature then we can go with interfaces whereas if there is a situation that
few of the derived classes sharing same implementation then we can think of using abstract class
instead of interface.
• In interface multiple inheritance is possible whereas in abstract class multiple
inheritance not possible.
MODIFIED BY SHUBHAM LAMBAT
24

44. Why Multiple Class Inheritance is Not Possible in C#? How to Overcome it.
• Multiple class inheritance is not possible in C# it is also called as Diamond Problem.
• Let’s say we have one class A which is derived by two classes B and C. Class B and C has
overridden method which was marked virtual in class A.
• Now if we derive class B and C in a new class D and we are not providing any
implementation in class D.
• So, if we create an object of class D then which method implementation should get call here
from class B or class C. There will be an ambiguity in calling 2 different copies of overridden
method. This problem is called as Diamond Problem.
• We can achieve multiple class inheritance using interfaces.

45. What are all Access Specifiers in C#?


There are 5 different access modifiers available in C#.
• Private – Its accessibility is only within a same type.
• Protected – It is accessible within containing type as well as in derived type in same assembly
or from different assembly.
• Public – It is accessible anywhere in the application.
• Internal – It is accessible anywhere in the same assembly.
• Protected Internal – It is accessible anywhere within same assembly as well as in derived type
in same assembly or from different assembly.

46. What is Default Access Specifier for Type and Type Members?
• Default access modifier for a type is internal.
• Default access modifier for types member is private.

47. What is Internal and Protected Internal Access Specifiers?


• Internal access modifiers are accessible from anywhere within the same assembly. We cannot
access them outside assembly.
• Protected internal is can be considered as combination of protected and internal access specifiers
means it is accessible anywhere from the containing assembly as well as in derived type in same
assembly or from different assembly.

48. What are Partial Classes and Rules to Create Partial Classes?
• Partial classes allow us to split a class into 2 or more files.
• When the application is compiled, all these parts then combined into a single class.
Rules :
• All parts should have partial keyword.
• All parts should have same access modifiers.
• If one part is marked abstract then entire type is considered abstract.
• If one part is marked sealed then entire type is considered sealed.
• Multiple class inheritance is not possible in C# so different parts should not inherit different
base classes.

49. What are Partial Methods? Anything can be asked related to Rules followed during
creating Partial Methods?
• Partial class can contain partial methods.
• Partial method created using partial keyword and it has two parts – the declaration and the
implementation.
• Partial methods are by default private. We cannot specify any other modifier even private.
• Partial method implementation is optional.
• If we not provide implementation then complier removes its declaration as well as all the
calls.
• Partial method return type must be void. Giving any other type gives compile time error.
MODIFIED BY SHUBHAM LAMBAT
25

50. Why there is Need of Exception Handling?


• Exceptions are nothing but runtime unforeseen errors of an application.
• It is always a bad practice in showing yellow screen to end user which contains some
application specific information.
• This information is meaningless for a normal user whereas useful for a hacker to hack your
application.
• So, it is always recommended to do a proper exception handling.

51. Can a Try Block have Multiple Catch Block?


• Yes. One try block can have multiple catch blocks.
• But as all exception classes are derived from Exception base class, we have to specify
Exception class in the end catch block. If we specify it at the top then we will get compiler
error.

52. What is purpose of Finally Block? Scenario for Executing Return Statements.
• Finally Block is guaranteed to be executed in both the cases if there is error occurs or not.
• Also, it gets executed if there is any error occurs in catch block.
• So, we can use finally block to close the open connection or if we want to explicitly free the
resources.

53. What is difference between [Link]() and ToString() methods?


• [Link]() handles NULL whereas ToString() doesn’t and it throws
NullReferenceException.

54. What are Enum? What is usage of Enum?


• Enum is the best replacement of an integral constant.
• Default underlying type of Enum is int.
• Enum are value type.
• Enum improve Readability and Maintainability.
• We declare Enum using ‘enum’ Keyword
• Ex :- enum Gender
{
Male, female, other
}
( Call Karte Time automatically Aa jate hai )
Class Student
{
[Link] = [Link]
[Link] = [Link]
}

enum --- e is Keyword


Enum --- E is Class

55. Can we Customize Values in Enum? What is default Start Value to Enum?
• Yes, we can customize the values of Enum.
• The default start value of Enum is 0.

56. What is Default Underlying type to Enum? Can we change its Underlying type to some
other type?
• Default underlying type of enum is int.
• We can anytime change underlying type to any other integral datatypes like byte, short etc.
depending on the size we want to store.
MODIFIED BY SHUBHAM LAMBAT
26

57. What is Difference Between enum and Enum class?


• Enum is a keyword use to create Enumerations.
• whereas Enum class contains static methods like GetValues(), GetNames() which can be used
to list enum underlying type values and their names.

58. What are all default methods Comes with every type in Dot Net? From where they are
Derived? Can we Override Them?
• All types in dot net directly or indirectly derived from Object class
• All these default methods are :
1) GetType()
2) ToString()
3) Equals()
4) GetHashCode()
 We can override ToString(), Equals(), GetHashCode() methods because virtual keyword is in
there method signature.

59. What it GetType() Method?


• Gives the type of the current instance.
int number = 10;
[Link]([Link]());O/P -> System.Int32

60. What is Difference Between Typeof and GetType() method?


• Both the methods are used to get the type of the current instance.
• For typeof method type is known as compile time whereas GetType() method is used to get exact
type of current instance at runtime.
• GetType() method is invoked with instance whereas typeof method expects the type.

61. Why there is Need of Overriding ToString Method?


• When we call ToString() method with built-in types it gives us the string representation of that
current type.
• But if we call ToString() method with Complex types like Customer, Employee it gives us the
fully qualified name of the type that means namespace name followed by type name.
• So to give a meaningful string representation for complex types we can override
ToString() method.

62. Why to override Equals() method? Is there is any Warning/Error Associates with just
Overriding Equals Method? If yes, how to fix it?
• Equals() method works fine with built-in types but when it comes to complex types it checks
only reference equality and not value equality.
• So we can override this Equals() method to check value equality for complex types.
• There is one warning when we override Equals() method and that is we have to override
GetHashCode() method also. This method is helps to generate unique hash codes.

63. Can we overload == operator?


• All arithmetic operators work fine with built-in types.
• But when we use == operators with complex types it just checks reference equality and not
value equality.
• In order to achieve value equality, we have to overload == operator.

64. What are Static, Constant and Read-Only?


Static
 Static fields have a single copy regardless of how many instances of the class are created.
 They are accessed with class name.
MODIFIED BY SHUBHAM LAMBAT
27

Constant
• Constant variables are used to create constant fields.
• It is mandatory to initialize the value at the time of declaration.
• Constant variables value cannot be changed throughout the program.
• They are by default static.

Read-Only –
• Read-Only fields are also similar to constant variables but we can change its value at runtime
through non static constructors.
• It is also not mandatory to initialize value at the time of declaration.
• We can also have static read-only fields in which we can assign value at runtime through static
constructor but only once.

65. What is use of Yield Keyword?


• Yield keyword helps us to do custom stateful iteration over .Net collections.

66. What are Delegates? Why Delegates are Type Safe?


• Delegates are type safe function pointers.
• Delegates signature should get match with method signature that’s why it is called as type safe.
• Delegates allow methods to be passed as parameters.
• Delegates are used to define callback methods.

67. What are types of Delegates? Predicate, Action and Func Delegate?
Basically, there are 2 types of delegates
Singlecast delegate – Delegate pointing to a single method.
Multicast delegate – Delegate Pointing to multiple methods.

Apart from these types we have few generic delegates which extensively used in LINQ
methods.
Action Delegate – Delegate has type T as input parameter and void as return type. 16 overloads.
Predicate Delegate – Delegate has type T as input parameter and bool as return type.
Func Delegate – Delegate has type T as input parameters and T as output parameter. 17
overloads.

67. What are Multicast Delegates?


• A delegate pointing to multiple methods called as multicast delegate.
• It will help to call multiple methods on a single event.
• If the methods have return type or out parameter then the last method value get returned
from delegate.

69. What is Generics? Name some Generic Collections and Non-Generic Collections?
• Generics allows us to design classes and methods decoupled from the data types.
• Which avoid boxing and unboxing operations and offers better performance.
• List<T>, Dictionary<T>, Stack<T>, Queue<T> are few examples of generic collections
classes.
• Array List and Hash Table are few examples of non-generic collections classes.

70. What is Collection Class? Name some Collection Class?


 Collection classes are specialized classes for data storage and retrieval.
 The purpose of collection class is allocating a memory dynamically to element and
accessing list of items on the basis of index.
 Arraylist, HashTable, Stack, Queue are few examples of collections classes.

MODIFIED BY SHUBHAM LAMBAT


28

71. What is difference Between ArrayList and List<>?


• ArrayList is a non-generic collection class whereas List is a generic class.
• ArrayList is object based and it is not type safe because it is associated boxing and unboxing
operations. whereas List is type safe and there are no boxing and unboxing operations which
actually helps to improve system performance.

72. What is difference between HashTable and Dictionary<>?


• Both Hashtable and Dictionary are Key Value Pair collections.
• HashTable is a non-generic collection class whereas Dictionary is a generic class.
• HashTable is object based and it is not type safe because it is associated boxing and unboxing
operations whereas Dictionary is type safe and there are no boxing and unboxing operations
which actually helps to improve system performance.

73. What is Advantage of Generics Collections over Non-Generic Collections?


• Generic collections are type safe because there are no boxing and unboxing operations which
actually helps to improve system performance.

74. What are Anonymous Methods and Extension Methods?


Anonymous methods :
• Anonymous methods are nothing but methods without name.
• Anonymous methods allow us to create delegate instance without having a separate method.
• Anonymous methods are created using delegate keyword.
Extension Methods :
• Extension methods are used to extend the functionality of any existing type.
• These methods are public static methods and its first parameter is prefixed with this keyword.
• It is mandatory to write extension method in public static class.

75. What is Lambda Expression?


• Lambda expression are simplified way to write LINQ queries.
• Lambda Expressions are more convenient than anonymous methods.

76. What is Difference between Anonymous Method and Lambda Expression?


• Lambda expressions are just new way to write anonymous methods.

77. What is Tuple?


• Tuple is collection of heterogeneous types of items.
• We use tuple to return multiple values from method.

78. What is Early Binding and Late Binding?


• Early binding gives errors at compile time with late binding there is a risk of runtime
exceptions.
• Early binding is much better for performance and should always be preferred over late binding.
• Late binding is used only when we are not aware about the objects at compile time.

79. What is Eager Loading and Lazy Loading in C#?


• In eager loading, all the objects are initialized in memory as soon as the objects are created.
• In Lazy loading, we delay the loading of the objects until the point where we need it.
• We have [Link] class to implement lazy loading.

80. Questions on interface like IEnumerable, IQuerable interfaces?


• We use IEnumerable for in memory collection like List, Dictionary whereas we use
IQuerable for remote servers like SQL server.
• IEnumerable doesn’t supports Lazy loading whereas IQuerable supports Lazy loading.
MODIFIED BY SHUBHAM LAMBAT
29

81. How to Restrict a Class for Instantiation?


• We can restrict a class for its instantiation by making that class as a static class or we can write a
private constructor in that class.

82. Private Constructor, how to Initialize? where it is Used? what is Singleton?


• When we write a private or protected constructor in a class, we cannot create instance of that class
from outside of that class.
• We create the instance of a class in that class itself. We use public static method to expose
the instance.
• Singleton pattern ensures that there will be single copy of object throughout the
application and it provides a global point to access that instance.

83. What is Difference Between Static class and a Singleton class?


• A Static class contains only static members whereas in Singleton class we can have both static
and non-static members.
• Singleton class can implement interface whereas static class cannot implement interface.
• We can dispose the object of singleton class but not of static class.

84. How to create a instance of Singleton Class?


Singleton class exposes a single instance through a public static method.
classSingleton
{
privatestaticSingleton _instance;

private Singleton()
{
}
publicstaticSingleton Instance()
{
if (_instance == null)
{
_instance = newSingleton();
}
return _instance;
}
}
• We can write below code to create instance of singleton class.

Singleton s1 = [Link]();
Singleton s2 = [Link]();
[Please note that here s1 == s2 will be true as both are referring to same object.]

• Inheritance scenarios - like multilevel inheritance with new and override keywords.
• Scenario based questions can be asked here –
• Let’s say there are 3 classes A, B and C. Class B is inheriting class A and class C is
inheriting class B.
• There will be a method which will be virtual in class A and it will be hidden by class B and C with
new keyword. Then which methods will get called with below set of objects.
• A a1 = newB();
• A a2 = newC();
• B b1 = newC();
• Same example can be replaced with override keyword or combination of new and override methods.
We have to think on the type of object and give the answers.
MODIFIED BY SHUBHAM LAMBAT
30

85. What is Association, Aggregation and Composition in C#?


Association
• Inheritance defines the ‘is a’ relationship just like Association defines ‘has a’ relationships
between objects.
• In short, Association means an object “uses” another object.
• We can define one-to-one, one-to-many, many-to-one and many-to-many objects’
relationships.

Aggregation
• Aggregation is a special type of association.
• It is a direct association among the objects.
• For example, departments and employees, a department has many employees but a single
employee is not associated with multiple departments. In this case both the objects have their
own life cycle. Employees may exist without a department. Here, department can be called an
owner object and the employee can be called a child object.

Composition
• Composition is special type of Aggregation.
• In this type of Aggregation, the child object does not have their own life cycle. The child object's
life depends on the parent's life cycle. Only the parent object has an independent life cycle. If we
delete the parent object then the child object(s) will also be deleted. We can define the
Composition as a "Part of" relationship.
• For example, the company and company location, a single company has multiple locations. If we
delete the company then all the company locations are automatically deleted. The company
location does not have their independent life cycle, it depends on the company object's life (parent
object).

86. Can we Write 2 Parameter less Constructor in one Class?


 Yes, we can write 2 parameter Less Constructor in One Class.
o Normal Constructor
o Static Constructor

MODIFIED BY SHUBHAM LAMBAT


31

LINQ
1) What are Lambda Expressions?
- A lambda expression is an anonymous function that can contain expressions and statements, and can
be used to create delegates or expression tree types.
- All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the
lambda operator specifies the input parameters (if any) and the right side holds the expression or
statement block.
- Ex: The => operator has th
- Lambdas are used in method-based LINQ queries e same precedence as assignment (=) and is right-
associative.
- as arguments to standard query operator methods such as Where and Where (IQueryable, String,
array []).

2) How do you Assign a Lambda Expression to a Delegate?


- delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25

3) Can we write a Lambda Expression on the Left Side of the “is” or “as” Operator?
- Lambdas are not allowed on the left side of the is or as operator.

4) What is Expression Lambda?


- A lambda expression with an expression on the right side is called an expression lambda.
- Expression lambdas are used extensively in the construction of Expression Trees.
- An expression lambda returns the result of the expression and takes the following basic form:
(Input parameters) => expression

- The parentheses are optional only if the lambda has one input parameter; otherwise, they are required.
- Two or more input parameters are separated by commas enclosed in parentheses:
(x, y) => x == y

- Sometimes it is difficult or impossible for the compiler to infer the input types. When this occurs, you
can specify the types explicitly as shown in the following example:
(int x, string s) => [Link] > x

- Specify zero input parameters with empty parentheses:


() => SomeMethod()
(Note in the previous example that the body of an expression lambda can consist of a method call.
However, if you are creating expression trees that will be consumed in another domain, such as SQL
Server, you should not use method calls in lambda expressions. The methods will have no meaning
outside the context of the .NET common language runtime.)

5) What is Statement Lambda?


- A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces:
(input parameters) => {statement;}
- The body of a statement lambda can consist of any number of statements; however, in practice there
are typically no more than two or three.
delegate void TestDelegate(string s);
TestDelegate myDel = n =>{string s=n+" "+"World"; [Link](s); }; myDel("Hello");

6) What is the Difference between Statement Lambdas and Expression Lambdas?


- Expression lambdas are used extensively in the construction of Expression Trees.
- Statement lambdas cannot be used to create expression trees.
MODIFIED BY SHUBHAM LAMBAT
32

7) What is Type Inference in Lambdas?


- When writing lambdas, you often do not have to specify a type for the input parameters because the
compiler can infer the type based on the lambda body,
- the underlying delegate type, and other factors as described in the C# 3.0 Language Specification.
- For most of the standard query operators, the first input is the type of the elements in the source
sequence.
- So, if you are querying an IEnumerable, then the input variable is inferred to be a Customer object,
which means you have access to its methods and properties:

[Link](c => [Link] == "London");

8) Explain Rules of Lambdas?


- The lambda must contain the same number of parameters as the delegate type.
- Each input parameter in the lambda must be implicitly convertible to its corresponding delegate
parameter.
- The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.

9) Does Lambda Expressions in Themselves do have a Type?


- Lambda expressions in themselves do not have a type because the common type system has no
intrinsic concept of lambda expression.
- However, it is sometimes convenient to speak informally of the "type" of a lambda expression.
- In these cases, the type refers to the delegate type or Expression type to which the lambda expression
is converted.

10) Explain about Variable Scope in Lambda Expressions?


- Lambdas can refer to outer variables that are in scope in the enclosing method or type in which the
lambda is defined.
- Variables that are captured in this manner are stored for use in the lambda expression even if variables
would otherwise go out of scope and be garbage collected.
- An outer variable must be definitely assigned before it can be consumed in a lambda expression.

11) List out the Rules apply to Variable Scope in Lambda Expressions?
- A variable that is captured will not be garbage-collected until the delegate that references it goes
out of scope.
- Variables introduced within a lambda expression are not visible in the outer method.
- A lambda expression cannot directly capture a ref or out parameter from an enclosing method.
- A return statement in a lambda expression does not cause the enclosing method to return.
- A lambda expression cannot contain a goto statement, break statement, or continue statement whose
target is outside the body or in the body of a contained anonymous function.

12) What are Expression Trees?


- Expression trees represent language-level code in the form of data. The data is stored in a tree-shaped
structure. Each node in the expression tree represents an expression, for example a method calls or a
binary operation such as x <>
- // Create an expression tree.

Expression<func> exprTree = num => num <>


// Decompose the expression
[Link] param = (ParameterExpression)[Link][0];
BinaryExpression operation = (BinaryExpression)[Link];
ParameterExpression left = (ParameterExpression)[Link];
ConstantExpression right = (ConstantExpression)[Link];

MODIFIED BY SHUBHAM LAMBAT


33

13) Are Expression Trees Immutable?


- Expression trees are immutable.
- This means that if you want to modify an expression tree, you must construct a new expression tree
by copying the existing one and modifying it.
- You can use an expression tree visitor to traverse the existing expression tree.

14) What is LINQ?


- LINQ Stand for Language-Integrated Query.
- Using LINQ, we can write common Syntax or all type of Data Source.
- Data Source, like in Memory Collection, Dataset, SQL Tables, Entities, XML, etc.
- It Is Familiar Language.
- Compiler Support LINQ.
- Intelligence Support.
- LINQ is a set of features in Visual Studio 2008 that extends powerful query capabilities to the language
syntax of C# and Visual Basic.
- LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology
can be extended to support potentially any kind of data store.

15) Why LINQ is Required?


- LINQ that bridges the gap between the world of objects and the world of data.
- Traditionally, queries against data are expressed as simple strings without type checking at compile
time or Intelligence support.
- Furthermore, you have to learn a different query language for each type of data source: SQL
databases, XML documents, various Web services, and so on.
- LINQ makes a query a first-class language construct in C# and Visual Basic.
- You write queries against strongly typed collections of objects by using language keywords and
familiar operators.

16) Advantages of LINQ?


- Familiar Language
- Less Coding
- Readable Code
- Compile Time Safety of Queries
- Intelligence Support
- Shaping Data
- Standardized way of Querying Multiple data Source

17) For Programming What Import in LINQ?


- We need ([Link]) Namespace for LINQ API.

18) How LINQ is beneficial than Stored Procedures?


- There are couple of advantage of LINQ over stored procedures.
1. Debugging - It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you
can use visual studio's debugger to debug the queries.
2. Deployment - With stored procedures, we need to provide an additional script for stored procedures
but with LINQ everything gets complied into single DLL hence deployment becomes easy.
3. Type Safety - LINQ is type safe, so queries errors are type checked at compile time. It is really good
to encounter an error when compiling rather than runtime exception!

19) What is the Benefit of using LINQ on Dataset?


- The main aim of using LINQ to Dataset is to run strongly typed queries on Dataset.
- Suppose we want to combine the results from two Datasets, or we want to take a distinct value from
the Dataset, then it is advisable to use LINQ.
MODIFIED BY SHUBHAM LAMBAT
34

- Normally you can use the SQL queries to run on the database to populate the Dataset, but you are not
able to use SQL query on a Dataset to retrieve a particular value.
- To get this you need to use [Link] functionalities. But, in case of LINQ, it provides more dignified
way of querying the Dataset and provides some new features as compared to [Link]

20) What are Quantifiers?


- They are LINQ Extension methods which return a Boolean value
1)All
2)Any
3)Contains
4)SequenceEqual
- example:
int[] arr={10,20,30}; var b=[Link](a=>a>20);
Output:
b will return False since all elements are not > 20.

21) Difference between XElement and XDocument


- Both are the classes defined by [Link] namespace
- XElement class :
o represents an XML fragment
- XDocument class :
o represents an entire XML document with all associated meta-data.
- Example:
XDocument d = new XDocument(
new XComment("hello"),
new XElement("book",
new XElement("bookname", "[Link]"), new XElement("authorname", "techmedia"),
));

22) What is the Difference between N-layer and N-tier Architecture?


- N-layers of application may reside on the same physical computer (same tier) and the components in
each layer communicates with the components of other layer by well-defined interfaces.
- Layered architecture focuses on the grouping of related functionality within an application into distinct
layers that are stacked vertically on top of each other.
- Communication between layers is explicit and loosely coupled. With strict layering, components in one
layer can interact only with components in the same layer or with components from the layer directly
below it.
- The main benefits of the layered architectural style are:
Abstraction, Isolation, Manageability, Performance, Reusability, Testability.

- N-tiers architecture usually have atleast three separate logical parts, each located on separate physical
server. Each tier is responsible with specific functionality.
- Each tier is completely independent from all other tier, except for those immediately above and below
it. Communication between tiers is typically asynchronous in order to support better scalability.
- The main benefit of tier architecture styles are:
1. Maintainability. Because each tier is independent of the other tiers, updates or changes can be
carried out without affecting the application as a whole.
2. Scalability. Because tiers are based on the deployment of layers, scaling out an application is
reasonably straightforward.
3. Flexibility. Because each tier can be managed or scaled independently, flexibility is increased.
4. Availability. Applications can exploit the modular architecture of enabling systems using easily
scalable components, which increases availability.

MODIFIED BY SHUBHAM LAMBAT


35

23) Difference between FirstOrDefault() and SingleOrDefault() extension method in LINQ?


- FirstOrDefault () :-
o It Return First Matching Item from Given Collection.
o It Handle Exception & Return Default Value.
o This Exception: throw Exception if no Matching item from given Collection

- SingleOrDefault () :-
o It Return First Matching Item from Given Collection.
o It Handle Exception & Return Default Value.
o This Exception: throw Exception if no Matching item from given Collection
o It Does Not Handle Exception Of Multiple Matching Element

24) Difference between First() and Single() extension method in LINQ?


- First () :-
o It Return First Matching Item from Given Collection
o Throw Exception if no matching item from given collection

- Single () :-
o It Return First Matching Item from Given Collection
o It Throw Exception in two Scenario :
 If there are multiple matching item
 If no matching item from given collection

25) Difference Between IEnumerable Vs IQueryable


- IEnumerable Vs IQueryable
- In LINQ, to query data from database and collections we use IEnumerable and IQueryable.
- IEnumerable is inherited by IQueryable, so it has all features of it and of its capabilities. Both has their
own importance to query data and data manipulation.

- IEnumerable: -
o It exists in [Link] namespace.
o It can move forward only over collection.
o It is best to query data from in-memory collections like Array, List, etc.
o It is suitable for LINQ to Objects & LINQ To XML queries.
o It doesn't support lazy loading, hence not suitable for paging like scenario.
o We use IEnumerable for in memory collection like List, Dictionary
DataContextClasses db= new DataContextClasses();
IEnumerable<Employee>List = [Link](m=>[Link]("a"));
list=[Link]<Employee>(10):

- IQueryable: -
o It exists in [Link] namespace.
o It can move forward only over collection.
o It is best to query data from out-memory like remote database.
o It is suitable for LINQ to SQL queries.
o It supports lazy loading, hence suitable for paging like scenario.
o we use IQuerable for remote servers like SQL server.
DataContextClasses db= new DataContextClasses();
IQueryable<Employee>List =[Link](m => [Link]("a")); list=list.
Take<Employee> (10);

MODIFIED BY SHUBHAM LAMBAT


36

26) What is Var?


- Var is used to declare implicitly typed local variable means it tells compiler to figure out the type of
the variable at compile time.
- Since, 'var' is anonymous type, hence it is used where we don't know the type of output like joining of
two tables.
- Ex:-
var q = (
from e in tblEmployee join d in tblDepartment
on [Link] equals [Link]
select new
{
[Link], [Link], d. DeptName
});

27) Sorting Operator?


- OrderBy, OrderByDescending, ThenBy, ThenBy,ThenByDecending, Reverse.
o OrderBy: Sort The Element in collection ascending or descending order.
o OrderByDescending: Sort the collection Based on fields in descending order.
o ThenBy: It is used after orderby. Used for second level sorting in ascending order.
o ThenByDescending: It is used for sorting in descending order.
o Reverse: Sort the collection in reverse order.

28) Filtering Operator?


- Where: Return value from the collection.
- OfType: Return value from the collection.

29) Grouping operator?


- GroupBy Operator: returns group of elements based on some key value. Execution of groupBy is
deferred.
- ToLookup: it is same as groupBy, Execution of toLookup is immediate.

30) Joining Operators?


- Join: join two collections based on a key and returns a resulted collection.
- GroupJoin: Join two collections based on keys and returns group of collections. It is like left oputer
join of SQL.

31) Projection Operators?


- Select: It is always return an IEnumerable collection which contains element based on a
transformation function.
- SelectMany

MODIFIED BY SHUBHAM LAMBAT


37

JAVASCRIPT
1. What is JavaScript? or JavaScript is which type of Language?
 It is object-based scripting language.
 It is widely used for client-side validation.
 It is Programming Language just like C#, Java, C++, etc.
 We can use JavaScript as a client side as well as server-side language. (Using [Link])
 Most of the time we use it as a client side scripting language.
 To manipulate HTML element.
 To Validate User Input.
 To Communicate with server side code.
 Faster Language
 Disadvantages :-
 JavaScript code is not secure.
 Browser Combability Issue

2. Why we Use JavaScript?


 Using HTML, we can only design a web page but cannot run any logic on web browser at
client side.
 Like addition of two numbers, check any condition, looping statements (for, while), decision
making statement(if-else) etc.
 So, for perform all these tasks at client side we use JavaScript.

3. Is JavaScript Case Sensitive?


 Yes

4. Where JavaScript is Used?


 It is used to create interactive websites.
 It is mainly used for:
 Client-side validation
 Dynamic drop-down menus
 Displaying Date and Time
 Build small but complete client-side programs
 Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog
box and prompt dialog box)
 Displaying clocks etc.

5. How do we add JavaScript onto a Web Page?


 Between <body><body/> tag of html using <script><script/> tag.
 Between <head><head/> tag of html using <script><script/> tag.
 Add in .js file and refer url whenever required. (External JavaScript)

6. What is the Difference Between == and ===?


 The == sign checks only value equality whereas === sign checks for type and value equality.
Ex. var i = 10; var j = “10”;
Var a = (i==j) ----> True
Var b = (i===j) ----> False

7. How to Declare Variable in JavaScript?


 We can use var keyword to declare variables in JavaScript.
 Because JavaScript did not provide any data types for declaring variables.

MODIFIED BY SHUBHAM LAMBAT


38

8. What would be the difference if we declare Two Variables inside a JavaScript, one with
'var' keyword and another without 'var' keyword?
 The variable with var keyword inside a function is treated as Local variable
 Whereas the variable without var keyword inside a function is treated a global variable.

9. What is Function Hoisting in JavaScript?


 By default, JavaScript moves all the function declarations to the top of the current scope
is called function hoisting.
 Also, JavaScript moves all function declaration before their call.
 It means we can call function before we declare function.

10. How to write Function in JavaScript?


function Add(a,b)
{
[Link](a + b);
}
Add(10,10);

11. How to write Anonymous Function in JavaScript?


var Add = function(a,b)
{
[Link](a + b);
}
Add(10,10);

12. What is Self-Invoked Function or Immediately-Invoked Function Expression


(IIFE) in JavaScript?
 This function invoked automatically without being called.
 Ex : -
(function (a, b)
{

[Link](a + b);
})
(10,10);

13. What is a Closure in JavaScript?


 Function Within Function.
 JavaScript allows you to declare a function inside function
 And inner function has access of outer function variables and outer function parameter called
closure.
 Ex : -
function add(a, b)
{
var result = “Addition = “;
function add()
{
[Link](result + (a + b));
};
add();
};

MODIFIED BY SHUBHAM LAMBAT


39

14. How to Access the Value of a Textbox using JavaScript?


 Using var tb = getElementById (“ ”).value

15. How to create Arrays in JavaScript?


 var array = new Array (2); // 2 is size of array and it automatically grows
 var array = new Array (10,20); // we can also pass arguments in array
 var array = [10,20,30,40];

16. What is the Array Mutators?


 The methods that modify the array objects are called a mutator methods.
1) push() :
 push() method adds new item to the end of array.
 Also Increase Size.
2) pop() :
 pop() method removes the last item of an array.
 Also Decrease The Size
3) unshift() :
 unshift() method adds new item at start of array.
4) shift() :
 shift() method removes first item of an array.
5) reverse() :
 reverse() method reverse the sequence of an array elements.
6) sort() :
 sort() method sorts the elements of an array.
 Either Ascending Or Descending
 sort() method works well for string not for integers, we can fix this by providing a
compare function.
7) splice() :
 splice() method used to remove and add elements in array on index basis.
 Syntax :- splice(Start, Count)
 If we want to add or delete element in between array.

17. What is Event Bubbling in JavaScript?


 With event bubbling the event bubbles up (i.e. triggers) from inner most element to
outer most element in the DOM hierarchy.
 If we have nested HTML element, all element assigns with events in this case when
inner element event gets triggered, it fires all events from inner to outer elements.
 Event gets Bubbled from Inner to Outer element.
 For Preventing Event Bubbling: - stopPropagation ().

18. What is Event Capturing in JavaScript?


 With Event Capturing the event captured (i.e. triggers) from outer most element to inner most
element in the DOM hierarchy.
 Opposite to Event Bubbling.
 Events gets Fired from Outer to Inner elements.

19. How to Prevent Browser Default Action?


 When we click on link it will redirect to link url.
 When we right click it gives context menu.
 To prevent these type browser action, we use
onContextMenu = “return false”

MODIFIED BY SHUBHAM LAMBAT


40

20. What does the isNaN() Function?


 The isNan() function returns Boolean as output when we check for variable is a number or
not.

21. How can you Submit a Form using JavaScript?


 To submit a form using JavaScript use [Link][0].submit();

22. What is Substrings in JavaScript?


1) Substring ():
 This method has 2 parameters Number start and Number end. { substring (Index, End Index) }
 Start parameter is required and specifies the position where to start the extraction.
 End parameter is optional and specifies the position where the extraction end.
 When end parameter not specified then all the characters from the start position to
end of the string are extracted.
 If value of start parameter is greater than end parameter then it swaps the two arguments.

2) slice ():
 Same as substring () method but does not swap arguments.

3) substr ():
 This method has 2 parameters Number start and Number length. { substr (index, count) }.
 Start parameter is required and specifies the position where to start the extraction.
 Length parameter is optional and specifies the length where the extraction end.
 If value of start parameter is greater than end parameter then it does not swap the two
arguments.

23. What is JavaScript Argument Object?


 The JavaScript argument object is a local variable which is available within all functions.
 With argument object we can access function parameters passed to function like an array.
 The length property of the arguments object returns the number of arguments passed to
function.

24. What are JavaScript Timing Events?


1) setInterval(func,delay) :
 Executes a specified function repeatedly at specified time interval.

2) setTimeout(func,delay) :
 Executes a specified function after waiting a specified number of milliseconds.

3) clearInterval(intervalID):
 Cancels the repeated execution of the method that was setup using setInterval()
method.

25. Does JavaScript Support Automatic Type Conversion?


 Yes, JavaScript does support automatic type conversion,
 it is the common way of type conversion used by JavaScript developers.

26. What are all the Looping Structures in JavaScript?


 While
 Do-While
 For

MODIFIED BY SHUBHAM LAMBAT


41

27. What are the Mouse Events in JavaScript?


 An event is signal from browser that something has happened.
1) mouseover : Occurs when the mouse pointer is moved over an element.
2) mouseout : Occurs when the mouse pointer is moved out of an element.
3) mousemove : Occurs when the mouse pointer is moving over an element.
4) mouseup : Occurs when the mouse button is released over an element.
5) mousedown : Occurs when the mouse button is pressed over an element.
6) click :Occurs when the mouse button is clicked.
7) dblclick :Occurs when the mouse button is double clicked.
8) contextmenu :Occurs when the mouse right button is clicked.

28. What are the Regular Expressions in JavaScript?


 Regular expression is a sequence of characters that forms a search pattern.
 We use Regular Expression to validate Patterns.
 Patterns like Email, Strong Password, Pin Code, Mobile Number, Etc.

1) match() : All numbers in string will be returned.


2) replace() : All numbers will be replaced with given parameter.
3) split() : Breaks a string into an array of substring.
4) search() : Returns the index of the first matching item only.

29. What is JavaScript Minification?


 JavaScript minification is the process of reducing the script file by removing
1. All Comments
2. Extra spaces and line that are not needed for executing JavaScript code.
3. Its shorthand’s variable names

 The JavaScript minification may reduce the size of the file by 30 to 90%.
 The minification process will not change its original functionality.
 Technique to compress JavaScript file.
 Normal File – [Link]
 Minified File – [Link]

Advantages:
o Reduce download time of JavaScript file on client machine before browser can execute
your js code.
o Multiple JavaScript files can be compressed into one minified js file.

Dis-Advantages:
o Readability is lost.

30. What are all the Types of Pop-up Boxes Available in JavaScript?
- Alert –
o Alert box displays only one button which is the OK button.
- Confirm –
o Confirmation box displays two buttons namely OK and Cancel.
- Prompt

31. How to Handle Exceptions in JavaScript?


- By using try-catch block

MODIFIED BY SHUBHAM LAMBAT


42

32. What are the Different types of Errors in JavaScript?


 There are three types of errors:

1) Load Time Errors:


Errors which come up when loading a web page like improper syntax errors are known as
Load time errors and it generates the errors dynamically.

2) Run Time Errors:


Errors that come due to misuse of the command inside the HTML language.

3) Logical Errors:
These are the errors that occur due to the bad logic performed on a function which is having
different operation.

33. What is DOM?


 DOM means Document Object Model.
 DOM gets created once entire HTML gets loaded on Browser.
 Browser creates DOM-Document.
 DOM contain entire information about HTML page & its Elements.
 DOM represents logical tree structure of HTML elements.

34. What is DOM Property?


 DOM properties are values of HTML elements that you can set or change.

35. What Z index in CSS?


 Z index specifies the stack order of an element.
 An element with greater stack order is always in front of an element with a lower stack order.
 z-index only works on positioned elements.
 If we want add background image then we can use Z index.

36. What Strict Mode in JavaScript?


 Used to generate silent error.

37. What is View Port?


 The viewport is the user's visible area of a web page.

38. What is Media Query?


 Media query is CSS property used for Responsive Web Design.

MODIFIED BY SHUBHAM LAMBAT


43

39. What is Responsive Design?


 Responsive web design is about creating web pages that look good on all devices.
 A responsive web design will automatically adjust for different screen sizes and
viewports.

40. Difference between Local Storage and Session Storage?


 Local storage is similar to session storage.
 But the data in local storage doesn’t expire Whereas data in session storage is expired when
page session ends.

41. What is the file in Local Storage?


 Browser setting, Browser extensions.

MODIFIED BY SHUBHAM LAMBAT


44

jQuery
1. What is jQuery?
 jQuery is JavaScript library.
 jQuery greatly simplifies JavaScript programming.

 The main Advantage of jQuery is: -


1. It is Lightweight
2. Simple and Easy to Learn.

2. Why use jQuery?


 For perform any task, jQuery requires less code as compared to JavaScript.
 It supports all web browser, AJAX capabilities, Event detection and handling, Manipulate
CSS style, and Predefined method for create Animation.
 Many of the biggest companies on the Web use jQuery, such as: Google, Microsoft and IBM.

3. Why needs [Link] event?


 [Link] method allows us to execute a function when document is fully
loaded.

4. What is Chaining?
 Chaining is used to run multiple jQuery methods (on the same element) within a single
statement.

5. What is Callback Function?


 A callback function is a function passed as a parameter to another function.

6. How JavaScript is Differed from jQuery?


 JavaScript is a language and jQuery is a built-in library for JavaScript.

7. Is jQuery a Library for Client Scripting or Server Scripting?


 Obviously, jQuery is a library for client-side scripting.

8. What is the Basic Need to Start with jQuery?


 To use jQuery library on your web-page you need to give reference of jQuery library.

1) Include jQuery from a CDN, like Google


2) Local Copy –
o Download from google and save in our project folder and give reference.

9. Which is Starting Point of Code Execution in jQuery?


 $(document).ready(function( ){ });

10. What is Dollar Sign ($) in jQuery?


 Dollar Sign is an alias for jQuery.
 You can write jQuery at the place of $

$.noConflict(); --> noConflict() method releases jQuery control of the $ variable.

11. Can we have Multiple [Link]() Function on the Same Page?


 Yes. You can write any number of [Link]() function on the same page.

MODIFIED BY SHUBHAM LAMBAT


45

12. Difference Between Body Onload() and [Link]() function?


 You can have more than one [Link]() function in a page where we can have only
one body onload function.

13. What is a CDN?


 It is a Content Delivery Network or Content Distribution Network (CDN)
 It is a large distributed system of servers deployed in multiple data centers across the
Internet.

Advantages :
 It reduces the load from your server.
 It saves bandwidth.
 When any user visit on other website it saves in browser, as a result next time easily load.

14. How to Iterate Object in jQuery?


 We can use each() method to iterate object in jQuery.

15. What are the Selectors in jQuery?


 Selectors are used to select or find the HTML element.
 To Find Element from HTML page.
 Some selectors are:
1. Class Selector: - Represented by single dot.
2. Id Selector: - Represented by single hatch (Faster selector in jQuery).
3. Element Selector: - Represented by single element name.
4. Element with Attribute: - Represented by single element name with attribute name.
5. This Selector
6. Tag Selector
7. Attribute Selector
8. Tag With Attribute Selector
9. Attribute With Value Selector

MODIFIED BY SHUBHAM LAMBAT


46

SOLID Principle
What is SOLID Principle?
- We use to create a better application architecture.
- S  SRP  Single Responsibility Principle
- O  OCP  Open Close Principle
- L  LSP  Lisko Substitutions Principle
- I  ISP  Interface Segregation Principle
- D  DIP  Dependency Inversion Principle

SRP :-
o It says we should create class/interface/methods which are responsible for a single task concern.
o Or its means a class should have only one responsibility.
o Or a Class Should have only one reason to change.
o In My Project One Class is responsible for one Operation.
OCP :-
o Code Should be open for extension & closed for modification.
o To implement OCP we can use Extension Method.
LSP :-
o It Say child class object can replace parent class object always.
o Base class reference variable can point to any of its derived class object
o Object of child class must be able to replace & object of parent class without breaking
application.
o All base class method must be applicable for all the derived class. For that we can use Interface.
o Ex:-
 I have 2 class in we can inherit that class.
 In that base class have one method and that is virtual
 In derived class can also contain same method and its override
 Now if we create base class object then we can call base class method
 And if we create a deriver class object then it will call derived class method.
 Its work easily and we can also give output and our application is also work properly
its means we can fulfil the need of LSP.
ISP :-
o A class Should not be forced to implement Interface that does not use.
o It is better to have multiple smaller Interface than larger Interface.
o Ex.
o We crate FlyCar Class and in that we have two method drive and fly
o And if create a simple car class and inherit the FlyCar class then we have to
implement both drive and fly method and it is not good for performance.
o That’s why we create 2 different Interface 1st is Fly And 2nd is Drive.
o And now if we create simple car class then we only inherit drive interface.
o Or if we create FlyCar Class Then we Inherit both Fly & Drive Interface
DIP :-
o High level module should not directly depend on low level module instead they should
depend through abstract class or Interface.
o High Level Module or Low-level module means Concrete Class.

MODIFIED BY SHUBHAM LAMBAT


47

DESIGN Pattern
What is Design Pattern?
- Help to solve OOPs Problem.
- OOP - Class, Object, Inheritance, Polymorphism, Abstraction, Encapsulation, Association.
- Design Pattern tell about Code.
- Tyes Of Design Pattern :-
o Structural Design Pattern
o Creational Design Pattern
o Behavioral Design Pattern

a. Singleton Design Pattern:


o To restrict object outside of that class and to maintain one single object of a class through the
application
b. Factory Design Pattern:
o Object creation Responsibility in case of inheritance.
o There should not be flowing new keyword throughout application
c. Dependency Injection (DI):
o We is DI to implement DIP(Dependency Inversion Principle)
o High level module should not directly depend on low level module instead they should
depend through abstract class or Interface.
o Ways To Inject Dependency (To create object of Interface / Abstract Class)
 Injection through Constructor
 Injection through Property
 Injection through Method
d. IoC Container:
o Inversion of Control
o We use IoC container for
 Registering Type (Dependency)
 Resolving Type

MODIFIED BY SHUBHAM LAMBAT


48

[Link]
1. What is [Link]?
 [Link] is Microsoft’s framework to build Web applications.
 In [Link] we create aspx pages.
 In [Link] Corewe create Razor Pages, means .cshtml.
 In [Link] user request for physical file i.e. aspx page

2. From which base class all web forms are inherited?


 Page class

3. What is Event? Explain its types?


 Events get automatically fires against some action.
Types:
1) Application-Level Events:
 Application-level events fires when application starts.
 These events fire once.
 Application-level events located in [Link] file.
 Global class inherits HttpApplication class.
 Application-level events are as follows:
a) Application_Start
b) Session_Start
c) Application_BeginRequest
d) Application_EndRequest
e) Session_End
f) Application_End

2) Page Level Events:


 Page level events are Page specific.
 Page level events are as follows:
a) Page_PreInit
b) Page_Init
c) Page__Load
d) Page_PreRender
e) Page_PreRenderComplete

3) Control Level Events:


 Control level events are Control specific.
 Control level events are as follows:
a) Postback event
b) Cached event

4. What are the State Management Techniques?


 Http is stateless protocol means all information that associated with the page along with
the controls on the page would be lost with each roundtrip from browser.
 To overcome this type of problems, we use state management techniques which
maintains and stores the information of any user till the end of the user session.
 There two types of state management techniques:
1) Client-Side State Management Techniques
 In Client based option, information get stored either in the page or on the client
computer.
 Some Client based state management techniques are:

MODIFIED BY SHUBHAM LAMBAT


49

a) Hidden Fields
 Hidden field provides a way to store state information in the page.
 Value property of the Hidden Filed is used to get or set the value.
 Hidden fields value is stored as string i.e. plain text.
 Scope on same Page.

b) ViewState
 ViewState is used to retain value across postback.
 ViewState value is object type.
 ViewState value get stored in base64 encrypted format.
 ViewState is slower than HiddenFieldbecozViewState internally uses
HiddenField.
 Scope on same Page.

c) Query strings
 Query strings is a very common way to send data from one webform to
another.
 Query strings are appended to the page URL.
 ?(Question Mark), indicates the beginning of a query string and its value.
 It is possible to use more than one query string, the first query string is
specified using the ?(question mark). Subsequent query strings can be
appended to the URL using the &(ampersand) symbol.
 Query strings are visible to the user, hence should not be used to send
sensitive information, unless encrypted.
 To read the query string value, use [Link] property.

d) Cookies
 Cookies can be used to send data from one webform to another.
 Cookies store at browser Side on user machine.
 [Link] command is used to create cookies.
 [Link] command is used to retrieve cookie value.
 Cookies are browser specific.
 Persistent Cookie:
Cookie has Expiration Time.
 Non-Persistent Cookie:
These cookies expired when browser is closed.
 Cookies are by default Non-Persistent.

2) Server-Side State Management Techniques


 In Server based option, information get stored on the server side.
 Some Server based state management techniques are :

a) Session
 Session data stored in server memory.
 Session state variables are available across all pages but only for a given single
session.
 Session variables are like single-user global data.
 Session state variables are stored on the web server.
 The default session state mode is InProc.
 Session State variables are cleared, when the user session times out.
 The default timeout is 20 minutes. This is configurable in [Link]

MODIFIED BY SHUBHAM LAMBAT


50

b) Application
 Application State variables are available across all pages and across all
sessions.
 Application State variables are like multi-user global data.
 Application State variables are stored on the web server.
 Application State variables are cleared, when the process hosting the
application is restarted.

c) Cache
 Caching is the technique of storing frequently used data/pages in memory.

5. What are the Redirection Techniques?


1) Hyperlink Control:
 Add Hyperlink from Toolbox and use NavigateURL tag to redirect from one page to
another page of same application or different application.
 Hyperlink does not allow to write event.

2) PostBackURL:
 Add Button from Toolbox and use PostBackURL as tag.
 We can’t redirect to another application page URL.

3) [Link]:
 Redirection done within same server.
 Redirection done by the server.
 URL does not change.
 It skips current page and give target page content.

4) [Link]:
 Redirection done within same server.
 Redirection done by the server.
 URL does not change.
 It does not skips current page and gives target page content as well as current page
content.

5) [Link]:
 Redirection can be done across multiple servers.
 Redirection done by the [Link] get changed.
 Skip current page.

6) [Link]():
 To open a popup window use [Link]() method.
 [Link](URL, name, feature, replace)
 <input type = “button” value = “Open Google”
onClick = “[Link]()”/>

6. .Net Invention
- WebForm (2002)  .NET MVC (2009)  .NET Core (Jun 2016).

7. .NET Core Version.


- Jun 2016(1.0) Aug 2018(2.0) Sept 2019(3.0) Dec 2019(3.1) Nov 2020(5.0) Nov 2021(6.0)

MODIFIED BY SHUBHAM LAMBAT


51

8. [Link] Core Importance.

MODIFIED BY SHUBHAM LAMBAT


52

MVC
1. What are Features in MVC5?1
- With MVC 5 there are many important features were introduced. Support for Bootstrap, Attribute
based routing, [Link] identity support.
[Please refer [Link]
for details. Interviewer can ask you about explanation on any of the feature you mentioned. ]

2. How Request and Response Occurs in MVC Application?


- Whenever user initiates the request with the help of routing it finds the controller.
- It creates of object of that controller and start execution for requested action method.
- If action method is returning a ViewResult then it finds appropriate view and returns to the
browser.
[Please follow below diagram if interviewer ask you to write a flow. No need to mention entire
things he wants high level things from this pipeline.]

3. What is RouteConfig File?


- In RouteConfig file we define routes for our application.
- There is a method called RegisterRoutes which contains all routings which is configured in
Application_Start event of [Link] file.

4. Can we write {controller}/{id}/{action}?


- Yes, we can define such routing. But we need to take care for url request.

5. What are Filters in MVC?


- Using filters, we can add pre and post processing logic for any action methods.
- We can apply these filter attributes either on controller or on action methods.
- Types of Filters:
o Authorization Filter
o Resource Filter
o Action Filter
o Result Filter
o Exception Filter

MODIFIED BY SHUBHAM LAMBAT


53

6. How to Implement Custom Filters?


- All types of filters in MVC implements interfaces like IActionFilter, IExceptionFilter.
- If we want to create custom filters then either we can implement these interfaces or we can override
methods from Filter Attribute classes.

7. How did you Implement Authentication and Authorization filters?


[Link]

8. How you Handled Global Error Handling in MVC?


- We can write a custom filter for HandleError attribute or IExceptionFilter and we can provide our
own implementation for OnException method.
- We can register this custom error filter in FilterConfig file which will be then applied to all action
methods in application or we can apply this class at controller level or at action method.

9. What is difference between [Link] and MVC Application?


- There are various differences between [Link] and MVC
application.

a) MVC is lightweight compare to [Link].


b) [Link] application we request to a physical file i.e. Web forms whereas in MVC application we
request to a controller action methods.
c) [Link] application uses server controls which makes page heavy but in MVC we use HTML
helpers which are lightweight.
d) [Link] code is tightly bind with code behind file whereas in MVC view and action methods
are separated.
e) [Link] is event based development model whereas MVC is an architectural pattern with
Model Views and Controllers.

10. How to Transfer Data from View to Controller?


- We can use
a) Query string
b) Hidden fields
c) Form posted values
to transfer data from view to controller.

11. How to Transfer Data from Controller to View?


- There are multiple ways to transfer data between controllers to view.
- We can use
a) ViewBag
b) ViewData
c) TempData
d) Session
e) Strongly typed View
depending on scope we want to implement.

12. Can we Transfer Data from Controller to View using TempData?


- Yes, we can pass data from Controller to View using Tempdata.
- We can access TempData object in View.

13. Which Version of MVC you have Used?


- We have used MVC 6 in our last project.

MODIFIED BY SHUBHAM LAMBAT


54

14. What is HttpVerbs in MVC?


- HttpVerbs decides the request type whether it is a GET or POST requests.
- Either we can use HttpVerbs attribute to specify or we can directly use HttpGet or HttpPost to specify
type of request.

15. What is Area? Have you used in your project?


- Yes, we have used areas in our project.
- We created role-based areas in our project.
- Area is a group of models, view, controllers.
- For complex application, number of controllers may vary according to modules.

16. What is Difference Between [Link] and [Link]?


- If a view is strongly typed view, then we can use [Link] which gives us intelligence and
it automatically take id and name with the help of lambda expression we write.
- Whereas [Link] we use in normal views where we have to specify all attribute values
separately.

17. Which Filters you have used in your Project?


- We have used Authorize filter for authentication.
- HandleError filter for exception handling
- OutputCache filter.
- We have created custom filters for global error handling.
[Please read out how we create Custom Handle Error filter and use it in application]

18. What is difference between ViewBag and ViewData?


- Both ViewBag and ViewData are used to pass data from controller to view.
- ViewBag is a dynamic property collection Whereas ViewData is key-value pair collection.
- In ViewBag no need to type cast while reading value Whereas In ViewData Need type cast.
- Scope of ViewBag And ViewData is only within single same request.

19. Can we create a View based on 2 different Models? or can we create a Strongly Typed View
based on 2 or more Models?
- Yes, we can create a view based on multiple models.
- There is various way to achieve this.
- We can use ViewBag, ViewData, PartialViews, TempData, ViewModel, Tuple to achieve this
scenario.
- Most preferred way is using ViewModel.

20. What is Routing in MVC?


- Pattern matching System.
- Routing helps to map a requested url to controller action methods.
- We can define multiple patterns for project routing.
- Two Types of Routing:
a) Conventional Based Routing
 We write in [Link] File.
 Common Routing for entire application all Controllers.

b) Attribute Based Routing


 We have more control on routing.
 We use Rout attribute to define attribute-based routing.

MODIFIED BY SHUBHAM LAMBAT


55

21. How to Configure Routing?


- There are 2 different Ways to Configure Routing:
a. We can configure in RouteConfig file.
b. We can use Route attribute to define routing.

22. Is there any other way to Configure Route except adding in RoutConfig file?
- Yes, we can configure routing using Route attribute also.
- We can apply this attribute either on action method or on controller.

23. How can we Create Multiple Routings in RouteConfig file?


- We use MapControllerRoute method and configure more than one routes in [Link] file.
- We have to mandatory provide name and url parameters to MapControllerRoute method.

24. What is Route Attribute?


- Using Route attribute, we can configure routings in MVC application.
- We can use Route attribute on action method or on controller level also.

25. What is ActionResult?


- ActionResult is used to return objects from an action method.
- ActionResult is abstract class which has several derived types like
 ViewResult, ContentResult etc.

26. What are different Action Results in MVC?


- There are around 12 to 13 different types of ActionResults.
- Depending on the returned output we can use any type from these lists.
- Available types are like
 IActionResult
 Action Result
 ViewResult
 PartialViewResult
 ViewComponantResult
 ContentResult
 EmptyResult
 JsonResult
 JavascriptResult
 FileResult
 RedirectToActionResult

27. What is JSON?


- JSON is JavaScript Object Notation.
- Which is lightweight compare to XML.
- If we are calling any service or method through AJAX call then it is good practice to use JSON
to transfer objects.

28. What are Filters and Sequence of execution of those Filters?


- Filters are used to execute logic before and after execution of an action method.
- Filters are broadly categorized in 4 categories –
 Authentication Filter
 Action Filter
 Result Filter
 Exception Filter.

MODIFIED BY SHUBHAM LAMBAT


56

29. How to transfer data from - C to V, V to C, C to C?


- To transfer data from controller to view we can use
 ViewBag, ViewData, TempData, Session variables.
- To transfer data from view to controller we use
 Query string, Hidden fields or form posted values.
- To transfer data from controller to controller we use
 TempData, Session, Cookies.

30. What is AJAX? can you write a Syntax for AJAX Call?
- AJAX is asynchronous JavaScript.
- Using AJAX we can call server code without reloading page.
- Syntax:
$.ajax({
url: , t pe: , data: ,
success:function(){},
error:function(){}
});

31. What is ViewModel?


- ViewModel allows us to create a single entity from one or more different entities using which we
can render more models in a view.
- We can create a strongly typed view based on more than one models.

32. Are there any other ways to Transfer more than one Models to a View?
- Yes. There is various way to achieve this.
- We can use ViewBag, ViewData, PartialViews, TempData, Tuple to achieve this scenario.
- Most preferred way is using ViewModel.

33. How do you Maintain Security in your Project?


- We have used form-based authentication and SSL to provide security in our application.

34. I have one View and that View have one Submit Button, if I click on that Submit Button how
Execution happens in MVC?
- This request will be a post request.
- This request reaches to Routing Engine and based on the parameters it selects an action method of
a controller.
- Controller takes help of model for any business logic or data.
- If action method is returning any view or any other result that will get returned to the client.

35. What is Different Client-Side State Management Techniques?


- In client-side state management techniques we have
 Query string, Hidden field, Cookies.

36. What is ViewBag, ViewData and TempData?


- These are the techniques to manage state of a MVC application.
- ViewBag is a dynamic property collection and
- ViewData is a key value pair dictionary collection
- both are used to pass data from controller to view.
- TempData is a dictionary which can be used in subsequent requests.

MODIFIED BY SHUBHAM LAMBAT


57

[Link] TempData and its Methods?


- TempData is used to store the data and transfer to subsequent requests.
- TempData value is cleared after subsequent requests completes.
- There are Keep and Peek methods which we can use to retain value in TempData after end of
subsequent request also.
- Keep() method preserves the value for next request.
- Peek() method returns TempData value without clearing it from the memory.

38. What are Action Filters?


- Action filters are used to execute any logic pre and post execution of any action methods.
- There are different types of filters available in MVC like AuthorizationFilter, ActionFilter,
ResultFilter and ExceptionFilter.

39. What is Authorize Attribute?


- Authorize attribute is used to implement AuthorizationFilter to any action method.
- Using Authorize attribute we can restrict or allow any user to access the action method.

40. Explain Exception Filter?


- Using ExceptionFilter we can achieve exception handling in MVC.
- There is an attribute called HandleError which we can use to implement error handling which reduces
efforts in writing try catch block in each and every action method.

41. What is MVC? and its Architecture?


- MVC is a architectural pattern to design web applications.
- In MVC, M stands for Model, C stands for Controller and V stands for View.
- Every component has their own responsibilities.
- Model handles business logic and provides data to controller and view.
- View is used to render HTML.
- Controller handles user requests.

42. How you Validate if User Name is Existing in DB or Not?


- There is one attribute called RemoteAttribute in MVC.
- Which we can use to validate if UserName is exists in DB or not.
- RemoteAttribute works with the help of AJAX call.
- It validates the data against database in asynchronous manner without reloading a page.

43. Which Grid you have used to Display Records in MVC?


- We have used [Link] nugget package to display records and used bootstrap to control over its
styling.

[Refer - [Link]
mvc/]

44. What are Attributes?


- Attributes are used to add declarative information to a class or a method.
- In MVC all validations we perform using attributes, all filters are attributes.

45. How you Maintained Session in your MVC project?


- To maintain session, we have used ViewBag, ViewData, TempData, Session variables.
- Depending on scope we have used these options one over another.

MODIFIED BY SHUBHAM LAMBAT


58

46. What is difference between TempData and Session Variable?


- TempData is available only till next subsequent request Whereas Session variable is available till the
session gets expire for that user.
- TempData internally gets stored in session variable.
- To store messages like validation messages or error messages we use TempData Whereas the data
which we want to store for entire lifetime of application then we can use Session variable.

47. Do you know any Aggregate syntax to call AJAX?


- Yes. MVC provides us an aggregate syntax to implement AJAX.
- Using @[Link] we can write ajax call syntax.
- If syntax asked:
@[Link] Link Te t , Action Method , new Aja
Options
{
HttpMethod= GET , OnBegin= , On“uccess=
});

48. What are Security Threats in Application? What is Cross Site Scripting (CSS Attack)?
- Security threats means a way to access our application by any anonymous user to perform any
unauthorized activities which can harm to application data.
- There are lot of security threats and there are ways to prevent them.
- Cross Site Scripting attack is an attack where a user can inject any script through textbox or textarea
and he can execute those unwanted scripts.
- We can prevent XSS attack by giving proper validations against these input fields.

49. What is Anti Forgery Token?


- AntiForgeryToken validates a POST request
- if it is coming from the same user or not.
- Using AntiForgeryToken we can prevent Cross Site Request Forgery attack.

50. Do you know Unit Testing?


- Yes. I know unit testing I have used nUnit framework to perform unit testing for modules in my
project.

51. If I have one View which has a Button and a Div Tag. I have created a Partial View. Now on
click on that Button this Partial View should get rendered in Div Tag. Tell me Flow how will you
Write Code for This.
- I will write an AJAX call to implement this.
- I can achieve this in 2 ways writing an JQuery AJAX call or using MVC AJAX helper method.
- Firstly, I will write an action method which returns me partial view.
- Then on the main view I will call this action method using [Link] method
- and I will set UpdateTargetId parameter to div id.

52. How View Model Works? If I have to show 3 Models on single View, how will you Achieve that.
- Using ViewModels we can create a strongly typed view based on multiple models.
- I will create a view model and I will write all required models as properties inside this class.
- I will create a strongly typed view based on this ViewModel.

53. How Partial View get Rendered on Main View?


- There are various ways to render a partial view on main view.
- We can use Partial, RenderPartial or RenderAction methods to render partial view on main view.

MODIFIED BY SHUBHAM LAMBAT


59

54. Suppose I have 2 Buttons on a View let’s say Add and Clear.
Then how will you write Events and Identify that which Button is Clicked?
- I will use jQuery selectors to write events for these two buttons.
- If required write action methods and I will call those action methods using AJAX call.

55. Let’s say I want to Display 1000 Records on my Site. How will you Show that?
- I will implement pagination to show 1000 of records on a page.
- In MVC we can use PagedList package to achieve pagination functionality.

56. How the State is Maintained in MVC?


- There are 2 different techniques to maintain states in MVC.
- We can use HiddenFields, Cookies, QueryString which are client-side techniques.
- We can use ViewBag, ViewData, TempData, Session, Application and Cache variables which are
server-side techniques.

[Link] is Razor Engine?


- Razor engine is introduced with MVC.
- Using Razor engine, we can create views like cshtml or vbhtml.
- Where in we can write both html and C# code.
- If we want to switch from html to C# code we just have to use @ symbol and we can start writing C#
code.
- Apart from this their helper methods which helps us to create html controls.

58. What is Attribute Routing?


- Attribute routing is a new feature introduced with MVC5.
- Where we can use Route attribute to define routings for our application.
- Before Route attribute we used to define convention-based routings in [Link] file.
- We can use Route attribute on controller or action method levels.

59. What are Partial Views and their Use?


- Partial views are used to write re-usable views.
- Which can minimize the complexity of views.
- We can create a partial view and we can use it on multiple views.

60. Can one Partial View called from Another Partial View?
- Yes, one partial view can call another partial view.

61. What is GET and POST Request?


- These are the type of requests which user can perform against our application.
- In general, if user is requesting to retrieve some data, we refer this method as GET request.
- By default, the initial request is a get request.
- If a user wants to post some data to server, we consider this request as POST request.
- There are HttpVerbs which we use to define type of request.

62. Can One View has 2 Submit Buttons?


- Yes, one view can have two submit buttons.
- On clicking on those submit button respective action methods are called.
- Which are defined with form tag.

MODIFIED BY SHUBHAM LAMBAT


60

63. What is difference between ActionResult and ViewResult?


- ActionResult is base type for all result classes Whereas ViewResult is one implementation of
ActionResult.
- We can return any data from an action method with ActionResult.
- If we want to return a view from action method, I can use both ViewResult.

64. Where we do Validations in MVC?


- We do all validations in models using validation attributes.
- All validation specific attributes are define in [Link].

65. What is ModelBinder in MVC?


- ModelBinder helps to bind posted values to an action method model.
- ModelBinders take the data from Value Providers to create an object.
- There are various value providers like FormValueProvider, QueryStringProvider,
JsonValueProvider.

66. Have you Used Cookies in your Project?


- Yes, we have used cookies to store some non-critical data of user which we had to use in multiple
pages.

67. If you use Area then how the URL is Displayed?


- By default, our URL is like domain/controller/action.
- But with area the URL is changes to domain/areaname/controller/action.

68. Which Control you have used to Display Images in your Project?
- We have created custom helper class to display images in our application.

69. Can I call more than one Action Methods at Same Time in MVC?
- Yes, we can call more than one action methods at same time.
- We can write to action methods which are returning me a partial view.
- Then I can use RenderAction method on main view which will call all respective action methods.

70. Can we Write Multiple Paths in RouteConfig file?


- Yes. We can define multiple routings in RouteConfig file.
- We have to make sure while giving name parameter.
- Because name should be different for all defined routings.

[Link] is Difference between Partial and RenderPartial?


- Both the methods are used to render partial view on main view.
- Partial method returns MvcHtmlString whereas RenderPartial method returns void.
- If we want to make some changes in partial view response then we can use Partial method or else
we can use RenderPartial method.
- RenderPartial method performs better because it directly renders response to output stream.

72. What is RenderAction method? When it is used?


- RenderAction method used to render partial view on main view.
- If there is an action method which is returning a partial view then
- I can use RenderAction method to call that action method to render partial view on main view.

MODIFIED BY SHUBHAM LAMBAT


61

73. What is Purpose of OutputCache Filter?


- OutputCache attribute is used to implement caching in MVC.
- If we want to perform page level or fragment level caching we can use OutputCache attribute with
appropriate action methods.
- It is somewhat similar to OutputCache directive in [Link]

74. What is HandleError Attribute?


- Using HandleError attribute we can do error handling in MVC application.
- Instead of writing try catch block in each and every action method we can use HandleError
attribute to achieve error handling.

75. What will happen if I have used HandleError Attribute and Try Catch block both in an
Action Method?
- It will not give me any compile time error
- But the error will be handled by Catch block in that case.

76. I have 2 Dropdown lists one is for State and other for City.
If I select State all Cities get shown in City dropdown list. How will write Code for this.
- I will create a ViewModel which will have List of State and City properties.
- I will add action method to controller and retrieve data for states from model.
- For this action method I will add a strongly typed view using ViewModel.
- On this View I will 2 dropdown list with the help of html helpers.
- Initially I will disable city dropdown list.
- I will add onchange method to state dropdown list.
- If user change state, then I will write AJAX call to fetch and bind city data to city dropdown list.

77. I have a Textbox, Button and Label on a Page. If you Click on Button, entered text should
be Displayed on Label. Write a code for this.
- I will write an action method with parameter name same as textbox name.
- Then I will make a AJAX call to action method on click of button.
- OnSuccess event I will bind response to label.
- If we don’t have to hit to server then we can easily achieve this functionality using javascript code
writing a simple javascript function or jQuery selector and event.

78. How to Overload Action Methods? [This question can be asked with 2 Action Methods]
- I will use ActionName attribute where I will give same name which is used to make a request to that
action method and while writing actual method name, I will write different name there.
- So, both methods can be called with same request with different request type.

79. What are different Types of Authentications?


- There are 3 different types of authentications
 Windows Authentication
 Forms Authentication and
 Passport Authentication.
- We have used Forms Authentication in our project.
- A login page where user can provide credentials to validate.

80. What is Bundling and Minification?


- Bundling and minification are techniques to improve performance of web site.
- Basically, if we have multiple JavaScript files, CSS files calls on a page then we can club them using
bundling to make a single request for multiple files.

MODIFIED BY SHUBHAM LAMBAT


62

- On other hand minification is process of compressing JS or CSS files


- Which actually does 3 things it removes all comments, it removes all new lines and blank spaces and
it shorthand the names of variables and methods.
- Which reduces the file size.

81. How to Return Empty String from an Action Method?


- We can use EmptyResult to return empty value from an action method.

82. How to Return String from an Action Method?


- We can use ContentResult to return a string from an action method.

83. What is Layout in MVC? what is Purpose of Layouts?


- Layouts in MVC is very similar to Master pages in [Link].
- Using Layouts, we can maintain consistent look and feel of any website.
- We can have multiple layouts in a single application.
- And we can include them on a view based on any condition.

84. Can we have More than one Layouts in MVC? How will you Assign them to Views in case
of Multiple Layouts?
- Yes, we can have more than one layout in single application.
- We can assign them on view through ViewStart file or we can assign them on individual views also.
- We can give any condition to check for assigning layout to any view.

85. I want to Prevent Action Method to be called with URL?


- If we have written any action method which is public and we want to restrict it to call with an URL
then we can mark that method as ChildActionOnly attribute.
- NoAction Attribute.
- This method will not be called from browser but we can call it as child request.
- We can make a call to this action method using Action() or RenderAction() methods.

86. I have a Textbox, I want to Restrict its Character Limit to 10 Characters? How you achieve?
- We can use StringLength attribute on model property to do this type of validation.

87. I have a Textbox, I want to Allow a user to Enter their Valid Date? How can I Validate it?
- We can use DataType attribute on that field to do this validation.
- We can specify [Link] to this attribute as parameter.

88. How to Consume Bootstrap in MVC Application?


- We can include all bootstrap files like [Link], [Link] and [Link] on our layout view
using CDN or we can download and refer them.
- Then we can set bootstrap classes to any controls with our helper methods using htmlAttributes
property.

89. What is Difference between MVC 4 and MVC 5?


- In MVC 4 new features introduced like WEBAPI, Bundling and Minification support, support
for adding controllers to other folders also.
- In MVC 5, built in support for bootstrap, attribute-based routing, [Link] identity.

90. Do You Have Experience of Deployment?


- Yes, I have experience deploying application using IIS.
- I have deployed application on my local machine & on development server using IIS

MODIFIED BY SHUBHAM LAMBAT


63

91. Repository Pattern?


- There Are different layer is use
o Data Layer
o Repository Layer
o Service Layer
o UI Layer

92. How do validation in MVC?


- Model Side use data annotation or validation Attribute
- For Client-Side Validation
o [Link]
o [Link]
- For Server Side Validation
o [Required]
o [StringLength]
o [EmailAddress]
o [Range]
o [RequiredExpression]
o [DataType]
o [Display]

93. What Are method to Implement Custom Filter?


- IFilterMetadata Interface
- ActionFilterAttribute

94. What is [Link] & [Link]


- [Link] is use to handle the request when one request work is done then it can give that request to
another.
- [Link]: program start to run the application.

95. Managed Code


- The Code which run under the environment of CLR (Common Language Runtime).
- And it will remove Garbage Code.

96. Unmanaged Code


- Not run in under CLR.
- Destructor call Finalize method and this method remove Unmanaged Code.
- Dispose Method also we use.

97. How to register Filter Globally?


- In [Link] we can register.
- [Link] (option => [Link]
{
typeOf(globalFIlter)
})

98. Where Error Log do.


- We can do in Siri log file.
- It is third party service.
- We can store in text format.

MODIFIED BY SHUBHAM LAMBAT


64

99. What is Hosting?


- Process of deploying application onto the process.

100. Stages of Deployment?


- Planning
- Development
- Testing
- Deploying
- Monitoring

101. What is Resource Filter?


- It can be use for handling resource and help to short circuit request execution pipeline if required.
- In this caching is used.
- Ex:
Public class custom resourceFilter : IResourceFilter
{
Public void onResourceExecuting()
{
// logic to perform execution
}
Public void onResourceExecuted()
{
// logic to perform execution
}
}

102. What is IIS?


- Internet Information Service.
- It is simply redirecting request to kestrel server
- No need to install it separately, we get IIS installed with windows machine.
- IIS is use to host/deploy application like dot net, java, angular, web api etc.
- It is not responsible for running dot net core application.
- To Enable IIS
o Turn windows feature ON/OFF
o Check IIS option & save.
- To Host application in IIS
o Publish Code
o Host in IIS
o For hosting we need to install Hosting Bundle.
- Default Port Number
o http – 80
o https – 443
- Application Pool
o Provide identity to run the application.
o By Default Identity:
 LocalService
 LocalSystem
 NetworkService
 ApplicationPoolIdentity
 It Create a new Identity for application by application Name.

MODIFIED BY SHUBHAM LAMBAT


65

[Link]
1. What is [Link]?
 [Link] stands Microsoft ActiveX Data Objects.
 [Link] is a set classes that can be used to interact with data sources like
database and XML.
 [Link] we use for database Communication.
 Database can be anything like SQL, Oracle, Ms Access, Excel, etc.

2. What are the Classes used in [Link]?


 SqlConnection
 SqlCommand
 SqlDataReader
 SqlDataAdapter
 Dataset

3. What are the Steps to Communicate Database using [Link]?


 Preparing Connection String
 Open Connection
 Preparing Command / Query
 Execute the Command
 Retrieve / Copying the Results
 Display in the Application

4. What is SqlCommand?
 To Prepare & Execute Command.
 SqlCommand class is used to prepare an SQL statement or Store Procedure that we
want to execute on SQL server database.
 There are three methods of SqlCommand class which are commonly used:
a) ExecuteScalar : Used when query returns single value.
b) ExecuteReader : Used when query returns more than one value.
c) ExecuteNonScalar : Used when we want to perform an Insert, Update or
Delete operations.

5. What is SqlDataReader?
 SqlDataReader reads data in the most efficient manner.
 SqlDataReader is connection-oriented means it requires an active and open
connection to the data source while reading the data.

6. What is SqlDataAdapter and Dataset?


 Dataset :-
 Dataset provides us disconnected Oriented data access model
 In memory collection object.
 Dataset is the collection of DataTables
 DataTables is a collection of Datarows.
 Also, DataTables is a combination of Colum & Rows.
 Fill() method opens connection to the database, executes SQL command, fills data in the
dataset and closes the connection.

 SqlDataAdapter :-
 SqlDataAdapter provides us disconnected Oriented data access model.
 It does not required connection Open or Close explicitly.

MODIFIED BY SHUBHAM LAMBAT


66

7. What is use SqlBulkCopy class?


 SqlBulkCopy class is used to copy data from different data source into SQL server
database.
 Using SqlBulkCopy we can load XML data to SQL server.

8. What is SQL injection?


 SQL injection is an attack where user can inject any script through textbox and
execute those unwanted scripts which harms our database.
 To prevent SQL injection we can use parametrized queries or store procedures.

MODIFIED BY SHUBHAM LAMBAT


67

ENTITY Framework
1. Entity Framework and its Approaches?
 Entity framework is used to communicate with the database.
 Entity Framework approaches are
1) Database First
- Database first approach creates the entity framework from an existing
database.
2) Code First
- Code first approach create database that doesn’t exists.
- It can also be used if you have an empty database and then code first will add new
tables too.
3) Model First

2. Which Approach you have Used in your Project and Explain it?
 We used Database first approaches as per requirement.

3. What is Difference between [Link] and Entity Framework?


 [Link] creates bunch of data layer code whereas Entity Framework doesn’t create
bunch of code.
 [Link] is faster than entity framework because entity framework uses [Link] code
behind so entity framework requires some extra time cost.
 In [Link] we need to write so much of code Whereas in Entity Farmwork we don’t
need to write so much of code.
 [Link] Performance is better than Entity Framework.

4. What is DbContext?
 DbContext is an important class in entity framework.
 DbContext is a bridge between entity classes and database.
 DbContext is the primary class that is responsible for interacting with the database.
 DbContextSavechanges method executes Insert, Update and Delete commands to the
database.

5. What is Dbset?
 The context class derived from DbContext must include the Dbset type properties for
the entities which maps the database table and views.

MODIFIED BY SHUBHAM LAMBAT


68

WEB API
1. What is Web API?
 Web API is framework which used to develop http restful services.
 Web API is service where we can write code once and consume it in any application.
 In our Web API project, we wrote business logic and consume it in MVC application.

2. What are Differences between Web API and WCF?


 Both are used create restful services but Web API is lightweight as compared to WCF.
 Because in WCF we need lot of config settings and complicated for developing restful
services.

3. Web API is replacement for WCF?


 No, Web API is another way of develop non-SOAP based services.
 i.e. plain XML or JSON string.

4. What is Protocol?
 Protocol means guidelines or rules to communicate over internet.
 Ex. http - Internet
tcp - Intranet (Communicate with LAN)
namedpipe – Used when same server
msmq - To maintain que

5. What is Serialization and Deserialization?


 Serialization means converting dot net object into any message format.
 Deserialization means converting any message format into dot net object.

6. What is Difference between SOAP and REST?


 SOAP means Simple Object Access Protocol Whereas REST means
Representational State Transfer.
 SOAP only uses XML data format Whereas REST uses many data formats including
Plain Text, HTML, XML and JSON.

7. What are Main Return Types Supported in Web API?


 Void – It will return empty content.
 HttpResponseMessage – It will convert the response into an Http message.
 IHttpActionResult – It internally calls ExecuteAsync to create an HttpResponseMessage.

8. Web API Supports which Protocol?


 Web App supports HTTP protocol.

9. Which .NET Framework supports Web API?


 NET 4.0 and above version supports web API.

10. Web API uses which of the following Open-Source Library for JSON Serialization?
 Web API uses [Link] library for JSON serialization.

11. What is Web API Routing?


 Routing is pattern matching like in MVC.
 All routes are registered in Route Tables.
 Domain/Api/Controller

MODIFIED BY SHUBHAM LAMBAT


69

12. How can you Handle Errors in Web API?


 Several classes are available in Web API to handle errors like:

 HttpError
 Exception Filters
 HttpResponseException
 Registering Exception Filters.

13. How can you Pass Multiple Complex Types in Web API?
 Two methods to pass the complex types in Web API –
 Using ArrayList and Newtonsoft array.

14. How to Test Web API?


 We can use third party tools for testing Web API.
a) Fiddler
b) Postman
c) Swagger UI

15. What are the HTTP Verbs/Methods in Web API?


 Get – Retrieves data
 Post – Insert new record
 Put – Update existing record
 Patch – Update records partially
 Delete – Delete records

16. What is Difference between Web API and MVC?


 Web API derives from [Link] whereas MVC derives from
[Link]
 In Web API method name must start with Http verbs otherwise apply http verbs
attribute whereas in MVC must apply appropriate Http verbs attribute.
 Web API specialized in returning data whereas MVC specialized in rendering view.

17. What is Request/Response Data Formats?


 Accept – The accept header attribute specifies the format of response data.
 Content-Type – The content-type header attribute specifies the format of request data.

18. How to Consume Web API in MVC?


 To consume Web API in MVC we can use HttpClient class in MVC controller.
 HttpClient sends a request to the Web API and receives a response.
 Then we can convert response data to a model and then render it on a view.

19. How to Authenticate User in Web API?


 There various ways to authenticate user in Web API.
 We used JWT token-based authentication in Web API.
 JWT – means Jason Web Token

20. How does JWT Authentication Work?


 The server generates a token that certifies the user identity and sends it to the client.
 The client will send the token back to the server for every subsequent request.
 So, the server knows, the request comes from particular identity.

MODIFIED BY SHUBHAM LAMBAT


70

21. What is Difference between Synchronous and Asynchronous Request in AJAX?


 In synchronous request, the working of a page and user interaction is blocked until a
response is received from the server.
 In an asynchronous request, the page continues to work normally without blocking the
user means that the user need not wait until the server replies. It is the most preferred
way of sending a request.

22. How to make AJAX Synchronous?


 In AJAX, there is flag called async and setting it false will make AJAX
request synchronous.

23. What is Open Authentication (OAuth)?


 Open authentication is a type of token authentication it allows an end users account
information used by third party services.
 Such as Facebook without exposing user’s username and password.

24. What is Content Negotiation


 Media Type Format
 Also called Communication Msg Format
 Ex. Json, XML.

25. What is CORS?


 If we want to give access of our Domain To another Domain then we use CORS
 CORS means Cross Origin Resource Sharing.
 We add Nugget Package [Link]
 We can register service in [Link] file.

MODIFIED BY SHUBHAM LAMBAT


71

UNIT Testing
1. What Is Unit Testing?
- Testing is a process to where each unit or component of an application is tested to determine
whether it is fit to use or not
- A single unit is any block of code either method or a class that has one responsibility
- A C# method can have multiple unit tests according to its uses and different outputs of that
method

2. Types of UNIT Testing?


- Unit Testing
o All test methods are written by developers
- Integration Testing
o All developers are working on different tasks, this testing helps every developers to test
their code whether it stills works on code collaboration
- System Testing
o It is done by testers and QA within team
o There are several testing QA does to test entire functionalities implemented for
application
o Example -> Smoke testing, Sanity testing, Regression testing, Load testing, etc.
- Acceptance Testing
o It is done by Business Analyst/ Product Owner and Customers who are actually going to
use the application

3. Advantages of Unit Testing


- Improves code quality
- Faster Development
- Faster Debugging
- Better Design
- Reduce Future Code
- Reduces the number of defects by testing team

4. What is Unit Testing Frameworks


- There are several unit testing frameworks available to test dot net based applications
- It simply the process of unit testing
- Enable the creation of test classes with specific attributes which enables them to picked up by a
test runner
- Unit testing without testing framework is difficult and quite complicated
- Popular testing frameworks in dot net
 MS Test (By Microsoft)
 NUnit (By community)
 xUnit (By community)
- Test Runners
 A test runner is a library or a tool used to executes unit tests in source code directory
 It writes test results to the console or log files
- Three components involved in unit testing
 Source Code (classes & methods)
 Testing framework (apply attributes & use asserts)
 Test Runner (run tests & generates testing statistics)
- All testing frameworks have their own test runners

MODIFIED BY SHUBHAM LAMBAT


72

5. What Is nUnit Testing Framework


- An open source unit testing framework for .NET
- It is written in C# language
- Extensible & Flexible
- Platform independent
- Integration with third party tools like NCover, JetBrains etc.
- Example:
o In NUnit Test we use [TestFixture] attribute over test class and [Test] attribute over all
test methods

6. xUnit Testing Framework


- An open source testing platform with a larger focus on extensibility and flexibility
- Developed by NUnit team based on standard of NUnit framework
- xUnit refers to a grouping of frameworks, but we will be focusing on the Dot Net Version
- It is used by Microsoft in Roslyn (C# compiler), CoreFx, etc
- Example:
o In xUnit Test, no need to specify any attribute over test class but we need to use [Fact]
attribute over all test methods

7. MS Test Vs NUnit Vs xUnit


- Attribute over test class
 NUnit -> [TestFixture]
 MS Test -> [TestClass]
 xUnit -> N/A

- Attibute over test method


 NUnit -> [Test]
 MS Test -> [TestMethod]
 xUnit -> [Fact]

- Any setup needed before running every test methods


 NUnit -> [SetUp]
 MS Test -> [TestInitialize]
 xUnit -> Constructor

- Any setup needed after running every test methods


 NUnit -> [TearDown]
 MS Test -> [TestCleanup]
 xUnit -> [Link]
- One time setup needed before running test methods
 NUnit -> [OneTimeSetUp]
 MS Test -> [ClassInitialize]
 xUnit -> IClassFixture<T>

- One time setup needed after running test methods


 NUnit -> [OneTimeTearDown]
 MS Test -> [ClassCleaup]
 xUnit -> IClassFixture<T>

MODIFIED BY SHUBHAM LAMBAT


73

- To ignore any written test method


 NUnit -> [Ignore(“reason”)]
 MS Test -> [Ignore]
 xUnit -> [Fact(Skip=”reason”)]

- To configure data driven test


 NUnit -> [Theory]
 MS Test -> [DataRow]
 xUnit -> [Theory]

8. Bundling & Minification


- Bundling is a process to create bundles of multiple js or css files
- It helps to reduce number of requests of browser and helps to improve performance

MODIFIED BY SHUBHAM LAMBAT


74

ANGULAR
1. What is Angular? Why was it Introduced?
- Angular was introduced to create Single Page applications.
- It is a front-end framework to develop web application or mobile application.
- This framework brings structure and consistency to web applications
- Provides excellent scalability and maintainability.
- Angular is an open-source, JavaScript framework wholly written in TypeScript.
- It uses HTML's syntax to express your application's components clearly.

2. What is TypeScript?
- TypeScript is a superset of JavaScript that offers excellent consistency.
- Developed by Microsoft, its first version released in 2012.
- TypeScript code compiles down to JavaScript that can run efficiently in any environment.
- TypeScript contains all features of JavaScript along with its own feature.
- Today Typescript is used as a main language for front end frameworks like Angular, React, VueJS.
- Typescript is free and open-source programming language
- Typescript is Object Oriented Programming language which supports type safety, data types,
classes, interfaces, inheritance, modules etc.

3. What is Data Binding? Which type of Data Binding does Angular Deploy?
- Data binding is the way to communicate between your typescript code of your component
and your HTML view.

- Angular uses the two-way binding.


- Any changes made to the user interface are reflected in the corresponding model state.
- This allows the framework to connect the DOM to the Model data via the controller.
- However, this approach affects performance since every change in the DOM has to be tracked.

4. What are Single Page Applications (SPA)?


- Single-page applications are web applications that load once with new features just being mere
additions to the user interface.
- It does not load new HTML pages to display the new page's content, instead generated dynamically.
- This is made possible through JavaScript's ability to manipulate the DOM elements on the existing
page itself.
- A SPA approach is faster, thus providing a seamless user experience.

5. What are Decorators in Angular?


- Decorators are a design pattern or functions that define how Angular features work.
- They are used to make prior modifications to a class, service, or filter.
- Angular supports four types of decorators, they are:
1. Class Decorators
2. Property Decorators
3. Method Decorators
4. Parameter Decorators

MODIFIED BY SHUBHAM LAMBAT


75

6. Differentiate between Angular and AngularJS


- The following table depicts the aspects of Angular vs AngularJS in detail:

Feature AngularJS Angular

Language JavaScript TypeScript That’s Why it Is Faster

Architecture Supports Model-View-Controller design Uses components and directives

Mobile support Not supported by mobile browsers Supports all popular mobile browsers

Dependency
Doesn’t support Supports
Injection

@routeProvider is used to provide @Route configuration is used to define


Routing
routing information routing information

Difficult to manage with an increase in Better structured, easy to create and manage
Management
source code size bigger applications

7. Mention some Advantages of Angular.


Some of the common advantages of Angular are -
 MVC architecture –
o Angular is a full-fledged MVC framework.
o It provides a firm opinion on how the application should be structured.
o It also offers bi-directional data flow and updates the real DOM.
 Modules:
o Angular consists of different design patterns like components, directives, pipes, and
services, which help in the smooth creation of applications.
 Dependency injection:
o Components dependent on other components can be easily worked around using this
feature.
 Other generic advantages include clean and maintainable code, unit testing, reusable components,
data binding, and excellent responsive experience.

8. What are Templates in Angular?


- Angular Templates are written with HTML that contains Angular-specific elements and attributes.
- In combination with the model and controller's information, these templates are further rendered to
provide a dynamic view to the user.

9. What are Annotations in Angular?


- Annotations in Angular are used for creating an annotation array.
- They are the metadata set on the class that is used to reflect the Metadata library.

MODIFIED BY SHUBHAM LAMBAT


76

10. What are Directives in Angular?


- Directives are attributes that allow the user to write new HTML syntax specific to their applications.
- They execute whenever the Angular compiler finds them in the DOM.
- Using Directive we can create custom HTML tag, Attributes Class.
- Angular supports three types of directives.
1. Structural Directives:
o Control DOM structure
o Ex: *ngIf, *ngFor, *ngSwitch
2. Attribute Directives:
o Which target styling o HTML element
o Ex: ngModel, ngStyle, ngClass
3. Component Directives
o Component Directives are Directive with its own template

11. What is an AOT compilation? What are its advantages?


- The Ahead-of-time (AOT) compiler converts the Angular HTML and TypeScript code into
JavaScript code during the build phase,
- i.e., before the browser downloads and runs the code.
Some of its advantages are as follows.
1. Faster rendering
2. Fewer asynchronous requests
3. Smaller Angular framework download size
4. Quick detection of template errors
5. Better security

12. What are Components in Angular?

- We create component based on pages / Functionalities needed to developed application.


- We can create component manually, it takes same time.
- Command to generate Component.
o Ng g c com-name
- Components are the basic building blocks of the user interface in an Angular application.
- Every component is associated with a template and is a subset of directives.
- An Angular application typically consists of a root component, which is the AppComponent, that
then branches out into other components creating a hierarchy.

13. What are Pipes in Angular?

- To format the data before rendering on browser.


- Pipes are simple functions designed to accept an input value, process, and return as an output, a
transformed value in a more technical understanding.
- Angular supports several built-in pipes.
- However, you can also create custom pipes that cater to your needs.

MODIFIED BY SHUBHAM LAMBAT


77

- Some key features include:


1. Pipes are defined using the pipe “|” symbol.
2. Pipes can be chained with other pipes.
3. Pipes can be provided with arguments by using the colon (:) sign.

- Built in pipes
a. uppercase
b. lowercase
c. titlecase
d. currency
e. date
f. number/ decimal
g. json

- Custom Pipe

14. What is an ngModule?


- NgModules are containers that reserve a block of code to an application domain or a workflow.
- @NgModule takes a metadata object that generally describes the way to compile the template of a
component and to generate an injector at runtime.
- In addition, it identifies the module's components, directives, and pipes, making some of them
public, through the export property so that external components can use them.

15. What are Filters in Angular? Name a few of them.


- Filters are used to format an expression and present it to the user.
- They can be used in view templates, controllers, or services.
- Some inbuilt filters are as follows.
 date - Format a date to a specified format.
 filter - Select a subset of items from an array.
 Json - Format an object to a JSON string.
 limitTo - Limits an array/string, into a specified number of elements/characters.
 lowercase - Format a string to lowercase.

16. What is View Encapsulation in Angular?


- View encapsulation defines whether the template and styles defined within the component can
affect the whole application or vice versa.
- Angular provides three encapsulation strategies:
 Emulated - styles from the main HTML propagate to the component.
 Native - styles from the main HTML do not propagate to the component.
 None - styles from the component propagate back to the main HTML and therefore are visible
to all components on the page.

17. What are Controllers?


- AngularJS controllers control the data of AngularJS applications.
- They are regular JavaScript Objects.
- The ng-controller directive defines the application controller.

18. Explain the Lifecycle Hooks in Angular


- In Angular, every component has a lifecycle.
- A component from creation to destruction goes through several stage and this stages are
the life cycle hooks.
- Here's the list of them –

MODIFIED BY SHUBHAM LAMBAT


78

1. ngOnChanges() - Responds when Angular sets/resets data-bound input properties.


2. ngOnInit() - Initialize the directive/component after Angular first displays the data-bound
properties and sets the directive/component's input properties/
3. ngDoCheck() - Detect and act upon changes that Angular can't or won't detect on its own.
4. ngAfterContentInit() - Responds after Angular projects external content into the component's
view.
5. ngAfterContentChecked() - Respond after Angular checks the content projected into the
component.
6. ngAfterViewInit() - Respond after Angular initializes the component's views and child views.
7. ngAfterViewChecked() - Respond after Angular checks the component's views and child
views.
8. ngOnDestroy - Cleanup just before Angular destroys the directive/component.

19. What is String Interpolation in Angular?


- String Interpolation is a one-way data-binding technique that outputs the data from TypeScript code
to HTML view.
- It is denoted using double curly braces.
- This template expression helps display the data from the component to the view.
- Ex: - {{ data }}

20. What are Services in Angular?


- Angular Services perform tasks that are used by multiple components.
- These tasks could be data and image fetching, network connections, and database management
among others.
- A Service is a typescript class and a reusable code which can be use in multiple components
- Service can be implemented with help of Dependency Injection.
- A service can be written once and injected into all the components that use that service.

21. What is ngOnInit? How is it defined?


- ngOnInit is a lifecycle hook and a callback method that is run by Angular to indicate that a
component has been created.
- It takes no parameters and returns a void type.
export class MyComponent implements OnInit
{
constructor() { }
ngOnInit(): void {
//.... } }
22. What are Promises and Observables in Angular?
- While both the concepts deal with Asynchronous events in Angular, Promises handle one such
event at a time while observables handle a sequence of events over some time.

o Promises –
 They emit a single value at a time.
 execute immediately after creation and are not cancellable.
 They are Push errors to the child promises.

MODIFIED BY SHUBHAM LAMBAT


79

o Observables –
 They are only executed when subscribed to them using the subscribe() method.
 They emit multiple values over a period of time.
 They help perform operations like forEach, filter, and retry, among others.
 They deliver errors to the subscribers.
 When the unsubscribe() method is called, the listener stops receiving further values.

23. How to use ngFor in a Tag?


- The ngFor directive is used to build lists and tables in the HTML templates.
- In simple terms, this directive is used to iterate over an array or an object and create a template for
each element.
- Ex:
<ul>
<li *ngFor = "let items in itemlist"> {{ item }} </li>
</ul>

- “Let item” creates a local variable that will be available in the template
- “Of items” indicates that we are iterating over the items iterable.
- The * before ngFor creates a parent template.

24. What are Template and Reactive forms?


Template-driven approach
 In this method, the conventional form tag is used to create forms.
 Angular automatically interprets and creates a form object representation for the tag.
 Controls can be added to the form using the NGModel tag.
 Multiple controls can be grouped using the NGControlGroup module.
 A form value can be generated using the “[Link]” object.
 Form data is exported as JSON values when the submit method is called.
 Basic HTML validations can be used to validate the form fields.
 In the case of custom validations, directives can be used.
 Arguably, this method is the simplest way to create an Angular App.

Reactive Form Approach


 This approach is the programming paradigm oriented around data flows and propagation of
change.
 With Reactive forms, the component directly manages the data flows between the form controls
and the data models.
 Reactive forms are code-driven, unlike the template-driven approach.
 Reactive forms break from the traditional declarative approach.
 Reactive forms eliminate the anti-pattern of updating the data model via two-way data binding.
 Typically, Reactive form control creation is synchronous and can be unit tested with
synchronous programming techniques.

25. What is Bootstrap? How is it Embedded into Angular?


- Bootstrap is a powerful toolkit.
- It is a collection of HTML, CSS, and JavaScript tools for creating and building responsive web
pages and web applications.
- There are two ways to embed the bootstrap library into your application.

1. Angular Bootstrap via CDN –


o Bootstrap CDN is a public Content Delivery Network.
o It enables you to load the CSS and JavaScript files remotely from its servers.

MODIFIED BY SHUBHAM LAMBAT


80

2. Angular Bootstrap via NPM –


o Another way to add Bootstrap to your Angular project is to install it into your project folder
by using NPM (Node Package Manager).
o npm install bootstrap
o npm install jquery

26. What is Eager and Lazy loading?


- Eager loading is the default module-loading strategy.
- Feature modules under Eager loading are loaded before the application starts.
- This is typically used for small size applications.

- Lazy loading dynamically loads the feature modules when there's a demand.
- This makes the application faster.
- It is used for bigger applications where all the modules are not required at the start of the
application.

27. What type of DOM does Angular implement?


- DOM (Document Object Model) treats an XML or HTML document as a tree structure in which
each node is an object representing a part of the document.
- Angular uses the regular DOM.
- This updates the entire tree structure of HTML tags until it reaches the data to be updated.
- However, to ensure that the speed and performance are not affected, Angular implements Change
Detection.
- With this, you have reached the end of the article.
- We highly recommend brushing up on the core concepts for an interview.
- It’s always an added advantage to write the code in places necessary.

28. Why were Client-Side Frameworks like Angular Introduced?


- Client-side frameworks like Angular were introduced to provide a more responsive user experience.
- By using a framework, developers can create web applications that are more interactive and
therefore provide a better user experience.
- Frameworks like Angular also make it easier for developers to create single-page applications
(SPAs).
- SPAs are web applications that only need to load a single HTML page.
- This makes them much faster and more responsive than traditional web applications.
- Overall, client-side frameworks like Angular were introduced in order to improve the user
experience of web applications.
- By making web applications more responsive and easier to develop, they provide a better
experience for both developers and users.

29. How does an Angular Application Work?


- An Angular application is a Single Page Application, or SPA.
- This means that the entire application lives within a single page, and all of the resources (HTML,
CSS, JavaScript, etc.) are loaded when the page is first loaded.
- Angular uses the Model-View-Controller, or MVC, architecture pattern to manage its data and
views.
- The Model is the data that the application uses, the View is what the user sees, and the Controller
is responsible for managing communication between the Model and the View.
- When a user interacts with an Angular application, the Angular framework will automatically
update the View to reflect any changes in the data.
- This means that Angular applications are very responsive and fast, as the user does not need to wait
for the page to reload in order to see updated data.

MODIFIED BY SHUBHAM LAMBAT


81

- Angular applications are also very scalable, as they can be divided into small modules that can be
loaded independently of each other.
- This means that an Angular application can be easily extended with new functionality without
having to rewrite the entire application.
- Overall, Angular applications are very fast, responsive, and scalable.
- They are easy to develop and extend, and provide a great user experience.

30. Explain Components, Modules and Services in Angular.


- Components, modules and services are the three fundamental building blocks in Angular.
- Components are the smallest, self-contained units in an Angular application.
- They are typically used to represent a view or UI element, such as a button or a form input field.
- Modules are larger units that group together one or more related components.
- Services are singleton objects that provide specific functionality throughout an Angular application,
such as data access or logging. Each component in Angular has its own isolated scope.
- This means that a component's dependencies (services, other components, etc.) are not accessible
to any other component outside of its own scope.
- This isolation is important for ensuring modularity and flexibility in an Angular application.
- Services, on the other hand, are not isolated and can be injected into any other unit in an Angular
application (component, module, service, etc.).
- This makes them ideal for sharing data or functionality across the entire app.
- When designing an Angular application, it is important to keep these three building blocks in mind.
- Components should be small and self-contained, modules should group together related
components, and services should provide shared functionality across the entire app.
- By following this design principle, you can create an Angular application that is modular, flexible,
and easy to maintain.

31. How are Angular Expressions different from JavaScript Expressions?


- One major difference between Angular expressions and JavaScript expressions is that Angular
expressions are compiled while JavaScript expressions are not.
- This means that Angular expressions are more efficient since they're already pre-processed.
- Additionally, Angular expressions can access scope properties while JavaScript expressions cannot.
- Finally, Angular expressions support some additional features such as filters and directives which
aren't available in JavaScript expressions.

32. How do you Share data between Components in Angular?


- Sharing data between components in Angular is simple and easy.
- To share data, all you need to do is use the Angular CLI to generate a new service.
- This service can be injected into any component and will allow the components to share data.

33. Angular by default, uses Client-Side Rendering for its Applications.


- This means that the Angular application is rendered on the client-side — in the user's web browser.
- Client-side rendering has a number of advantages, including improved performance and better
security.
- However, there are some drawbacks to using client-side rendering, as well.
- One of the biggest drawbacks is that it can make your application more difficult to debug.
- Client-side rendering is typically used for applications that are not heavily data-driven.
- If your application relies on a lot of data from a server, client-side rendering can be very slow.
- Additionally, if you're using client-side rendering, it's important to be careful about how you load
and cache your data.
- If you're not careful, you can easily end up with an application that is very slow and difficult to use.
- When rendered on the server-side, this is called Angular Universal.

MODIFIED BY SHUBHAM LAMBAT


82

34. Explain the Concept of Dependency Injection.


- Dependency injection is a technique used to create loosely coupled code.
- It allows pieces of code to be reused without the need for hard-coded dependencies.
- This makes code more maintainable and easier to test.
- Dependency injection is often used in frameworks like AngularJS, ReactJS, and VueJS.
- It is also possible to use dependency injection in vanilla JavaScript.
- To use dependency injection in JavaScript, you need a dependency injection library.
- There are many different libraries available, but they all work in basically the same way.

35. What are RxJs in Angular?


- RxJs is a library that provides reactive programming support for Angular applications.
- It allows you to work with asynchronous data streams and handle events over time.
- RxJs is based on Observables, which are data streams that can be subscribed to and processed using
operators.
- It provides a powerful and flexible way to handle complex asynchronous operations in Angular.

36. What exactly is a Parameterized Pipe?


- It is a pipe that accepts one or more arguments, also known as parameters.
- Pipes transform data in Angular templates, and parameterized pipes allow you to customize the
transformation based on specific requirements.
- By passing parameters to a pipe, you can modify its behavior and apply different transformations
to the data.

37. What are Class Decorators?


- Class decorators in Angular are a type of decorator that can be applied to a class declaration.
- They are used to modify the behavior of the class or add additional functionality.
- Class decorators are defined using the @ symbol followed by the decorator’s name and are placed
immediately before the class declaration.
- They can be used for various purposes, such as adding metadata, applying mixins, or extending the
functionality of a class.

38. What are Method Decorators?


- Method decorators in Angular are decorators that can be applied to methods within a class.
- They are used to modify the behavior of the method or add additional functionality.
- Method decorators are defined using the @ symbol followed by the decorator’s name and are placed
immediately before the method declaration.
- They can be used for tasks like logging, caching, or modifying the method's behavior based on
specific conditions.

39. What are Property Decorators?


- Property decorators in Angular are decorators that can be applied to class properties.
- They are used to modify the behavior of the property or add additional functionality.
- Property decorators are defined using the @ symbol followed by the decorator’s name and are
placed immediately before the property declaration.
- They can be used for tasks like validation, memorization, or accessing metadata associated with the
property.

40. What are the Key Concepts of Angular?


- Some key concepts of Angular include components, modules, templates, data binding, services,
dependency injection, and routing.
- These concepts form the foundation of Angular development and help in building dynamic and
scalable web applications.

MODIFIED BY SHUBHAM LAMBAT


83

41. What are Router Links?


- Router links in Angular are used for navigation within an application.
- They are defined using the routerLink directive and provide a way to navigate to different routes or
components.
- Router links can be used in HTML templates and are typically placed on anchor (<a>) tags or other
clickable elements.
- By specifying the destination route or component, router links allow users to navigate between
different parts of an Angular application.

42. What Exactly is the Router State?


- The router state in Angular represents the current state of the Angular router.
- It contains information about the current route, including the URL, route parameters, query
parameters, and other related data.
- The router state can be accessed and manipulated using the Angular Router service.
- It provides a way to programmatically navigate, retrieve information about the current route, and
handle route changes in Angular applications.

43. What does Angular Material Mean?


- Angular Material is a UI component library for Angular applications.
- It provides a set of pre-built and customizable UI components, such as buttons, forms, navigation
menus, and dialog boxes, that follow the Material Design guidelines.
- Angular Material simplifies the process of building consistent and visually appealing user interfaces
in Angular.
- It offers a range of features and styles that can be easily integrated into Angular projects.

44. What is Transpiling in Angular?


- Transpiling in Angular refers to the process of converting TypeScript code into JavaScript code that
web browsers can execute.
- Angular applications are built using TypeScript, a superset of JavaScript that adds static typing and
additional features to the language.
- Since browsers can only run JavaScript, the TypeScript code needs to be Transpiled into JavaScript
before it can be executed.
- This is typically done using the TypeScript compiler (tsc) or build tools like Angular CLI.

45. What are HTTP Interceptors?


- HTTP interceptors in Angular are a feature that allows you to intercept HTTP requests and
responses globally.
- Interceptors provide a way to modify or handle HTTP requests and responses at a centralized
location before they reach the server or client.
- This can be useful for logging requests, adding authentication headers, handling errors, or
modifying request/response data.
- Interceptors can be registered in the Angular module and are executed in a specific order based on
the request/response pipeline.

46. What is a Bootstrapping Module?


- A bootstrapping module in Angular is the main entry point of an Angular application.
- It is responsible for starting the application and initializing the root component.
- The bootstrapping module is typically defined in the [Link] file and is configured in the Angular
AppModule.
- It sets up the necessary environment, loads required modules, and invokes the Angular platform to
start the application.
- The bootstrapping module plays a crucial role in the Angular application's lifecycle.

MODIFIED BY SHUBHAM LAMBAT


84

47. How do you Choose element from a Component Template?


- You can use various techniques to choose an element from a component template in Angular.
- One common approach is to use template reference variables.
- The template defines these variables using the # symbol followed by a name.
- You can then reference the element using the variable name in your component code.
- Another approach is to use Angular directives like ViewChild or ViewChildren to query for
elements based on CSS selectors or component types.
- These directives provide more flexibility and control when selecting elements from the component
template.

48. How do you Deal with Errors in Observables?


- When dealing with errors in observables in Angular, catchError operator can be used to handle and
recover from errors.
- This operator allows you to provide a fallback value or execute alternative logic when an error
occurs.
- You can chain the catchError operator after the observable that might produce an error and define
a callback function to handle the error.
- Within the callback function, you can perform error handling tasks such as logging the error,
displaying an error message to the user, or initiating a retry mechanism.

49. What Happens when we Use the Script tag Within a Template?
- Using the script tag within an Angular template is not a recommended practice.
- Angular templates are intended for defining the structure and layout of the user interface, and
including scripts directly within the template goes against the separation of concerns principle.
- When a script tag is used within a template, the browser treats it as part of the HTML content and
attempts to execute it.
- However, Angular's template compiler does not process or execute scripts within templates.
- Instead, scripts should be placed in separate JavaScript files and included using the appropriate
Angular mechanisms, such as component logic or Angular modules.

50. What is Angular Coding Language?


- Angular itself is not a coding language.
- It is a framework for building web applications using TypeScript.
- TypeScript is a superset of JavaScript that adds static typing and additional features to JavaScript.
- Angular leverages TypeScript to provide a more structured and scalable approach to web
development.

51. What is a Service in Angular?


- In Angular, a service is a class that is used to share data or functionality across different
components.
- Services are responsible for providing specific functionality that can be used by multiple
components in an application.
- They promote reusability, modularity, and maintainability in Angular projects.

52. What is the Full form of ng in Angular?


- In Angular, "ng" stands for "Angular".
- It is a convention used in Angular to prefix directives, components, and other Angular-specific
entities.
- For example, ngFor is a built-in Angular directive used for rendering lists based on an array, and
ngModel is a directive used for two-way data binding between an input element and a component
property.
- The "ng" prefix helps to distinguish Angular-specific entities from regular HTML elements and
attribute.
MODIFIED BY SHUBHAM LAMBAT

You might also like