Interview Questions

Dot Net Questions

Explain ACID rule of thumb for transactions ?

Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).

**************************************************************************************************************************************************

Do you know Extension methods? Can we define extension methods for static class?

  1. Extension methods are very well known by most of the developers, by definition, Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
  2. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
  3. Read this MSDN Guide to know how to implement and call a Custom Extension Method.
  4. Googly comes when interviewer asks , “Can we define extension method for a class which itself is a static class?”
  5. To answer this, we cannot define extension methods for static class because Extension methods require an instance of an object and we cannot instantiate a static class.
    It will throw following error :
    “static types cannot be used as parameters”.

**************************************************************************************************************************************************

Difference between Implicit and Explicit Interface ?

http://blogs.msdn.com/b/mhop/archive/2006/12/12/implicit-and-explicit-interface-implementations.aspx

http://www.iminfo.in/post/advanced-c-sharp-dot-net-interview-questions-for-experienced–developers

**************************************************************************************************************************************************

LINQ – How to find the object with the largest value on one of its properties ?

The first thing to remember when using LINQ to Objects methods is to add the namespace System.Linq to the list of using statements in our class. This allows us to use the extension methods for IEnumerable<T> defined on that namespace.

Most of the examples I found related to this were using arrays of ints and the Max() method but that gives you the largest value found, not the object that contains that value.

Let’s assume we have a list of CampaignInfoData objects that have one property named NumberOfBatches of type int.

private List<CampaignInfoData> m_campaignInfosList = new List<CampaignInfoData>();

Using the Max method, we can get the largest number of batches in one campaign:

int largestNumberOfBatches = m_campaignInfosList.Max( f => f.NumberOfBatches );

but what I wanted was to get the campaign object with the largest number of batches. To get that, we can use the Aggregate method:

CampaignInfoData largestCampaign = m_campaignInfosList.Aggregate( ( seed, f ) => f.NumberOfBatches > seed.NumberOfBatches ? f : seed );

The Aggregate method accepts a lambda expression with two parameters. The first parameter holds the result of the previous lambda function execution, and the second is the current item on the list at a specific point in time.

The method traverses the list from beginning to end, and for each element, executes the code to the right of the => symbol on the lambda expression. After that, it puts the result value on the first parameter (seed) and moves to the next element on the list.

When it reaches the last element, the Aggregate method returns the result of the last lambda function execution.

This gives us the campaign object we were looking for without affecting the order of the elements on the list.

**************************************************************************************************************************************************

What are the New features have been added to C# language with version 2.0 of .NET ? 

• Generics
• Iterators
• Anonymous methods
• Partial classes

**************************************************************************************************************************************************

What’s the difference between ‘cast’ syntax and using the ‘as’ operator?

Using the as operator differs from a cast in C# in three important ways:
1. It returns null when the variable you are trying to convert is not of the requested type or in it’s inheritance chain, instead of throwing an exception.
2. It can only be applied to reference type variables converting to reference types.
3. Using as will not perform user-defined conversions, such as implicit or explicit conversion operators, which casting syntax will do.

**************************************************************************************************************************************************

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

The first one performs a deep copy of the array, the second one is shallow.

**************************************************************************************************************************************************

What is deep copy vs. shallow copy ?

Shallow Copy
Shallow copying is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type –> a bit-by-bit copy of the field is performed; for a reference type –> the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep Copy
Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type –> a bit-by-bit copy of the field is performed. If a field is a reference type –> a new copyof the referred object is performed.

Note: the classes to be cloned must be flagged as [Serializable].

**************************************************************************************************************************************************

What is Dll Hell problem ?

This is a problem in loading a specific dll (class id, version number, path etc). For example, if I build test.dll v1.0.0.0 and deploying it in c:\MyProg. My application App1 and App2 are using the methods in that dll. And there is a requirement to change something in App1 and I supposed to change test.dll also for the same requirement. Once I finished with all my changes, I will be deploying them in the appropriate locations. Now, the older dll will be overwritten. And my App2 will look for test.dll of older version and since it is not there it will not work. This is a scenario for dll hell issue.
.Net Framework provides operating systems with a Global Assembly Cache. This Cache is a repository for all the .Net components that are shared globally on a particular machine. When a .Net component is installed onto the machine, the Global Assembly Cache looks at its version, its public key, and its language information and creates a strong name for the component. The component is then
registered in the repository and indexed by its strong name, so there is no confusion between different versions of the same component, or DLL.

