Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

All QA 2.O

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

1

All Question Answer

Modified By - SHUBHAM_LAMBAT

MODIFIED BY SHUBHAM LAMBAT


2

INDEX PAGE
TA B L E O F C O N T E N T S

03 SQL 15 C#

32 LINQ 38 JAVASCRIPT

45 jQuery 47 SOLID Principle

48 DESIGN Pattern 50 ASP.NET

55 MVC 67 ADO.NET

69 ENTITY Framework 70 WEB API

75 UNIT Testing 78 ANGULAR

89 COMPANY QA 94 PROGRAMS

MODIFIED BY SHUBHAM LAMBAT


3

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) –
o Commands which affects on schema or structure.
o These SQL commands are used for creating, modifying, and dropping the structure of database
objects. (i.e. affects on schema or structure).
o These commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.

- Data Manipulation Language (DML) –


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

- Transaction Control Language (TCL) –


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

- Data Control Language (DCL) –


o Commands to control permissions.
o 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
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.]
MODIFIED BY SHUBHAM LAMBAT
4

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 :
a. We can have a Single Primary Across the Table whereas we can have Multiple Unique Key
across the Table.
b. 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. Set NULL:
It will delete or update records from primary key table and set null value in foreign key
table.
c. Set Default:
It will delete or update records from primary key table and set default value in foreign key
table.
d. Cascade:
It will delete or update records from primary key table as well as from foreign key table.

5. What is Composite key in SQL?


- Primary key over more than one or more Columns.
- A primary key that is made by the combination of more than one column is known as a
composite key.
- Sometimes more than one attributes are needed to uniquely identify an entity.
- 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.

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.
o SCOPE_IDENTITY() – Returns the last identity value that is created in the same session and
in the same scope.
o @@IDENTITY –Returns the last identity value that is created in the same session and across
any scope.
o IDENT_CURRENT('tblName') – Returns the last identity value that is created for a specific
table across any session and any scope.

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)
MODIFIED BY SHUBHAM LAMBAT
5

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
 The data in each column should be atomic. (There should not be comma separated values).
 The table does not contain any column repeating groups.
 Every record should identify uniquely (i.e., every record should have primary key).
 2NF
 The table satisfy all the conditions of 1NF.
 Identify groups and split into multiple tables.
 Create relationship between these tables using foreign keys
 3NF
 The table satisfy all the conditions of 1NF and 2NF.
 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 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.

12. 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.
a. Inner Join
b. Outer Join which again classified to 3 subtypes
o Left Outer Join
o Right Outer Join
o Full Outer Join
c. Cross Join

Inner Join –
- Inner joins return only the common records from both the tables.
Left Outer Join –
- Left join returns common records from both tables as well as uncommon records from left table.
Right Outer Join –
- Right 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.

MODIFIED BY SHUBHAM LAMBAT


6

13. What is Self-Join?


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

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 :
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.
Non Correlated Sub Query :
- Outer query depends on inner query.
- Inner query runs first.
- Inner query executes once.

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:
i. Execution Plan Retention - 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.
ii. Reduces Network Traffic - You only need to send, EXECUTE SP_Name statement, over the
network, instead of the entire batch of adhoc SQL code.
iii. 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.
MODIFIED BY SHUBHAM LAMBAT
7

iv. 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.
v. Avoids SQL Injection Attack - SP's prevent SQL injection attack.

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

19. 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 ().

20. 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()

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

22. 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:
o Scalar functions always return a single scalar value.
o The returned value can be of any data type except text, ntext, image, cursor, and timestamp.

2) Inline Table Valued Function:


o The Inline Table Valued function returns a table but we cannot customize the schema of
returned table.
o Inline table valued function cannot have begin and end body.
o It is faster than multi statement table valued unction.

3) Multi Statement Table Valued Function:


o The multi statement table valued function returns a table and we can customize the
schema of returned table.
o The multi statement table valued function can have begin and end body.

MODIFIED BY SHUBHAM LAMBAT


8

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

24. 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 –
a. Local Temporary tables
b. Global Temporary tables.

Difference Between Local and Global Temporary Tables:


a) Local Temp tables are prefixed with single pound (#) symbol Whereas global temp tables are
prefixed with double pound (##) symbols.
b) 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.
c) 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.
d) 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.

25. What 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

MODIFIED BY SHUBHAM LAMBAT


9

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

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

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


- Syntax for SELECT INTO :
SELECT col1, col2 INTO targetTblName FROM sourceTblName

29.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.
MODIFIED BY SHUBHAM LAMBAT
10

- Difference between Clustered and Non-Clustered Index:


a) Only one clustered index per table, where as you can have more than one non clustered index
b) 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.
c) 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.

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

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

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

32.
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.
MODIFIED BY SHUBHAM LAMBAT
11

Advantages of using views:


a) 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.
b) Views can provide row and column level security.
 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.

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

34. 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.
a) After or For triggers
- After trigger will be fired and executed after performing the Insert, Update and Delete
actions successfully.
b) 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
12

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


- There are 2 magical tables available while working with triggers:
1) INSERTED Table
o 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
o 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.

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

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

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

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

40. 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)
MODIFIED BY SHUBHAM LAMBAT
13

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 skip 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)

41. What is Pivot and UnPivot in SQL?


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

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

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

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

45. 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 searches row by row.
- Use temporary table to handle bulk data.

46. What is Deadlock?


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

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

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

49. 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 come across situation
where I can implement cursors in my project. Again, they are bad over performance.]

50. How to Optimize Store Procedure


- This can be achieved through various techniques, including proper indexing, avoiding unnecessary
operations, and optimizing the query execution plan.
1) Use Indexes
2) Limit the Number of Rows
3) Avoid Using Cursors
4) Minimize Data Retrieval
5) Avoid Using Temporary Tables
6) Optimize Joins
7) Avoid Nested Subqueries
8) Recompile Option
9) Avoid Functions in WHERE Clauses
10) Monitor Execution Plans
11) Consider Partitioning
12) Regular Maintenance
13) Use Stored Procedures Wisely

51. How to Optimize SQL Query.


- Use Indexes - Limit the Result Set
- Avoid Using Wildcards at the Beginning of a LIKE Pattern
- Use Joins Efficiently - Avoid Using Nested Subqueries
- Minimize Transactions - Use EXISTS or IN Instead of DISTINCT
- Avoid Cursors - Optimize Group by and Having
- Update Statistics - Avoid Using Functions in WHERE Clauses
- Consider Deformalizing DataUse - UNION ALL Instead of UNION
- Regular Database Maintenance - Review and Optimize Execution Plans
- Avoid Using DISTINCT Unless Necessary
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()
• Convert Any Type value into String format we use Parse().

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 Var 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”.
 Types Of Array:
 Single-Dimensional Array
 Multi-Dimensional Array

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 are 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 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.
 It is a programming paradigm that uses the concept of "objects" to design and organize code.
 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];
