C# Interview Questions
C# Interview Questions
If you look at the dictionary meaning of cohesion it means sticking things together which are of
the same types or substance.
Cohesion in software is a measure which tells how strongly related the responsibilities of a class
or module is.
For example below is a class diagram of a simple “customer” class. In this class diagram
“CustomerName” and “CustomerCode” are very much related to the “Customer” class but
watch the “SupplierCode” property it’s not related directly.
Cohesion can be at any level class level, module level etc. For example below is a simple
package diagram which groups classes in a “Customer” package.
Now Customers buy products and have multiple addresses. So it’s logical to have “Customer” ,
“Product” and “Address” in this namespace but look at “Exception” and “Logger” classes they
are needed but they are not logically the part of “Customer” namespace.
So below grouping would look more logical and appropriate.
Coupling is a contrast to cohesion. Coupling says how much the classes and modules directly
depend on each other. A good architecture is that architecture where change in one place
should not lead to changes all over the places. If classes are directly connected with each other,
then change in one class leads to changes in other class as well, so a loose coupling is more
desirable.
Below is a simple class diagram which shows “Customer” and “Address” relationship. In the first
section of the diagram “Customer” and “Address” classes are directly connected. In other
words changes in “Address” class will lead to change in “Customer” class as well. So rather than
these classes talk with each other directly they can talk via interfaces which the next section of
the diagram shows. This is termed as decoupling.
Coupling and cohesion are measured using ordinal measurement: – LOW and HIGH. So we have
low cohesion, high cohesion, low coupling and high coupling. Below table explains the same in
detail.
High Low
Classes and modules have related and logical elements Elements are unrelated
Cohesion
together. This is a desirable situation. and are not desirable.
In other words, good software architectures have high cohesion and low coupling.
Inversion of Control
C# Indexer
https://www.youtube.com/watch?v=HdtEQqu0yOY
Indexer help us to l simplify the way we are getting collection from the class
https://www.youtube.com/watch?v=hF-6eudOD0M
https://www.youtube.com/watch?v=lYdcY5zulXA
In OUT we need to compulsorily initialize variables inside the function for REF we do not need to do the
same.
REF helps to pass data two ways i.e. from caller to callee and back. While OUT is one way it just passes
data from callee to caller.
http://www.dotnetinterviewquestions.in/article_what-is-the-difference-between-out-and-ref-c-
interview-questions_255.html#.VgpKBaKrySA.facebook
//IS str1 variable type of string
https://www.youtube.com/watch?v=vNPBWNNlDwM&feature=player_embedded
Const: Compile time Constant, value will be assigned at the time of declaration itself.
Extension Methods
https://www.youtube.com/watch?v=Iu7OrL6vCOw&feature=player_embedded
Extension Methods: Help you to create a methods without changing the source code
Anonymous Methods
https://www.youtube.com/watch?v=drgsIO5M8ok
Delegate:
Anonymous Method: Method which can be coded inline
It avoids the writing a separate method for simple code and need to point
delegate to that method
Delegate:
https://www.youtube.com/watch?v=ifbYA8hyvjc
What is the benefit of calling method in directly using delegate (via pointer)?
https://www.youtube.com/watch?v=8o0O-vBS8W0
FUNC<>(Generic delegate): Func is a readymade delegate we can pass input and get output.
Action<>: Action Delegate used when we want to pass the input and no output expected.
Predicate<>: it is a extension to the Func<> it is used for checking purpose. Return type is always
Boolean type by taking any input type.
Expression tree
https://www.youtube.com/watch?v=4fju3xcm21M
What is Tuple in C#?
Basically, a tuple (Tuple in C#) is an ordered sequence, immutable, fixed-size and of heterogeneous
objects, i.e., each object being of a specific type. The tuples are not new in programming
http://www.codeproject.com/Articles/193537/C-Tuples
Difference between IEnumerable and IEnumerator.
https://www.youtube.com/watch?v=jd3yUjGc9M0
IEnumerable and IEnumerator help to loop through the collection (list, array list)
Biggest difference is IEnumerator remembers the state where as IEnumerable not remembers the state.
IEnumerable used when we want to loop in the sequentially and we don’t want to remember where the
current cursor and we are going to use IEnumerable.
IEnumerator is useful when you want to pass the value from one function to other function and we want
to remember in t=what position cursor is then we are going to use the IEnumerator.
IEnumerable IQueryable
Namespace System.Collections Namespace Syste.LINQ
Derives from No base interface Derives from IEnumerable
Deferred
Supported Supported
Execution
Lazy Loading Not Supported Supported
While querying data from database, While querying data from database, IQueryable
How does it work
IEnumerable execute select query on execute select query on server side with all
server side, load data in-memory on
client side and then filter data. Hence filters. Hence does less work and becomes fast.
does more work and becomes slow.
LINQ to Object and LINQ to XML
Suitable for LINQ to SQL queries.
queries.
Supports using CreateQuery and Execute
Custom Query Doesn’t supports.
methods.
Extension mehtod Extension methods supported in Extension methods supported in IEnumerable
parameter IEnumerable takes functional objects. takes expression objects i.e. expression tree.
when querying data from in-memory when querying data from out-memory (like
When to use
collections like List, Array etc. remote database, service) collections.
Best Uses In-memory traversal Paging
VAR type will be decided by the type assigned by the value in the right hand side at compile time.
Ex:
Var I=123
If we try to assign I=”Shiva” we will get compile error already I is Integer type.
VAR keywords used when class names are big and to make readable and shorter code
LINQ
Var vs Dynamic in c#
https://www.youtube.com/watch?v=SsvJY33vc5g
In the above example VAR x at compile time only we comes to know it is a string type and we can find
length of string.
When we use the dynamic key we won’t get the compile time error and build succeds, but in run time
we will get error because we are given length instead of “Length”
What is TPL ( Task Parallel Library) and how it differs from threads (c#
interview questions) ?
https://www.youtube.com/watch?v=No7QqSc5cl8
Prove that only 1 instance of the object is created for static classes?
https://www.youtube.com/watch?v=N9xwjZ4mMvw
Back Ground Thread: Background thread will exit, when the main application will quit.
Multithreading and thread safe objects.
https://www.youtube.com/watch?v=J-jNcUhi9xw
Thread Safe:
Lock: will lock the code and make sure only one thread can execute the Locked code.
What is AutoResetEvent and ManualResetEvent
https://www.youtube.com/watch?v=xaaRBh07N34
What are Async and Await
https://www.youtube.com/watch?v=V2sMXJnDEjM
What is the use of private constructor ?
https://www.youtube.com/watch?v=8xyXjdUtmfQ&list=PL5753E1DFB675A268&index=2
Association: Both the objects used each other, but they can have own life style. (has a Relation)
Aggregation: is a single owner of the object (There is a single owner of child object)
Composition: both the objects depend each other, one goes off and other goes off.
https://www.youtube.com/watch?v=1Q4I63-hKcY
Boyce-Codd Normal Form (BCNF) is one of the forms of database normalization. A database table is in
BCNF if and only if there are no non-trivial functional dependencies of attributes on anything other than a
superset of a candidate key. BCNF is also sometimes referred to as 3.5NF, or 3.5 Normal Form.
SQL SERVER – Stored Procedure
Optimization Tips – Best Practices
We will go over how to optimize Stored Procedure with making simple changes in the code. Please
note there are many more other tips, which we will cover in future articles.
Include SET NOCOUNT ON statement: With every SELECT and DML statement, the SQL
server returns a message that indicates the number of affected rows by that statement. This
information is mostly helpful in debugging the code, but it is useless after that. By setting
SET NOCOUNT ON, we can disable the feature of returning this extra information. For
stored procedures that contain several statements or contain Transact-SQL loops, setting
SET NOCOUNT to ON can provide a significant performance boost because network traffic
is greatly reduced.
CREATE PROC dbo.ProcName
AS
SET NOCOUNT ON;
--Procedure code here
SELECT column1 FROMdbo.TblTable1
-- Reset SET NOCOUNT to OFF
SET NOCOUNT OFF;
GO
Use schema name with object name: The object name is qualified if used with schema
name. Schema name should be used with the stored procedure name and with all objects
referenced inside the stored procedure. This help in directly finding the complied plan
instead of searching the objects in other possible schema before finally deciding to use a
cached plan, if available. This process of searching and deciding a schema for an object
leads to COMPILE lock on stored procedure and decreases the stored procedure’s
performance. Therefore, always refer the objects with qualified name in the stored procedure
like
SELECT * FROM dbo.MyTable -- Preferred method
-- Instead of
SELECT * FROM MyTable -- Avoid this method
--And finally call the stored procedure with qualified name like:
EXEC dbo.MyProc -- Preferred method
--Instead of
EXEC MyProc -- Avoid this method
Do not use the prefix “sp_” in the stored procedure name: If a stored procedure name
begins with “SP_,” then SQL server first searches in the master database and then in the
current session database. Searching in the master database causes extra overhead and
even a wrong result if another stored procedure with the same name is found in master
database.
Use IF EXISTS (SELECT 1) instead of (SELECT *): To check the existence of a record in
another table, we uses the IF EXISTS clause. The IF EXISTS clause returns True if any
value is returned from an internal statement, either a single value “1” or all columns of a
record or complete recordset. The output of the internal statement is not used. Hence, to
minimize the data for processing and network transferring, we should use “1” in the SELECT
clause of an internal statement, as shown below:
IF EXISTS (SELECT 1 FROM sysobjects
WHERE name = 'MyTable' AND type ='U')
DECLARE @Query VARCHAR(100)
DECLARE @Age INT
SET @Age = 25
SET @Query = 'SELECT * FROM dbo.tblPerson WHERE Age = ' +CONVERT(VARCHAR(3),@Age)
EXEC (@Query)
If we again execute the above batch using different @Age value, then the execution plan for
SELECT statement created for @Age =25 would not be reused. However, if we write the above
batch as given below,
DECLARE @Query NVARCHAR(100)
SET @Query =N'SELECT * FROM dbo.tblPerson WHERE Age = @Age'
EXECUTE sp_executesql @Query, N'@Age int', @Age = 25
the compiled plan of this SELECT statement will be reused for different value of @Age parameter.
The reuse of the existing complied plan will result in improved performance.
Try to avoid using SQL Server cursors whenever possible: Cursor uses a lot of
resources for overhead processing to maintain current record position in a recordset and this
decreases the performance. If we need to process records one-by-one in a loop, then we
should use the WHILE clause. Wherever possible, we should replace the cursor-based
approach with SET-based approach. Because the SQL Server engine is designed and
optimized to perform SET-based operation very fast. Again, please note cursor is also a kind
of WHILE Loop.
Keep the Transaction as short as possible: The length of transaction affects blocking and
deadlocking. Exclusive lock is not released until the end of transaction. In higher isolation
level, the shared locks are also aged with transaction. Therefore, lengthy transaction means
locks for longer time and locks for longer time turns into blocking. In some cases, blocking
also converts into deadlocks. So, for faster execution and less blocking, the transaction
should be kept as short as possible.
Use TRY-Catch for error handling: Prior to SQL server 2005 version code for error
handling, there was a big portion of actual code because an error check statement was
written after every t-sql statement. More code always consumes more resources and time. In
SQL Server 2005, a new simple way is introduced for the same purpose. The syntax is as
follows:
BEGIN TRY
--Your t-sql code goes here
END TRY
BEGIN CATCH
--Your error handling code goes here
END CATCH