**************************************************************************************************************************************************

What is Agile software development ?

Agile software development is a group of software development methodologies based on iterative and incremental development, where requirements and solutions evolve through collaboration between self-organizing, cross-functional teams. It promotes adaptive planning, evolutionary development and delivery, a time-boxed iterative approach, and encourages rapid and flexible response to change.

Software development process : Activities and steps

 Requirements
 Specification
 Architecture
 Design
 Implementation
 Testing
 Deployment
 Maintenance

**************************************************************************************************************************************************

What is xmlns ? 

xmlns is an XML, not necessarily XAML, construct which defines a namespace in which to resolve xml element names. Because it is defined without a qualifier, it is defining the default namespace by which an XML element name should be resolved.
In XAML you usually see the following entry. It defines the default namespace to be essentially WPF and all XML element names are hence resolved as WPF elements.
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

It’s also common to see non-default namespaces such as the following.
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

This defines a qualified namespace for XAML specific elements. If you want an element or attribute name to be resolved within this namespace you should qualify it with x. For example
<StackPanel x:Name=”foo” />

There are 2 name resolutions in this definition.

1. StackPanel – Because it’s an unqualified name, it will be resolved in the default namespace which is WPF
2. x:Name – Name is qualified with x and will be resolved within the XAML document.

**************************************************************************************************************************************************

The difference between ‘out’ and ‘ref’ ?

1. The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed.

2. The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument.

3. As a minor difference, an out parameter needs not be initialized.

Example for out:
string a, b;
person.GetBothNames(out a, out b);

where GetBothNames is a method to retrieve two values atomically, the method won’t change behaviour whatever a and b are. If the call goes to a server in Hawaii, copying the initial values from here to Hawaii is a waste of bandwidth.

A similar snippet using ref:
string a = String.Empty, b = String.Empty;
person.GetBothNames(ref a, ref b);

**************************************************************************************************************************************************

What is Assemblies ?

In addition to metadata, assemblies also have a special file called Manifest. It contains information about the current version of the assembly and other related information.

Assemblies have the following properties:

• Assemblies are implemented as .exe or .dll files.
• You can share an assembly between applications by placing it in the Global Assembly Cache.
• Assemblies must be strong-named before they can be placed in the Global Assembly Cache. For more information, see Strong-Named Assemblies.
• Assemblies are only loaded into memory if they are required.
• You can programmatically obtain information about an assembly using reflection. For more information, see the topic Reflection.
• If you want to load an assembly only to inspect it, use a method such as ReflectionOnlyLoadFrom.
• You can use two versions of the same assembly in a single application. For more information, see extern alias.

**************************************************************************************************************************************************

How can we make a thread sleep for infinite period ?

You can also place a thread into the sleep state for an indeterminate amount of time by
calling Thread.Sleep (System.Threading.Timeout.Infinite).To interrupt this sleep you can
call the Thread.Interrupt method

**************************************************************************************************************************************************

What the way to stop a long running thread ?

To stop a long running thread use the following line of code:
System.Threading.Thread.Abort

**************************************************************************************************************************************************

What is ReaderWriterLockSlim ?

Represents a lock that is used to manage access to a resource, allowing multiple threads for reading or exclusive access for writing

**************************************************************************************************************************************************

Avoid deadlocks in a multithreaded process ?

There are four conditions which must occur for deadlock to occur:

1. Mutual exclusion condition: a resource that cannot be used by more than one process at a time
2. Hold and wait condition: processes already holding resources may request new resources
3. No preemption condition: No resource can be forcibly removed from a process holding it, resources can be released only by the   explicit action of the process
4. Circular wait condition: two or more processes form a circular chain where each process waits for a resource that the next process in the chain holds

**************************************************************************************************************************************************

Difference between a process and a thread ?

Process:

An executing instance of a program is called a process.

Some operating systems use the term ‘task‘ to refer to a program that is being executed.

1. A process is always stored in the main memory also termed as the primary memory or random access memory.
Therefore, a process is termed as an active entity. It disappears if the machine is rebooted.

2. Several process may be associated with a same program.

3. On a multiprocessor system, multiple processes can be executed in parallel.