Console.WriteLine (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.
- Encapsulation means Wrapping of Data and Methods/Properties into a Single Unit.

- 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 is 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 keyword is use for stop Inheriting.
• 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.
• 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#.
• Public – It is accessible anywhere in the application.
• 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.
• 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 Convert.ToString() and ToString() methods?


• Convert.ToString() handles NULL Whereas ToString() doesn’t handles 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
{
S1.Gender = Gender.Male
S1.Gender = Gender.Female
}

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;
Console.WriteLine(number.GetType());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.

68. 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 is 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 System.Lazy 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 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
[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

87. What is “Is Keyword” And “As Keyword”?


Is Keyword :-
o It is used for type Checking.
o It returns True Or False
As Keyword :-
o It is used for type Casting.
o If type casting Not Done then it return Null value.

88. What is the Difference Between “DISPOSE” AND “FINALIZE”?


- Dispose is a method of IDisposable interface.
- Inside this method developer has to write the code to clean or destroy the objects which are no
more required.
- Finalize is called by GARBAGE COLLECTOR automatically and need not to be called by the
user code to run.
- There is no performance cost associated with Dispose method, as the developers know when the
objects will be created and where to clean up them.
- There is performance cost associated with Finalize method.
- For example, if GC is running in every 10 minutes but there are no objects for cleaning then it is
just wasting the memory which it is using for running.

MODIFIED BY SHUBHAM LAMBAT


31

89. What is the Difference Between “FINALIZE” AND “FINALLY” Method?


- Finalize –
o This method is used for garbage collection.
o So before destroying an object this method is called as part of clean up activity by GC.
- Finally –
o This method is used for executing the code irrespective of exception occurred or not.
o It is a part of exception handling.

90. How to Return Multiple Value in C#.


- Using out Parameters
- Using Tuple
- Using List

MODIFIED BY SHUBHAM LAMBAT


32

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 the
- 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) => s.Length > 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"; Console.WriteLine(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
33

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:

customers.Where(c => c.City == "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
tree.ParameterExpression param = (ParameterExpression)exprTree.Parameters[0];
BinaryExpression operation = (BinaryExpression)exprTree.Body;
ParameterExpression left = (ParameterExpression)operation.Left;
ConstantExpression right = (ConstantExpression)operation.Right;

MODIFIED BY SHUBHAM LAMBAT


34

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 (System.Linq) 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
35

- 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 ADO.NET functionalities. But, in case of LINQ, it provides more dignified
way of querying the Dataset and provides some new features as compared to ADO.NET

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=arr.All(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 System.Xml.Linq 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", "ASP.NET"), 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 at least 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


36

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 Single 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 Single 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 System.Collection 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 = dc.Employees.Where(m=>m.Name.StartsWith("a"));
list=list.Take<Employee>(10):

- IQueryable: -
o It exists in System.Linq 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 =dc.Employees.Where(m => m.Name.StartsWith("a")); list=list.
Take<Employee> (10);

MODIFIED BY SHUBHAM LAMBAT


37

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 e.DeptID equals d.DeptID
select new
{
e.EmpID, e.FirstName, 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


38

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 node.js)
 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


39

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)
{
document.write(a + b);
}
Add(10,10);

11. How to write Anonymous Function in JavaScript?


var Add = function(a,b)
{
document.write(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)
{

document.write(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()
{
document.write(result + (a + b));
};
add();
};

MODIFIED BY SHUBHAM LAMBAT


40

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


41

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 document.form[0].submit();

22. What is Substrings in JavaScript?


1) Substring ():
 This method has 2 parameters, Number starts 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


42

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 – Home.js
 Minified File – Home.min.js

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


43

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


44

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


45

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 Document.Ready event?


 Document.Ready 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 Document.Ready() Function on the Same Page?


 Yes. You can write any number of Document.Ready() function on the same page.

MODIFIED BY SHUBHAM LAMBAT


46

12. Difference Between Body Onload() and Document.Ready() function?


 You can have more than one Document.Ready() 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


47

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 it 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


48

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

A. Singleton Design Pattern:


- To restrict object outside of that class and to maintain one single object of a class through the
application

B. Factory Design Pattern:


- Object creation Responsibility in case of inheritance.
- There should not be flowing new keyword throughout application.

C. Dependency Injection (DI):


- We use DI to implement DIP (Dependency Inversion Principle).
- It is Loosely Coupled Architecture, means it is Independent.
- High level module should not directly depend on low level module instead they should depend
through abstract class or Interface.
- There are Multiple Ways to Inject Dependency (To create object of Interface / Abstract Class)
 Injection through Constructor
 Injection through Property
 Injection through Method
- We can Configure in Program.cs File.
- We use Interface, Add Singleton, Add Scope, Add Transients.
- With the help of Constructor Injection, in that Inject dependency Injection in MVC controller.

D. IoC Container:
- Inversion of Control
- We use IoC container for
 Registering Type (Dependency)
 Resolving Type
- An IoC container is a framework or library that manages the dependencies between different
components in your application.
- It's responsible for instantiating objects, resolving their dependencies, and providing them to other
objects. This allows you to decouple the creation and management of objects from your application
logic.
- DI is a specific form of IoC where a component's dependencies are provided by an external entity
(often referred to as a container).
- This means that instead of a component creating its own dependencies, they are "injected" from the
outside, making components more modular, testable, and loosely coupled.

MODIFIED BY SHUBHAM LAMBAT


49

2. What is AddSingleton, AddScope & AddTransient


- AddSingleton –
o Only One Object we can Create Throughout the Application.
o AddSingleton method create only one instance when the service is requested for first time.
o And then the same instance will be shared by all different http requests.

- AddScope –
o We create Object for Every Request.
o AddScope method create single instance per request.
o For every individual request there will be a single instance or object.

- AddTransient –
o AddTransient instance will not be shared at all even with in the same request.
o Every time a new instance will be Created.

MODIFIED BY SHUBHAM LAMBAT


50

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

2. 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 global.asax.cs 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 gets stored either in the page or on the client
computer.
 Some Client based state management techniques are:

MODIFIED BY SHUBHAM LAMBAT


51

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 (Not Applicable In MVC)


 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 Request.QueryString property.

D. Cookies
 Cookies can be used to send data from one webform to another.
 Cookies store at browser Side on user machine.
 Response.Cookies command is used to create cookies.
 Request.Cookies 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.

E. ViewBag
 ViewBag are used to pass data from controller to view.
 ViewBag is a dynamic property collection
 In ViewBag no need to type cast while reading value
 Scope of ViewBag is only within single same request.

F. ViewData
 ViewData are used to pass data from controller to view.
 ViewData is key-value pair collection.
 In ViewData Need type cast.
 Scope of ViewData is only within single same request.

MODIFIED BY SHUBHAM LAMBAT


52

G. TempData
 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.

2) Server-Side State Management Techniques


 In Server based option, information gets 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 web.config

B. Application (Not Applicable In MVC)


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

D. Profile Properties

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) Server.Transfer:
 Redirection done within same server.
 Redirection done by the server.
 URL does not change.
 It skips current page and give target page content.

MODIFIED BY SHUBHAM LAMBAT


53

4) Response.Redirect:
 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) Server.Execute:
 Redirection can be done across multiple servers.
 Redirection done by the browser.URL get changed.
 Skip current page.

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

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)

8. What is Scaffolding
- It is code generation Framework for Asp.Net web application.
- It Give Code Automatically it is Known as Scaffolding.
- It gives auto Generated code.
- It reduces Developers Efforts & Time.

9. ASP.NET Core Importance.

MODIFIED BY SHUBHAM LAMBAT


54

10. What is Render Body & Render Session?


- It used in layout to render view Content.
- We can us only one render body.
- But we can use multiple render Session.
- It uses for loading all data for view response.

11. How to Handle Session in MVC?


- For that we can use ViewBag, ViewData & TempData.

12. What is HTML Helper


- HTML Helper is a method that is used to render HTML content in a view.
- We can use HTML helper class with Extension Method to Create UI Control like
- Text Box, Button, Text Area, a Tag, Etc.

MODIFIED BY SHUBHAM LAMBAT


55

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

2. Which Version of MVC you have Used?


- We have used MVC 6 in our last project.

3. How Request and Response Occurs in MVC Application?


o Whenever user initiates the request with the help of routing it finds the controller.
o It creates of object of that controller and start execution for requested action method.
o If action method is returning a ViewResult then it finds appropriate view and returns to the
browser.

4. 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 global.asax file.

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


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

6. 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 Action Filter
o Result Filter
o Exception Filter

MODIFIED BY SHUBHAM LAMBAT


56

7. What is Authorize Attribute?


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

8. What are Action Filters?


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

9. Explain Exception Filter?


o Using ExceptionFilter we can achieve exception handling in MVC.
o 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.

10. Which Filters you have used in your Project?