4. On a uni-processor system, though true parallelism is not achieved, a process scheduling algorithm is applied and the processor is scheduled to execute each process one at a time yielding an illusion of concurrency.

Example: Executing multiple instances of the ‘Calculator’ program. Each of the instances are termed as a process.

Thread:

A thread is a subset of the process.

It is termed as a ‘lightweight process’, since it is similar to a real process but executes within the context of a process and shares the same resources allotted to the process by the kernel (See kquest.co.cc/2010/03/operating-system for more info on the term ‘kernel’).

1. Usually, a process has only one thread of control – one set of machine instructions executing at a time.

2. A process may also be made up of multiple threads of execution that execute instructions concurrently.

3. Multiple threads of control can exploit the true parallelism possible on multiprocessor systems.

4. On a uni-processor system, a thread scheduling algorithm is applied and the processor is scheduled to run each thread one at a time.

5. All the threads running within a process share the same address space, file descriptor, stack and other process related attributes.

Since the threads of a process share the same memory, synchronizing the access to the shared data withing the process gains unprecedented importance.

**************************************************************************************************************************************************

What is QueueUserWorkItem ?

To use QueueUserWorkItem, simply call this method with a delegate that you want to run on a pooled thread:

static void Main()
{
ThreadPool.QueueUserWorkItem (Go);
ThreadPool.QueueUserWorkItem (Go, 123);
Console.ReadLine();
}

static void Go (object data) // data will be null with the first call.
{
Console.WriteLine (“Hello from the thread pool! ” + data);
}

Hello from the thread pool!
Hello from the thread pool! 123

Our target method, Go, must accept a single object argument (to satisfy the WaitCallback delegate). This provides a convenient way of passing data to the method, just like with ParameterizedThreadStart. Unlike with Task,QueueUserWorkItem doesn’t return an object to help you subsequently manage execution. Also, you must explicitly deal with exceptions in the target code — unhandled exceptions will take down the program.

**************************************************************************************************************************************************

What is Asynchronous delegates ?

ThreadPool.QueueUserWorkItem doesn’t provide an easy mechanism for getting return values back from a thread after it has finished executing. Asynchronous delegate invocations (asynchronous delegates for short) solve this, allowing any number of typed arguments to be passed in both directions. Furthermore, unhandled exceptions on asynchronous delegates are conveniently rethrown on the original thread (or more accurately, the thread that callsEndInvoke), and so they don’t need explicit handling.

Don’t confuse asynchronous delegates with asynchronous methods (methods starting withBegin or End, such as File.BeginRead/File.EndRead). Asynchronous methods follow a similar protocol outwardly, but they exist to solve a much harder problem.

Here’s how you start a worker task via an asynchronous delegate:
1. Instantiate a delegate targeting the method you want to run in parallel (typically one of the predefined Funcdelegates).
2. Call BeginInvoke on the delegate, saving its IAsyncResult return value.

BeginInvoke returns immediately to the caller. You can then perform other activities while the pooled thread is working.
3. When you need the results, call EndInvoke on the delegate, passing in the saved IAsyncResult object.
In the following example, we use an asynchronous delegate invocation to execute concurrently with the main thread, a simple method that returns a string’s length:

static void Main()
{
Func<string, int> method = Work;
IAsyncResult cookie = method.BeginInvoke (“test”, null, null);
//
// … here’s where we can do other work in parallel…
//
int result = method.EndInvoke (cookie);
Console.WriteLine (“String length is: ” + result);
}

static int Work (string s) { return s.Length; }

EndInvoke does three things. First, it waits for the asynchronous delegate to finish executing, if it hasn’t already. Second, it receives the return value (as well as any ref or out parameters). Third, it throws any unhandled worker exception back to the calling thread.

**************************************************************************************************************************************************

How can you create responsive UI without using threads ?

Expected answer: By splitting work in small pieces and queuing them on the message loop of the UI

**************************************************************************************************************************************************

What is Design patterns ?

Design patterns recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges.

They are categorized in three groups: Creational, Structural, and Behavioral. Here you will find information on these important patterns.

Creational Patterns

Abstract Factory : Creates an instance of several families of classes
Factory Method : Creates an instance of several derived classes
Prototype : A fully initialized instance to be copied or cloned
Singleton : A class of which only a single instance can exist

Structural Patterns

Facade : A single class that represents an entire subsystem
Proxy : An object representing another object

Behavioral Patterns

Command : Encapsulate a command request as an object
Iterator : Sequentially access the elements of a collection
Template Method : Defer the exact steps of an algorithm to a subclass

**************************************************************************************************************************************************

How can you call Mouse Handing in MVVM if you don’t want your handler in View Code behind file ?

Basically, per the accepted answer to that question, you’ll have to use the AttachedCommandBehavior rather than a MouseBinding to achieve what you want. In my opinion that would be the best way if this is something you do a lot.

Alternatively, if this is the only case in your code that you are doing this I don’t think it would hurt to handle the event in code behind and call the view model’s command from there. MVVM purists might disagree, but sometimes it’s best to do things the simple way rather than tying yourself in knots trying to keep your code behind completely empty!

private void textBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
MyViewModel vm = this.DataContext as MyViewModel;

vm.MethodToExecute(…);
}

Please, code behind is not a bad thing at all. Unfortunately, quite a lot people in the WPF community got this wrong.

MVVM is not a pattern to eliminate the code behind. It is to separate the view part (appearance, animations, etc.) from the logic part (workflow). Furthermore, you are able to unit test the logic part.

I know enough scenarios where you have to write code behind because data binding is not a solution to everything. In your scenario I would handle the DoubleClick event in the code behind file and delegate this call to the ViewModel.

**************************************************************************************************************************************************

Difference between GridView and ListView?

The GridView control is used to display the values of a data source in a table. Each column represents a field, while each row represents a record. The GridView control supports the following features:
• Binding to data source controls, such as SqlDataSource.
• Built-in sort capabilities.
• Built-in update and delete capabilities.
• Built-in paging capabilities.
• Built-in row selection capabilities.
• Programmatic access to the GridView object model to dynamically set properties, handle events, and so on.
• Multiple key fields.
• Multiple data fields for the hyperlink columns.
• Customizable appearance through themes and styles.
• To learn about the other data-bound controls that are available in ASP.NET, see ASP.NET Data-Bound Web Server Controls Overview.

The ListView control is used to display the values from a data source. It resembles the GridView control, except that it displays data by using user-defined templates instead of row fields. Creating your own templates gives you more flexibility in controlling how the data is displayed.
The ListView control supports the following features:
• Support for binding to data source controls such as SqlDataSource, LinqDataSource, and ObjectDataSource.
• Customizable appearance through user-defined templates and styles.
• Built-in sorting capabilities.
• Built-in update and delete capabilities.
• Built-in insert capabilities.
• Support for paging capabilities by using a DataPager control.
• Built-in item selection capabilities.
• Programmatic access to the ListView object model to dynamically set properties, handle events, and so on.
• Multiple key fields.

**************************************************************************************************************************************************

What are the various ways for a service to connect to Sql Server ?

First Way :

string myConnectionString = “Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True”;

public List<Person> GetAllPersons()
{
List<Person> persons = new List<Person>();
using (SqlConnection con = new SqlConnection(myConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = “GetAllPersons“;
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;

cmd.Parameters.Add(“@ID“, System.Data.SqlDbType.Int).Value = person.ID;
cmd.Parameters.Add(“@NAME“, System.Data.SqlDbType.VarChar).Value = person.Name;
cmd.Parameters.Add(“@CITY“, System.Data.SqlDbType.VarChar).Value = person.City;
cmd.Parameters.Add(“@PHONENO“, System.Data.SqlDbType.VarChar).Value = person.PhoneNo;

con.Open();

SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Person person = new Person();
person.ID = int.Parse(reader[“ID“].ToString());
person.Name = Convert.ToString(reader[“NAME“]);
person.City = Convert.ToString(reader[“CITY“]);
person.PhoneNo = Convert.ToString(reader[“PHONENO“]);

persons.Add(person);
}
}
}

return persons;

}

Second Way :

string s_command = “SELECT Code,Name,Country FROM customers”;

SqlConnection connection = new SqlConnection();
connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[“ConnStr”].ToString();
connection.ConnectionString = “Data Source=192.168.10.9,1433;Initial Catalog=Customers;Network Library=DBMSSOCN;User ID=temporalguest;Password=”;”;
SqlCommand command = new SqlCommand();
command.CommandText = s_command;
command.Connection = connection;

DataSet ObjDataset = new DataSet();
SqlDataAdapter objAdapater = new SqlDataAdapter();
objAdapater.SelectCommand = objCommand;