o We have used Authorize filter for authentication.
o HandleError filter for exception handling
o OutputCache filter.
o We have created custom filters for global error handling.

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

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

13. What is difference between ASP.NET and MVC Application?


- There are Various Difference between ASP.Net & MVC Application.
a. MVC is lightweight compare to ASP.NET.
b. ASP.NET application we request to a physical file i.e., Web forms
whereas
c. In MVC application we request to a controller action method.
d. ASP.NET application uses server controls which makes page heavy
but in MVC we use HTML helpers which are lightweight.
e. ASP.NET code is tightly bind with code behind file whereas in MVC
view and action methods are separated.
f. ASP.NET is event-based development model whereas MVC is an
architectural pattern with Model Views and Controllers.

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

MODIFIED BY SHUBHAM LAMBAT


57

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

16. What is HttpVerbs in MVC?


- There Are Different Type of HttpVerbs
 Get,
 Post,
 Put,
 Patch,
 Delete
- 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.

17. 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.
- By default, our URL is like domain/controller/action.
- But with area the URL is changes to domain/AreaName/controller/action.

18. What is Difference Between Html.Textbox and Html.TextboxFor?


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

19. What is difference between ViewBag and ViewData?


- These are the techniques to manage state of a MVC application.
- 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 & ViewData is only within single same request.

20.Explain 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.

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

MODIFIED BY SHUBHAM LAMBAT


58

22. 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 Program.cs 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.
 Using Route attribute, we can configure routings in MVC
application.
 We can use Route attribute on action method or on controller
level also.

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

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


- We use MapControllerRoute method and configure more than one routes in Program.cs file.
- We have to mandatory provide name and URL parameters to MapControllerRoute method.

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.

MODIFIED BY SHUBHAM LAMBAT


59

28. What is AJAX? can you write a Syntax for AJAX Call?
- AJAX is asynchronous JavaScript.
- Using AJAX, we can reload part of the page & it not reload full Page or Application.
- Using AJAX, we can call server code without reloading page.
- Syntax: $.ajax({
url:___, type:___, data:___,
success:function(){},
error:function(){}
});

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

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

31. How do you Maintain Security in your Project?


- We have used Form-Based Authentication and SSL, to provide security in our application.

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

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

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


- We have used Grid.Mvc nugget package to display records and used bootstrap to control over its
styling.

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

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

MODIFIED BY SHUBHAM LAMBAT


60

37. 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 CSS attack by giving proper validations against these input fields.

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

39. Do you know Unit Testing?


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

40. 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 AJAX.ActionLink method
- and I will set UpdateTargetId parameter to div id.

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

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

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

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

45.What 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.

MODIFIED BY SHUBHAM LAMBAT


61

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

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

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

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

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

51. Where we do Validations in MVC?


- We do all validations in models using validation attributes.
- All validation specific attributes are define in System.ComponentModel.DataAnnotations.

52. What is ModelBinder in MVC?


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

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

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

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

MODIFIED BY SHUBHAM LAMBAT


62

56. What is Difference between Partial and RenderPartial?


- Both the methods are used to render partial view on main view.
- Partial it is Little Bit Slower.
- Render Partial it is Faster Because it is directly writing Partial View Contain on the Browser.
- 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.

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

58. 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 ASP.NET

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

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

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

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

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

MODIFIED BY SHUBHAM LAMBAT


63

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

65. 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.
- On other hand minification is process of compressing JS or CSS files
- Which actually does 3 things
o It removes all comments
o It removes all new lines and blank spaces
o Its shorthand the names of variables and methods.
- Which reduces the file size.

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


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

67. How to Return String from an Action Method?


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

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


- Layouts in MVC is very similar to Master pages in ASP.NET.
- 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.

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

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

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

72. 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 DataType.Date to this attribute as parameter.

MODIFIED BY SHUBHAM LAMBAT


64

73. How to Consume Bootstrap in MVC Application?


- We can include all bootstrap files like bootstrap.css, bootstrap.js and jquery.js 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.

74. 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, ASP.NET identity.

75. Repository Pattern?


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

76. How do Validation in MVC?


- Model Side use Data Annotation Namespace or Validation Attribute
- For Client-Side Validation
o jQuery.validate.min.js
o jQuery.validate.unobtrusibe.js

- For Server-Side Validation


o [Required]
o [StringLength]
o [EmailAddress]
o [Range]
o [RequiredExpression]
o [DataType]
o [Display]

77. What Is method to Implement Custom Filter?


- IFilterMetadata Interface
- ActionFilterAttribute

78. What is App.Use & App.Run


- App.Use is use to handle the request when one request work is done then it can give that request to
another.
- App.Run: program start to run the application.

79. Managed Code


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

80. Unmanaged Code


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

MODIFIED BY SHUBHAM LAMBAT


65

81. How to register Filter Globally?


- In Program.cs we can register.
- Builder.services.addControllerWithViews (option => option.filter.add
{
typeOf(globalFIlter)
})

82. Where Error Log do.


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

83. What is Hosting?


- Process of deploying application onto the process.
- "hosting" refers to the environment or platform where your MVC application is deployed and runs.
- The hosting environment provides the necessary infrastructure and services for your application to
handle incoming requests, process them, and send back responses.

84. Stages of Deployment?


- Planning
- Development
- Testing
- Deploying
- Monitoring

85. What is Resource Filter?


- It can be used 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
}
}

86. Difference Between View & Partial View


- View Contain Layout Page Whereas Partial View Dose not Contain.
- _ViewStart.cshtml page is rendered before any view is rendered Whereas does not check for
_ViewStart.cshtml in Partial View.
- View may have Markup Tags like HTML, Body, Head, Title, Meta, Etc. Whereas The Partial View
is specially designed to render within the view and as a result it does Not Contain Any Markup.
- View we use For Display the Data Whereas Partial View it creates Part of Pages, It render on Main
View by using Partial, RenderPartial & RenderAction Methods.
- View we can use for one Time Whereas Partial View we use for Reusable Purpose, we can write Once
and Access any View.
- View It is a Main View Whereas Patial view it is a Part of Pages.

MODIFIED BY SHUBHAM LAMBAT


66

87. What is Middleware?


- It is handling Request and Response.
- We can configure Dependency Injection.
- It handles Request & Response in Request Processing Pipeline.
- We can setup the Middleware in ASP.Net using the configure method of over Startup Class.
- Methods –
o UseStaticFiles
o UseRouting
o UseAuthorization

MODIFIED BY SHUBHAM LAMBAT


67

ADO.NET
1. What is ADO.Net?
 Ado.net stands Microsoft ActiveX Data Objects.
 Ado.net is a set classes that can be used to interact with data sources like
database and XML.
 ADO.Net, we use for database Communication.
 Database can be anything like SQL, Oracle, MS Access, Excel, etc.

2. What are the Classes used in ADO.Net?


 SqlConnection
 SqlCommand
 SqlDataReader
 SqlDataAdapter
 Dataset

3. What are the Steps to Communicate Database using ADO.Net?


 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) ExecuteNonQuery – 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


68

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


69

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


 ADO.net creates bunch of data layer code Whereas Entity Framework doesn’t create
bunch of code.
 ADO.net is faster than entity framework because entity framework uses ado.net code
behind so entity framework requires some extra time cost.
 In ADO.Net we need to write so much of code Whereas in Entity Farmwork we don’t
need to write so much of code.
 ADO.Net 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.

6. Write the Steps to Implement the Code-First approach in Entity Framework


 Create a Class Library Project
 Install Entity Framework NuGet Package
 Define Your Model Classes
 Create a DbContext Class
 Configure Connection String
 Enable Migrations
 Add Initial Migration
 Update Database.

MODIFIED BY SHUBHAM LAMBAT


70

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.
 A protocol refers to a set of rules and conventions that govern how data is transmitted over the
internet.
 It defines the format and structure of messages exchanged between different software
components.
 Ex. http - Internet
tcp - Intranet (Communicate with LAN)
namedpipe – Used when same server
msmq - To maintain que
 There are several Commonly used Protocol in Web API.
o HTTP (Hypertext Transfer Protocol)
o HTTPS (Hypertext Transfer Protocol Secure)
o REST (Representational State Transfer)
o SOAP (Simple Object Access Protocol)
o WebSocket
o MQTT (Message Queuing Telemetry Transport)

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.

MODIFIED BY SHUBHAM LAMBAT


71

10. Web API uses which of the following Open-Source Library for JSON Serialization?
 Web API uses Json.NET 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

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 System.Web.Http.ApiController whereas MVC derives
from System.Web.Mvc.Contoller
 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.
 We have to install System.Net.HTTP Nugget package.
 HttpClient sends a request to the Web API & 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

MODIFIED BY SHUBHAM LAMBAT


72

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.

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 mean by Async & Await


 Async:
o The async keyword is used to declare a method as asynchronous.
o An asynchronous method is a method that can run in the background while the calling
code can continue its execution.
o It does not block the calling thread.

 Await:
o The await keyword is used inside an async method to indicate a point at which the
method can pause its execution until a specific task is complete.
o The method will resume execution after the awaited task completes.

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

25. What is Content Negotiation


 Content negotiation is a process that allows a client and a server to agree on the format and
language of the data being exchanged.
 When we Consume the API we reused the data in the form of JSON, XML, Plain Text.
 It enables a web server to serve the most appropriate representation of a resource based on the
client's preferences.
 Media Type Format
 Also called Communication Msg Format
 Ex. Json, XML.

26. What is CORS?


 If we want to give access of our Domain To another Domain then we use CORS
 Also, if we want give API service for Two different Project Then we have to Enable CORS.
 CORS means Cross Origin Resource Sharing.
 We add Nugget Package Microsoft.asp.netcore.CORS
 We can register service in program.cs file.

27. What is Media Type Formator?


 It is a abstract class which form the JSON media formator & XML media Formator it Inherited.
 We can use Serialization & Deserialization.
 Media type Formator is used for Content Negotiation.

MODIFIED BY SHUBHAM LAMBAT


73

28. Suppose I Have Two Method with Same Name then How to call in Web API.
 We can use as same name with different Parameter (it’s called Method Overloading)
 Or we can use Action Name Attribute.
 Or we can use Rout Attribute in that we can use different URL to call that method.

29. What is HTTP Status Code?


 1XX – Informational
 2XX – Success
 3XX – Redirection
 4XX – Client Error
 5XX – Server Error

30. What HTTP Status Code Return?


 100 – Continue
 102 – Processing

 200 – OK
 201 – Created
 204 – No Content

 300 – Multiple Choice


 302 – Found

 400 – Bad Request


 401 – Unauthorized
 402 – Payment Required
 404 – Not Found
 405 – Method Not Allowed

 500 – Internal Server Error

31. How to Consume WEB Api from a .Net MVC Application?


 Web API methods can be consumed with the help of HttpClient class.
 Below are the steps for consuming any Web API in a MVC application

MODIFIED BY SHUBHAM LAMBAT


74

32. How you Secured the WEB Api?


 In our project, we have 2 different servers.
 One server is Internal Server on which we have hosted our API and another server is
MVC server we call it Demonetized Server which is outside server.
 So, we have used CORS to authenticate user.
 And at MVC side we have used OCTA tool to authenticate User.
 Which was provided by client so when user enter credentials it will redirect to OCTA tool
so after authenticating user can login into UI layer.

33. WHAT IS REST AND RESTFUL?


 REST stands for Representational State Transfer.
 It is a set of guidelines which helps in creating a system where applications can easily communicate
with each other.
 REST Guidelines:
- Separation of Client and Server - The implementation of the client and the implementation
of the server can be done independently without each knowing about the other.
- Stateless - The server will not store anything about the latest HTTP request the client made. It
will treat every request as new. No session, no history.
- Uniform interface – Identify of resources by URL for example: www.abc.com/api/questions
- Cacheable - The cacheable constraint requires that a response should implicitly or explicitly
label itself as cacheable or non-cacheable.
- Layered system - The layered system style allows an architecture to be composed of
hierarchical layers. For example, MVC is a layered system.

 RESTFUL: If a system written by applying REST architectural concepts, it is called RESTful


services.

34. What is Web Api end Point.


 Here are some key points about Web API endpoints:
o Resource-Based: Endpoints in a Web API are often organized around resources, which are
the main entities or objects that the API deals with (e.g., users, products, orders).
o HTTP Methods: Each endpoint supports one or more HTTP methods, such as GET
(retrieve data), POST (create new data), PUT (update existing data), DELETE (remove
data), etc.
o Uniform Resource Locator (URL): The endpoint is identified by a unique URL. The URL
defines the path and, optionally, parameters needed to access the resource.
o Request and Response: When a client sends an HTTP request to an API endpoint, the API
processes the request and returns an appropriate HTTP response, which may include data,
status codes, and headers.

 For example, in a RESTful Web API for a social media platform, you might have endpoints like:
GET /users: Retrieve a list of all users.
GET /users/{id}: Retrieve a specific user by their ID.
POST /users: Create a new user.
PUT /users/{id}: Update an existing user.
DELETE /users/{id}: Delete a user.

 Web API endpoints are fundamental to building APIs that allow clients to interact with the API and
perform various operations on resources.

MODIFIED BY SHUBHAM LAMBAT


75

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


76

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 -> IDisposable.Dispose
- 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


77

- 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


78

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


79

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


80

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


81

- 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


82

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


83

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 “form.value” 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


84

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


85

- 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


86

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


87

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 main.ts 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


88

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
89

COMPANY QA
1. What Is SDLC
- Software development lifecycle
- It’s a process to develop and deliver any application / website/ software
- Phases :-
o Requirement Gathering
o Analysis
o Design
o Coding
o Testing
o Production/ Live
o Maintenance & Support

2. Coding Standards
- Code Analysis
o Naming conventions
o Performance
o Security
o Scalability
o Maintainability
o Two ways
 During development time/ coding time using FxCop Tool
 After commit/ check in using tools like SonarCube
- Code Metrics
o Maintainability Index
o Cyclomatic Complexity
o Depth Of Inheritance
o Class Coupling
o Lines of code
- Code Coverage
o How much written code is covered by test cases

3. What Is GIT? Have you use GIT in Your Project


- GITHUB is extension of GIT.
- On joining company
o ID card
o Official email
- On project assignment
o Admin will provide access to GIT repository
o They will share GIT repository URL
Steps:
- Clone (once)
- Create own branch
- Make changes as per requirement
- Commit changes to locally created branch
- Merge changes from main/master to locally created branch
- Solve conflicts if any
- In case of conflicts, Commit changes to locally created branch
- Push branch to git
- Pull request (code review request)
MODIFIED BY SHUBHAM LAMBAT
90

- *code changes, commit, push, pull request required in case of code review comment
- Reviewer will merge changes from your branch to main/ base branch

GIT Branches
- Master Branch
o No direct commit
o Deployments done from this branch
- Release Branch
o Release specific branches
- Hotfix Branch
o Any escalation/ ticket/ incident fix on live environment
- Feature Branch (multiple)
o Feature means authentication, payment, etc.
- Developer specific branch for task completion

4. How many Meetings Done in Your Organization / Company


- Sprint Pre planning meeting
o PO, SM, Scrum team
o Planning of next sprint
o Discussion on all user stories from next sprint
o Estimating all user stories from next sprint
 Story point
 1 SP = 1 Day = 8 Hours
o Decides scope of user story
 Committed
 Dev Only
 Test Only
 Out Of Scope
 Deferred
- Sprint Planning Meeting
o PO, SM, Scrum team
o Finalizing estimations
o Finalizing user stories scope
o Answers for all queries
- Retrospective meeting
o PO, SM, Scrum team
o Done on last day of sprint or 1st day of next sprint
o 1st day of Sprint 2, have retrospective meeting for Sprint 1
o Agenda
 What went well
 What went wrong
 Action items/ improvements
- Scrum meeting/ Daily Standup Meeting
o Scrum team
o Daily meeting at a fixed defined time – 10 am
o Updates about assigned user stories, daily work by all team members
- Demo meeting
o PO, SM, Scrum team
o Developer demonstrates developed user story to PO, SM or any client-side member.

MODIFIED BY SHUBHAM LAMBAT


91

5. What is JIRA
- Project management tool
- Jira Software provides planning and tracking tools so teams can manage dependencies, feature
requirements, and stakeholders from day one.
- CI/CD integrations facilitate transparency throughout the software development life cycle.
- Here are some of the key reasons why organizations use Jira:
o Issue Tracking: Jira excels at tracking tasks, bugs, user stories, and other types of issues
in a project. It provides a centralized platform for teams to create, prioritize, assign, and
resolve tasks efficiently.

o Workflow Management: Jira allows you to define customized workflows that reflect
your team's specific processes. This helps in visualizing and managing the entire lifecycle
of a task or project, from creation to completion.

o Agile Project Management: Jira provides robust support for Agile methodologies like
Scrum and Kanban. It helps teams plan and manage sprints, backlog, and iterations,
making it an ideal tool for Agile development practices.

o User Story Management: For Agile teams, Jira allows you to create and manage user
stories, epics, and other backlog items. This helps in breaking down larger tasks into
smaller, manageable pieces.

o Sprint Planning: Teams can use Jira to plan and manage their sprints, set sprint goals,
estimate story points, and allocate tasks to team members.

o Customizable Dashboards and Reports: Jira provides a range of reporting and


dashboard features that allow teams to track progress, identify bottlenecks, and make
data-driven decisions. Customizable dashboards can be tailored to display the specific
metrics that matter to your team.

o Team Collaboration: Jira provides features for team collaboration, including


commenting on tasks, @mentions, notifications, and activity feeds. This fosters
communication and helps in maintaining transparency within the team.

o Scalability: Jira can be used by small teams as well as large enterprises. It can scale to
accommodate the needs of complex, multi-team projects.

o Traceability and Auditability: Jira provides a detailed history of all changes made to
issues, which can be important for compliance, auditing, and debugging purposes.

o Prioritization and Backlog Management: Teams can use Jira to prioritize tasks based
on factors like urgency, business value, or dependencies. This helps in ensuring that the
most critical work is addressed first.

o Release Management: Jira allows teams to plan and track releases, manage versioning,
and link issues to specific releases. This helps in coordinating development efforts
towards specific milestones.

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


92

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

8. Explain your Project Architecture?


 My application has 3 tier architecture.
 In that we used MVC as Presentation Layer i.e., UI, Web API as Business Layer and Sql
server as Database Layer.
 The MVC layer not directly communicate with the database.
 The MVC layer is communicate with the Web API layer for that we have used
Repository pattern to call APIs.
 When API gets requests from the MVC layer, the API repositories interacts with the
database layer.
 All the calls from MVC layer are transferred to the database through the API project.
 The API project which is hosted on internal server of my client and only the MVC
layer is visible to external users.

9.What you did in your Project?


 In our application, basically I worked on all different layers.
 I worked on database, MVC and Web API also.
 In database, I worked on table design, writing store procedures and views,
optimization of queries.
 In MVC, I worked on Forms Authentication, Validations, Consuming Web API in
controller.
 In Web API, I worked on writing methods for accessing data from database and also
testing of API methods using Postman.

10. What is Your Team Size?


 Team size- 12
 Dot net developer- 6
 Tester – 8
 Deployment – 2
 Team lead – 1

MODIFIED BY SHUBHAM LAMBAT


93

11. Do you know about Agile Process?


 Yes. I worked in agile process in my previous organization.
 We used Agile scrum. Where we worked in 2-week sprint.
 Sprint is duration which we will deliver something to client.
 Every sprint has Release where we delivering product to client.
 Agile scrum has scrum meeting.
 Agile scrum has -
o Product owner- Business analyst- helps to understand the requirement
o scrum master- Manager
o scrum team – developers, testers, leads etc.

MODIFIED BY SHUBHAM LAMBAT


94

PROGRAMS
1. How to Delete Duplicates Rows from Table.
with cte
as
(
select Name,
ROW_NUMBER() over (partition by Name order by Name) As
RowNumber from sample1
)
delete from cte
where RowNumber >1

2. How to Find 4th Highest Salary from Employees Table (Explain Different Ways).

- 1st way using SubQuery :


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

- 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 = 4

3. Write Inner join Query to Find whose Manager of Employee


create table Employees (
ID int PRIMARY KEY,
Name varchar(50),
City varchar(50),
ManagerID int,
FOREIGN KEY (ManagerID) REFERENCES Employees(ID)
);
INSERT INTO Employees (ID, Name, City, ManagerID)
VALUES (1, 'Akshay Raut', 'Yavatmal', 2), (2, 'Shubham Lambat', 'Wardha', NULL),
(3, 'Sonali Param', 'Pune', 2), (4, 'Maithili Rathod', 'Nagpur', 1), (5, 'Vikas Mishra', 'Chandrpur', 3);

SELECT e.Name AS Employee, m.Name AS Manager


FROM Employees e JOIN Employees m ON e.ManagerID = m.ID;

Also Find if No Manger Then Set CEO


SELECT e.Name AS Employee, COALESCE(m.Name, 'CEO') AS Manager
FROM Employees e LEFT JOIN Employees m ON e.ManagerID = m.ID;

MODIFIED BY SHUBHAM LAMBAT


95

4. Reverse the String ‘Shubham’ to ‘mahbuhS’


- 1st way:
static void Main()
{
Console.WriteLine("Enter String :- ");
string name = Console.ReadLine();
string rev = null;
for(int i = name.Length-1; i >= 0; i--)
{
rev += name[i];
}
Console.WriteLine(rev);

Console.ReadLine();
}
- 2nd Way:
static void Main()
{
string originalString = "Shubham";
string reversedString = ReverseString(originalString);

Console.WriteLine("Original string: " + originalString);


Console.WriteLine("Reversed string: " + reversedString);
}
static string ReverseString(string input)
{
char[] charArray = input.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}

- 3rd Way:
public static void Main(string[] args)
{
string input = "Shubham";
string reversed = ReverseString(input);
Console.WriteLine(reversed);

foreach (char c in reversed)


{
Console.Write(c);
}
Console.WriteLine();
}
static string ReverseString(string input)
{
char[] charArray = input.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
Reverse the String in C# ‘Shubham’ to ‘mahbuhS’ Without Using Build in Function
static void Main()
{
string originalStr = "Shubham";
string reversedStr = ReverseString(originalStr);
Console.WriteLine(reversedStr);
}
static string ReverseString(string inputStr)
{
char[] charArray = inputStr.ToCharArray();
int start = 0;

MODIFIED BY SHUBHAM LAMBAT


96

int end = inputStr.Length - 1;


while (start < end)
{
char temp = charArray[start];
charArray[start] = charArray[end];
charArray[end] = temp;

start++;
end--;
}
return new string(charArray);
}

5. Swapping Two Number without Using 3rd Variables.


static void Main()
{
Console.WriteLine("Enter First Number : ");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Second Number : ");
int y = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("*** Before Swapping ***");


Console.WriteLine($"X => {x} And Y => {y}");

x = x + y;
y = x - y;
x = x - y;

Console.WriteLine("*** After Swapping ***");


Console.WriteLine($"X => {x} And Y => {y}");
Console.ReadLine();
}

6. Write A Program for Palindrome


class Program
{
static void Main()
{
int a, b, sum = 0, temp;
Console.WriteLine("Enter A Number");
a = Convert.ToInt32(Console.ReadLine());
temp = a;
while (a > 0)
{
b = a % 10;
sum = (sum * 10) + b;
a = a / 10;
}
if (temp == sum)
Console.WriteLine($"{temp} => Number Is Palindrome");
else
Console.WriteLine($"{temp} => Number Not Palindrome");

Console.ReadLine();
}
}

MODIFIED BY SHUBHAM LAMBAT


97

7. Write a program to give Separate number of Character Count.


String is "Shubham Lambat"? Output - 'S': 1, 'h': 2, 'u': 1, 'b': 2, 'a': 3, 'm': 2, 'L': 1, 't': 1
static void Main()
{
string inputString = "Shubham Lambat";
Dictionary<char, int> characterCounts = CountCharacters(inputString);

Console.WriteLine($"Character counts in the string '{inputString}':");


foreach (var kvp in characterCounts)
{
Console.WriteLine($"'{kvp.Key}': {kvp.Value}");
}

Console.ReadLine();
}

static Dictionary<char, int> CountCharacters(string input)


{
Dictionary<char, int> counts = new Dictionary<char, int>();

foreach (char c in input)


{
if (char.IsLetterOrDigit(c)) // Count only letters and digits
{
if (counts.ContainsKey(c))
{
counts[c]++;
}
else
{
counts[c] = 1;
}
}
}
return counts;
}

8. Character Count Using LINQ

using System;
using System.Linq;

class Program
{
static void Main()
{
string strName = "Shubham Lambat";

var groupedChars = strName


.GroupBy(x => x)
.Where(x => x.Count() >= 1);

foreach (var group in groupedChars)


{
Console.WriteLine($"Character '{group.Key}' occurs {group.Count()} times.");
}

Console.ReadLine();
}
}

MODIFIED BY SHUBHAM LAMBAT


98

9. Find a Factorial of Number


Class Program
{
static void Main()
{
int num, fact = 1;
Console.WriteLine("Enter Number :- ");
num = Convert.ToInt32(Console.ReadLine());

for (int i = 1; i <= num; i++)


{
fact = fact * i;
}
Console.WriteLine($"Factorial Is :- {fact}");
Console.ReadLine();
}
}

10. Find the Output of This Program


static void Main()
{
try
{
// int a = 10; //Commented Line. If you don’t want error for ‘a’ variable then Uncomment this line
try
{
int a = a / 0; //Error :- use Unassigned local variable ‘a’.
}
catch() //Error :- Type Expected.
{
Console.WriteLine(" Inner Exception ");

// throw; // If you want to run Outer Exception also the Uncomment “throw” Keyword
}
}
catch(Exception ex)
{
Console.WriteLine(" Outer Exception ");
}
Console.ReadLine();
}

Output :- After Solving All Error The Output Is :- Inner Exception

11. Write a Program for Fibonacci Series.


static void Main()
{
Console.WriteLine("Enter a Number :- ");
int n = Convert.ToInt32(Console.ReadLine());
int first = 0, second = 1;

Console.Write($"Fibonacci Series of {n} : ");


for (int i = 0; i < n; i++)
{
Console.Write(first + " ");

int next = first + second;


first = second;
second = next;
}
}

MODIFIED BY SHUBHAM LAMBAT


99

12. Find the Output of This Program


class Program
{
class A
{
public virtual void print()
{
Console.WriteLine("Print A");
}
}

class B : A
{
public override void print()
{
Console.WriteLine("Print B");
}
}
static void Main()
{
A a1 = new A();
a1.print(); //Print A

A a2 = new B();
a2.print(); //Print B

B b1 = new B();
b1.print(); //Print B
.
B b2 = new A();
b2.print(); //Error
// This will give an error because you're trying to assign an instance of A to a variable of type B
}
}

13. Give Pattern like this in C#


**
** **
*** ***
**** ****
***** *****
public static void Main()
{
int rows = 6;
for (int i = 1; i<= rows; i++)
{
for (int j = 1; j<= i; j++)
{
Console.Write("*");
}
Console.Write(" ");
for (int k = 1; k<= i; k++)
{
Console.Write("*");
}
Console.WriteLine();
}
}

MODIFIED BY SHUBHAM LAMBAT


100

14. Explain Multilevel & Multiple Inheritance Example with Scenario.


- Multilevel Inheritance:
o Multilevel inheritance involves a chain of classes where one class is derived from
another, and then another class is derived from the second class.
o This creates a hierarchy of inheritance.
o Scenario:
 Consider a simple hierarchy for vehicles, where we have a base class Vehicle, a
derived class Car (inheriting from Vehicle), and another class SportsCar
(inheriting from Car).
o In this example, SportsCar inherits from Car, and Car inherits from Vehicle, creating a
multilevel inheritance hierarchy.

class Vehicle
{
public void Start()
{
Console.WriteLine("Vehicle started");
}
}
class Car : Vehicle
{
public void Drive()
{
Console.WriteLine("Car is driving");
}
}
class SportsCar : Car
{
public void Race()
{
Console.WriteLine("Sports car is racing");
}
}

static void Main()


{
SportsCar sportsCar = new SportsCar();
sportsCar.Start(); // Inherited from Vehicle
sportsCar.Drive(); // Inherited from Car
sportsCar.Race();
}

- Multiple Inheritance (Through Interfaces):


o Definition: C# does not support multiple inheritance of classes (i.e., a class cannot
directly inherit from multiple classes).
o However, it supports multiple inheritance through interfaces, where a class can
implement multiple interfaces.
o Scenario:
 IDriveable and IFlyable are interfaces that define behaviors.
 Car implements IDriveable because it can be driven.
 Airplane implements both IDriveable and IFlyable because it can be driven on the
ground and it can also fly.
MODIFIED BY SHUBHAM LAMBAT
101

o Example -
interface IDriveable
{
void Drive();
}
interface IFlyable
{
void Fly();
}
class Car : IDriveable
{
public void Drive()
{
Console.WriteLine("Driving a car...");
}
}

class Airplane : IDriveable, IFlyable


{
public void Drive()
{
Console.WriteLine("Driving an airplane on the ground...");
}
public void Fly()
{
Console.WriteLine("Flying an airplane...");
}
}

15. Explain Ref and Out scenario with Proper Example.


- In C#, ref and out are used to pass arguments to methods by reference, allowing the method to
modify the original value of the argument.
- The main difference between them is how they handle the input value of the argument:

Ref Parameter:
- Ref is used to pass arguments by reference.
- This means that any changes made to the parameter inside the method will also affect the original
variable outside the method.
- Scenario:
o When you want to pass a variable to a method, allow the method to modify it, and have
those modifications reflected in the calling code.
- Example:
void ModifyValue(ref int x)
{
x = x + 5;
}
// Usage
int number = 10;
ModifyValue(ref number);
Console.WriteLine(number); // Output: 15

- In this example, ModifyValue takes an int parameter x by reference. It adds 5 to x, which will
affect the original number variable because it was passed by reference using the ref keyword.
MODIFIED BY SHUBHAM LAMBAT
102

Out Parameter:
- Out is used when you want a method to return multiple values.
- The out parameter must be assigned a value inside the method before it returns.
- Scenario:
o When you need a method to return more than one value and you don't want to use a return
statement for each value.
- Example:
void GetValues(out int x, out int y)
{
x = 10;
y = 20;
}
// Usage
int firstValue, secondValue;
GetValues(out firstValue, out secondValue);
Console.WriteLine(firstValue); // Output: 10
Console.WriteLine(secondValue); // Output: 20

- In this example, GetValues takes two out parameters, x and y.


- Inside the method, x and y are assigned values, which are then accessible in the calling code after
the method call.

Key Points:
- When using Ref, the variable must be initialized before being passed to the method.
- When using Out, the variable does not need to be initialized before being passed to the method,
but it must be assigned a value inside the method.
- Out parameters are not required to be initialized by the caller before being passed to the method.
The method is responsible for initializing them.
- Both Ref and Out are useful in scenarios where you need to pass and modify variables in a
method, but they serve slightly different purposes.

16. Explain int.TryParse & int.Parse scenario with Proper Example.


- The int.TryParse method in C# is used to convert a string representation of a number to its integer
equivalent.
- Unlike int.Parse, which throws an exception if the conversion fails,
- int.TryParse returns a Boolean value indicating whether the conversion was successful or not.
- If successful, it also stores the converted value in an output variable.

int.TryParse
- int.TryParse attempts to convert a string representation of a number to an integer.
- If successful, it returns true and assigns the converted value to an output parameter.
- If the conversion fails, it returns false and assigns a default value (usually 0) to the output
parameter.
- Scenario:
o When you're not sure if the input string can be successfully converted to an integer, and
you want to handle conversion failures without throwing an exception.
- Example:

MODIFIED BY SHUBHAM LAMBAT


103

string input = "123";


int number;
if (int.TryParse(input, out number))
{
Console.WriteLine("Conversion successful. Value: " + number);
}
else
{
Console.WriteLine("Conversion failed. Using default value: " + number);
}
- In this example, the string "123" is successfully converted to an integer, and the TryParse method
returns true.
- The converted value is stored in the variable number.

int.Parse
- int.Parse attempts to convert a string representation of a number to an integer. If successful, it
returns the converted value.
- If the conversion fails (e.g., if the input string is not a valid number), it throws a FormatException.
- Scenario:
o When you're confident that the input string will be a valid integer, and you want to get the
converted value directly.
o If the conversion fails, an exception will be thrown.
- Example:
string input = "123";
int number = int.Parse(input);
Console.WriteLine("Conversion successful. Value: " + number);

- In this example, the string "123" is successfully converted to an integer using int.Parse.
- Since we're confident that the input is valid, we use int.Parse directly.
- If the input was not a valid number, a FormatException would be thrown.

17. Write a program to find whether the given input is prime or not.
static bool IsPrime(int number)
{
if (number < 2)
return false;

for (int i = 2; i <= Math.Sqrt(number); i++)


{
if (number % i == 0)
return false;
}

return true;
}
static void Main()
{
Console.Write("Enter a number: ");
int num = Convert.ToInt32(Console.ReadLine());

if (IsPrime(num))
Console.WriteLine(num + " is a prime number.");
else
Console.WriteLine(num + " is not a prime number.");
}

MODIFIED BY SHUBHAM LAMBAT


104

18. Write a Program to Print all Prime Numbers till Target. (take target from user)
class Program
{
static void Main()
{
Console.Write("Enter a target number: ");
int target = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Prime numbers up to " + target + ":");
for (int i = 2; i <= target; i++)
{
bool isPrime = true;
for (int j = 2; j <= i/2; j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
Console.Write(i + " ");
}
Console.WriteLine();
}
}

19. Write a program for coffee shop. display menu to user - Please choose coffee size 1-Small
2-Medium 3-Large Total bill amount
class Program
{
static void Main()
{
DisplayMenu();

Console.Write("Please Choose Coffee Size (1-Small, 2-Medium, 3-Large): ");


int size = Convert.ToInt32(Console.ReadLine());

double totalAmount = CalculateTotalPrice(size);


Console.WriteLine("Total Bill Amount: " + totalAmount + " Ru");
}
static void DisplayMenu()
{
Console.WriteLine("Coffee Menu:");
Console.WriteLine("1 - Small");
Console.WriteLine("2 - Medium");
Console.WriteLine("3 - Large");
}
static double CalculateTotalPrice(int size)
{
switch (size)
{
case 1: return 20.00; // Small
case 2: return 30.00; // Medium
case 3: return 40.00; // Large
default: return 0.00; // Invalid choice
}
}
}

MODIFIED BY SHUBHAM LAMBAT


105

20. Write a program to find if a given Number, is Armstrong.


class Program
{
static void Main()
{
Console.Write("Enter a number: ");
int number = Convert.ToInt32(Console.ReadLine());

int originalNumber = number;


int numDigits = number.ToString().Length;
int sum = 0;

while (number > 0)


{
int digit = number % 10;
sum += (int)Math.Pow(digit, numDigits);
number /= 10;
}

if (sum == originalNumber)
Console.WriteLine(originalNumber + " is an Armstrong number.");
else
Console.WriteLine(originalNumber + " is not an Armstrong number.");

Console.ReadLine();
}
}

21. Write a program which take input from user - print 'THREE' if that number is divisible by
3. print 'FIVE' if that number is divisible by 5. print 'THREEFIVE' if that number is
divisible by 3 & 5 both.

class Program
{
static void Main()
{
Console.Write("Enter a number: ");
int number = Convert.ToInt32(Console.ReadLine());

if (number % 3 == 0 && number % 5 == 0)


{
Console.WriteLine("THREEFIVE");
}
else if (number % 3 == 0)
{
Console.WriteLine("THREE");
}
else if (number % 5 == 0)
{
Console.WriteLine("FIVE");
}
else
{
Console.WriteLine("The number is not divisible by 3 or 5.");
}
}
}

MODIFIED BY SHUBHAM LAMBAT


106

22. Write a program to Reverse given Array.


class Program
{
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Console.WriteLine("Original Array:");
PrintArray(arr);

ReverseArray(arr);

Console.WriteLine("\nReversed Array:");
PrintArray(arr);
}

static void ReverseArray(int[] arr)


{
int left = 0;
int right = arr.Length - 1;

while (left < right)


{
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;

left++;
right--;
}
}
static void PrintArray(int[] arr)
{
foreach (int num in arr)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}

23. Write a program to print below series: (easy with 2 for loops but try with single for loop)
if input is 4 - o/p - 1 3 2 4 Also if input is 5 o/p - 1 3 5 2 4
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
int n = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= n; i++)
{
int num;
if (i % 2 == 0)
num = (n / 2) + (i / 2);
else
num = (i / 2) + 1;
Console.Write(num + " ");
}
}
}

MODIFIED BY SHUBHAM LAMBAT


107

24. Write a Program to sort an Array using Bubble Sort.


class Program
{
static void Main()
{
int[] arr = { 64, 34, 25, 12, 22, 11, 90 };
int n = arr.Length;

Console.WriteLine("Original Array:");
PrintArray(arr);

// Bubble Sort
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
Console.WriteLine("\nSorted Array:");
PrintArray(arr);
}
static void PrintArray(int[] arr)
{
foreach (int num in arr)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}

25. Write a program to find highest number from array.


class Program
{
static void Main()
{
int[] arr = { 12, 45, 78, 23, 56, 89, 34, 67 };
int highest = arr[0]; // Assume the first element is the highest
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] > highest)
{
highest = arr[i];
}
}
Console.WriteLine("The highest number in the array is: " + highest);
}
}

MODIFIED BY SHUBHAM LAMBAT


108

26. Print Fibonacci series using recursion.


class Program
{
static int Fibonacci(int n)
{
if (n <= 1)
return n;
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
static void PrintFibonacciSeries(int count)
{
for (int i = 0; i < count; i++)
{
Console.Write(Fibonacci(i) + " ");
}
}
static void Main()
{
Console.Write("Enter the number of terms in the Fibonacci series: ");
int count = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Fibonacci Series:");
PrintFibonacciSeries(count);
}
}

27. Write a program to find second highest number from array. (This program should be able
to change for nth highest number)
class Program
{
static void Main()
{
int[] arr = { 12, 45, 78, 23, 56, 89, 34, 67 };
int n = 2; // Change this to find the nth highest number

if (n > 0 && n <= arr.Length)


{
int nthHighest = FindNthHighest(arr, n);
Console.WriteLine("The " + n + "th highest number in the array is: " + nthHighest);
}
else
{
Console.WriteLine("Invalid value of n. Please choose a value between 1 and " + arr.Length);
}
}

static int FindNthHighest(int[] arr, int n)


{
Array.Sort(arr);
return arr[arr.Length - n];
}
}

MODIFIED BY SHUBHAM LAMBAT


109

28. Explain List & Dictionary with Proper Example.


List:
- A list is an ordered collection of elements of the same type.
- It allows you to add, remove, and access elements based on their position in the list.
Example:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating a list of integers
List<int> numberList = new List<int>();

// Adding elements to the list


numberList.Add(10);
numberList.Add(20);
numberList.Add(30);

// Accessing elements in the list


Console.WriteLine("Elements in the list:");
foreach (int num in numberList)
{
Console.WriteLine(num);
}

// Removing an element
numberList.Remove(20);

// Accessing elements after removal


Console.WriteLine("\nElements after removing 20:");
foreach (int num in numberList)
{
Console.WriteLine(num);
}
}
}

Dictionary:
- A dictionary is a collection of key-value pairs. It allows you to store and retrieve values based on
a unique key.
Example:
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating a dictionary of strings (key) and integers (value)
Dictionary<string, int> studentGrades = new Dictionary<string, int>();

// Adding key-value pairs


studentGrades["John"] = 85;
studentGrades["Jane"] = 90;
studentGrades["Bob"] = 75;

MODIFIED BY SHUBHAM LAMBAT


110

// Accessing values using keys


Console.WriteLine("Grades:");
Console.WriteLine("John: " + studentGrades["John"]);
Console.WriteLine("Jane: " + studentGrades["Jane"]);
Console.WriteLine("Bob: " + studentGrades["Bob"]);

// Updating a value
studentGrades["Jane"] = 95;

// Accessing updated value


Console.WriteLine("\nUpdated Grades:");
Console.WriteLine("Jane: " + studentGrades["Jane"]);
}
}

29. Write a Program for Method Overloading & Method Overriding & Method Hiding.
- Method Overloading:
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}

public double Add(double a, double b)


{
return a + b;
}
}

class Program
{
static void Main()
{
Calculator calculator = new Calculator();

int sumInt = calculator.Add(5, 3);


Console.WriteLine("Sum of integers: " + sumInt);

double sumDouble = calculator.Add(2.5, 3.5);


Console.WriteLine("Sum of doubles: " + sumDouble);
}
}

- Method Overriding:
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}
}
class Circle : Shape
{

MODIFIED BY SHUBHAM LAMBAT


111

public override void Draw()


{
Console.WriteLine("Drawing a circle");
base.Draw();
}
}

class Program
{
static void Main()
{
Shape shape = new Shape();
shape.Draw(); // Output: "Drawing a shape"

Circle circle = new Circle();


circle.Draw(); // Output: "Drawing a circle"
}
}

- Method Hiding:
class Shape
{
public void Draw()
{
Console.WriteLine("Drawing a shape");
}
}

class Circle : Shape


{
public new void Draw()
{
Console.WriteLine("Drawing a circle");
}
}

class Program
{
static void Main()
{
Shape shape = new Shape();
shape.Draw(); // Output: "Drawing a shape"

Circle circle = new Circle();


circle.Draw(); // Output: "Drawing a circle"

Shape shape = new Circle();


shape.Draw(); // Output: "Drawing a shape"

}
}

MODIFIED BY SHUBHAM LAMBAT


112

30. I Have one Interface in that there are Three Method and i will Implemented it in one class
but I want to Implement only Two Method how can I do in c#.
- Default Implementation (C# 8 and later):
o In C# 8.0 and later versions, you can provide a default implementation for interface
methods.
o This allows you to implement them in the interface itself, providing a fallback
implementation that can be used by classes that don't explicitly implement the method.
interface IExample
{
void Method1();
void Method2();
void Method3()
{
Console.WriteLine("Default Method3 implementation");
}
}

- Throw NotImplementedException:
o You can throw a NotImplementedException in the method you don't want to implement.
o This indicates that the method is intentionally not implemented.
class MyClass : IExample
{
public void Method1()
{
Console.WriteLine("Method1 implementation");
}
public void Method2()
{
Console.WriteLine("Method2 implementation");
}
public void Method3()
{
throw new NotImplementedException();
}
}

31. Explain with Example First and FirstOrDefault, Single & SingleOrDefault
First –
- First returns the first element in a sequence that satisfies a given condition.
- If no element satisfies the condition, it will throw an exception.
- Ex:
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 3, 5, 7, 9, 11 };
int firstOdd = numbers.First(n => n % 2 != 0);
Console.WriteLine("First odd number: " + firstOdd);
}
}

MODIFIED BY SHUBHAM LAMBAT


113

FirstOrDefault –
- FirstOrDefault is similar to First, but if no element satisfies the condition, it returns the default
value for the type (e.g., 0 for integers, null for reference types).
- Ex:
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 2, 4, 6, 8, 10 };
int firstOdd = numbers.FirstOrDefault(n => n % 2 != 0);
Console.WriteLine("First odd number: " + firstOdd);
}
}

Single –
- Single returns the only element in a sequence that satisfies a given condition.
- If there is more than one element that satisfies the condition or no elements match the condition, it
throws an exception.
- Ex:
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 3, 5, 7, 9, 11 };
int singleElement = numbers.Single(n => n == 7);
Console.WriteLine("Single element: " + singleElement);
}
}

SingleOrDefault
- SingleOrDefault is similar to Single, but if there are no elements or more than one element that
satisfies the condition, it returns the default value for the type (e.g., 0 for integers, null for
reference types).
- Ex:
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 2, 4, 6, 8, 10 };
int singleElement = numbers.SingleOrDefault(n => n == 7);
Console.WriteLine("Single element: " + singleElement);
}
}

MODIFIED BY SHUBHAM LAMBAT


114

32. I have collection of Persons I want to check person leave in Pune using LINQ Query
using System.Collections.Generic;
using System.Linq;
class Person
{
public string Name { get; set; }
public string Location { get; set; }
public bool HasTakenLeave { get; set; }
}
class Program
{
static void Main()
{
List<Person> persons = new List<Person>
{
new Person { Name = "John", Location = "Pune", HasTakenLeave = true },
new Person { Name = "Jane", Location = "Mumbai", HasTakenLeave = false },
new Person { Name = "Bob", Location = "Pune", HasTakenLeave = true },
new Person { Name = "Alice", Location = "Delhi", HasTakenLeave = true },
};
var personsInPune = persons.Where(p => p.Location == "Pune" && p.HasTakenLeave);
// Instead Of Where we can use Any

foreach (var person in personsInPune)


{
Console.WriteLine($"{person.Name} has taken leave in Pune.");
}
}
}

33. I have Class B & class C and in that two class there are 2 Same Name method also and C : B
in B class method we declare I variable and C class method use this I variable then if we
create an object of C class then which method get called
class B
{
protected int i = 10;
public virtual void Display()
{
Console.WriteLine("Method in class B");
}
}
class C : B
{
public override void Display()
{
Console.WriteLine("Method in class C");
Console.WriteLine("Value of i from class B: " + i);
}
}
static void Main()
{ // Output
C objC = new C(); // Method in class C
objC.Display(); // Value of i from class B: 10

MODIFIED BY SHUBHAM LAMBAT


115

34. I have Emp table in that there is a Name, also I have Address table in that there is a address.
Find emp who's have more than one address

SELECT Emp.Name, COUNT(Address.AddressID) AS AddressCount


FROM Emp
JOIN Address ON Emp.EmpID = Address.EmpID
GROUP BY Emp.Name
HAVING COUNT(Address.AddressID) > 1;

- This query performs the following steps:


o Joins the Emp table with the Address table using the EmpID field.
o Groups the results by Emp.Name.
o Uses the HAVING clause to filter out the groups where the count of addresses
(COUNT(Address.AddressID)) is greater than 1.

MODIFIED BY SHUBHAM LAMBAT

You might also like