objAdapater.Fill(ObjDataset);
clsCustomer objCustomer = new clsCustomer();
objCustomer.CustomerCode = ObjDataset.Tables[0].Rows[0][0].ToString();
objCustomer.Customer = ObjDataset.Tables[0].Rows[0][1].ToString();
objConnection.Close();
return objCustomer;
objAdapater.Fill(ObjDataset,”Table”);
List1.DataContext = ds.Tables[0].DefaultView;
objConnection.Close();

**************************************************************************************************************************************************

Difference between DataSet and DataReader ?

Some developers say that DataSet is better and some says DataReader is better. But, both are Microsoft developments but are depend upon the situation that where DataReader and DataSet are useful. DataReader is faster than DataSet, DataSet is complex where as DataReader is lightweight, let’s discussed the both with example.

DataSet

  1. Dataset is disconnected architecture.
  2. Data set cannot directly accessible to database.
  3.  DataAdapter is used to communicate between DataSet and database.
  4. DataSet can hold more than one table.
  5. Primary and foreign keys can be created in DataSet tables.
  6. XML technology is used to work dataset.
  7. DataSet is present inside System.Data namespace.
  8. There are two type of DataSet
    1. Typed DataSet
    2.  Untyped DataSet
  9. DataSet will retrieve the data into memory and return the database connection to the connection pool.
  10. DataSet changes can directly update to database
  11. DataSet can be loaded from
    1. Microsoft SQL Server
    2. Oracle Database
    3. Microsoft Access Database.
  12. When you have to delete, edit and update records then DataSet is good choice.

Example

using (SqlConnection conn = new SqlConnection(“CONNECTIONSTRING”))

{

SqlDataAdapter DataAd = new SqlDataAdapter(“SELECT * FROM TABLE”, conn);

System.Data.DataSet ds = new System.Data.DataSet();

DataAd.Fill(ds);

foreach (System.Data.DataRow dr in ds.Tables[0].Rows)

{

Response.Write(String.Format(“{0}”, dr[0].ToString() + “<br>”));

}

}

DataReader

  1. DataReader is connected architecture.
  2. DataReader is read only.
  3. DataReader is faster than DataSet.
  4. DataReader keeps the connection locked open until processing is complete.
  5. DataReader is present inside System.Data.SqlClient namespace.
  6. DataReader is useful when you have to fetch thousand of records from database.

Example

using (SqlConnection connection = new SqlConnection(“CONNECTIONSTRING”))

{

connection.Open();

SqlCommand command = new SqlCommand(“SELECT * FROM TABLE”, connection);

SqlDataReader reader = command.ExecuteReader();

while (reader.Read())

{

Response.Write(String.Format(“{0}”, reader[0].ToString() + “<br>”));

}

}

Disconnected architecture is a method of retrieving a record set from the database and storing it giving you the ability to do many CRUD (Create, Read, Update, Delete) operations on the data in memory, then it can be re-synchronized with the database when reconnecting.  A method of using disconnected artitecture is using a DataSet.

Connected architecture is when you constaintly make trips to the database for any CRUD operation you wish to do. this creates more traffic to the database but is normally much faster as you should be doing smaller transactions.

**************************************************************************************************************************************************

What is the difference between Execute Scalar , Execute Reader and ExecuteNonQuery?

ExecuteScalar is typically used when your query returns a single value. If it returns more, then the result is the first column of the first row. An example might be SELECT @@IDENTITY AS 'Identity'.Use for retriving 1 row 1 col value. i.e. Single value. eq: for retriving aggregate fucntion. It is faster than other ways of retriving a single value from DB.

ExecuteReader is used for any result set with multiple rows/columns (e.g., SELECT col1, col2 from sometable). Use for accessing data.It provides a forward only, read-only, connected recordset.

ExecuteNonQuery is typically used for SQL statements without results (e.g., UPDATE, INSERT, etc.). Use for data manipulation such as insert, update , delete.

**************************************************************************************************************************************************

What is delegate

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object.

A delegate can be seen as a placeholder for a/some method(s).

By defining a delegate, you are saying to the user of your class “Please feel free to put any method that match this signature here and it will be called each time my delegate is called“.

Typical use is of course events. All the OnEventX delegate to the methods the user defines.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Thanks for your comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: