Skip to main content

Common C# Interview Questions/Answers and Thought Experiments

Common C# Interview Questions/Answers and Thought Experiments
Hello,
This file contains some common Questions/Answers for C# Interview, Please update it accordingly, so we all can benefit from it.
Some Thought Experiements (These are all available for Microsoft Certified Porfessional Exam Ref)
General C# Questions (Multiple sources)
Thought Expermiment 1:
You need to build a new application, and you look into multithreading capabili-ties. Your application consists of a client application that communicates with a web server.
1. Explain how multithreading can help with your client application.
2. What is the difference between CPU and I/O bound operations?
3. Does using multithreading with the TPL offer the same advantages for your server application?
Observations:
1. Multithreading can improve the responsiveness in a client application. The UI thread can process requests from the user while background threads execute other operations.
2. A CPU-bound operation needs a thread to execute. In a client application, it can make sense to execute a CPU-bound operation on another thread to improve responsiveness. In a server application, you don’t want an extra thread for a CPU-bound operation. Asynchronous I/O operations don’t require a thread while executing. Using asynchronous I/O frees the current thread to do other work and improves scalability.
3. Using multithreading in a server environment can help you distribute operations over multiple CPUs. This way, you can improve performance. Using the TPL to create another thread to execute a CPU-bound operation while the originating thread has to wait for it won’t help you with increasing performance.
Thought Expermiment 2: (Implementing Multi-Threading)
You are experiencing deadlocks in your code. It’s true that you have a lot of locking statements and you are trying to improve your code to avoid the deadlocks.
1. How can you orchestrate your locking code to avoid deadlocks?
2. How can the Interlocked class help you?
Observations:
1. It’s important to make sure that all locking follows the same order when locking multiple objects. As soon as you start locking dependent objects in different orders, you start getting deadlocks.
2. The Interlocked class can help you to execute small, atomic operations without the need for locking. When you use locking a lot for these kind of operations, you can replace them with the Interlocked statement.
Thought Expermiment 3: (Choosing Program-flow statemens)
You are updating an old C#2 console application to a WPF C#5 application. The application is used by hotels to keep track of reservations and guests coming and leaving. You are going through the old code base to determine whether there is code that can be easily reused. You notice a couple of things:
■■ The code uses the goto statement to manage flow.
■■ There are a lot of long if statements that map user input.
■■ The code uses the for loop extensively.
1. What is the disadvantage of using goto? How can you avoid using the goto statement?
2. Which statement can you use to improve the long if statements?
3. What are the differences between the for and foreach statement? When should you use which?
Observations:
1. Using the goto statement makes your code much harder to read because the application flow jumps around. goto is mostly used in looping statements. You can then replace goto with while or do-while.
2. The switch statement can be used to improve long if statements.
3. The for statement can be used to iterate over a collection by using an index. You can modify the collection while iterating. You need to use the index to retrieve each item. foreach is syntactic sugar over the iterator pattern. You don’t use an index; instead the compiler gives you a variable that points to each iteration item.
Some General Questions
1) What is C#?
--> C# is an object oriented, type safe and managed language that is compiled by .Net framework to generate Microsoft Intermediate Language.
2) You want to synchronize access by using a lock statement. On which member do you lock?
-->A private lock of type object is the best choice.
3) You need to implement cancellation for a long running task. Which object do you pass to the task?
--> A CancellationToken generated by a ancellationTokenSource should be passed to the task.
4) You are implementing a state machine in a multithreaded class. You need to check what the current state is and change it to the new one on each step. Which method do you use?
-->CompareExchange will see whether the current state is correct and it will then change it to the new state in one atomic operation.
5) What is the base class in .net from which all the classes are derived from?
System.Object
6) What is the difference between public, static and void?
--> All these are access modifiers in C#. Public declared variables or methods are accessible anywhere in the application. Static declared variables or methods are globally accessible without creating an instance of the class. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created. And Void is a type modifier that states that the method or variable does not return any value.
7) What is an object?
--> An object is an instance of a class through which we access the methods of that class. “New” keyword is used to create an object. A class that creates an object in memory will contain the information about the methods, variables and behavior of that class.
8) Define Constructors?
--> A constructor is a member function in a class that has the same name as its class. The constructor is automatically invoked whenever an object class is created. It constructs the values of data members while initializing the class.
9) What is the use of using statement in C#?
--> The using block is used to obtain a resource and use it and then automatically dispose of when the execution of block completed.
10) What is serialization?
--> When we want to transport an object through network then we have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called Serialization. For an object to be serializable, it should inherit ISerialize Interface.
De-serialization is the reverse process of creating an object from a stream of bytes.
11) Can “this” be used within a static method?
--> We can’t use ‘This’ in a static method because we can only use static variables/methods in a static method.
12) What are value types and reference types?
--> Value types are stored in the Stack whereas reference types stored on heap.
Value types:
int, enum , byte, decimal, double, float, long
Reference Types:
string , class, interface, object.
13) What are sealed classes in C#?
--> We create sealed classes when we want to restrict the class to be inherited. Sealed modifier used to prevent derivation from a class. If we forcefully specify a sealed class as base class then a compile-time error occurs.
14) What is method overloading?
--> Method overloading is creating multiple methods with the same name with unique signatures in the same class. When we compile, the compiler uses overload resolution to determine the specific method to be invoke.
15) What is the difference between Array and Arraylist?
--> In an array, we can have items of the same type only. The size of the array is fixed. An arraylist is similar to an array but it doesn’t have a fixed size.
16) Can a private virtual method be overridden?
--> No, because they are not accessible outside the class.
17) How can we sort the elements of the array in descending order?
--> Using Sort() methods followed by Reverse() method.
18) Write down the C# syntax to catch exception?
--> To catch an exception, we use try catch blocks. Catch block can have parameter of system.Exception type.
Eg:
try
{
GetAllData();
}
catch(Exception ex)
{
}
19) What’s the difference between an interface and abstract class?
--> Interfaces have all the methods having only declaration but no definition. In an abstract class, we can have some concrete methods. In an interface class, all the methods are public. An abstract class may have private methods.
20) What is the difference between Finalize() and Dispose() methods?
--> Dispose() is called when we want for an object to release any unmanaged resources with them. On the other hand
21) Finalize() is used for the same purpose but it doesn’t assure the garbage collection of an object.
22) What are circular references?
--> Circular reference is situation in which two or more resources are interdependent on each other causes the lock condition and make the resources unusable.
23) What are generics in C#.NET?
--> Generics are used to make reusable code classes to decrease the code redundancy, increase type safety and
performance. Using generics, we can create collection classes. To create generic collection, System.Collections.Generic namespace should be used instead of classes such as ArrayList in the System.Collections namespace. Generics promotes the usage of parameterized types.
24) What are Custom Exceptions?
--> Sometimes there are some errors that need to be handeled as per user requirements. Custom exceptions are used for them and are used defined exceptions.
25) What are delegates?
--> Delegates are same are function pointers in C++ but the only difference is that they are type safe unlike function pointers. Delegates are required because they can be used to write much more generic type safe functions.
26) How do you inherit a class into other class in C#?
--> Colon is used as inheritance operator in C#. Just place a colon and then the class name.
public class DerivedClass : BaseClass
27) What are the different ways a method can be overloaded?
--> Methods can be overloaded using different data types for parameter, different order of parameters, and different number of parameters.
28) How can we set class to be inherited, but prevent the method from being over-ridden?
--> Declare the class as public and make the method sealed to prevent it from being overridden.
29) What is the difference between a Struct and a Class?
--> Structs are value-type variables and classes are reference types. Structs stored on the stack, causes additional overhead but faster retrieval. Structs cannot be inherited.
30) How to use nullable types in .Net?
--> Value types can take either their normal values or a null value. Such types are called nullable types. (? makes variable nullable)
Int? someID = null;
If(someID.HasVAlue)
{
}
31) How we can create an array with non-default values?
--> We can create an array with non-default values using Enumerable.Repeat.
32) Is C# code is managed or unmanaged code?
--> C# is managed code because Common language runtime can compile C# code to Intermediate language.
33) How to implement singleton design pattern in C#?
--> In singleton pattern, a class can only have one instance and provides access point to it globally.
Eg:
Public sealed class Singleton
{
Private static readonly Singleton _instance = new Singleton();
}

Comments

Popular posts from this blog

Top 10 ASP.NET Web API Interview Questions

What is ASP.NET Web API? ASP.NET Web API is a framework that simplifies building HTTP services for broader range of clients (including browsers as well as mobile devices) on top of .NET Framework. Using ASP.NET Web API, we can create non-SOAP based services like plain XML or JSON strings, etc. with many other advantages including: Create resource-oriented services using the full features of HTTP Exposing services to a variety of clients easily like browsers or mobile devices, etc. What are the Advantages of Using ASP.NET Web API? Using ASP.NET Web API has a number of advantages, but core of the advantages are: It works the HTTP way using standard HTTP verbs like  GET ,  POST ,  PUT ,  DELETE , etc. for all CRUD operations Complete support for routing Response generated in JSON or XML format using  MediaTypeFormatter It has the ability to be hosted in IIS as well as self-host outside of IIS Supports Model binding and Validation Support for OD...

Extension methods in C#

Consider the class C# 1 2 3 4 5 6 7 8 9 10 11 12 13          namespace ExtensionMethod      {          public class testClass {              public string sayHello ( ) {              return "Hello" ;            }        }      }     Invoke the above from your form using C# 1 2 3 4 5 6          testClass test = new testClass ( ) ;      MessageBox . Show ( test . sayHello ( ) ) ;     This will show “Hello” in message box. Consider the scenario where you don...

What is cookie? Advantages and disadvantages of cookies?

What is cookie? A cookie is a small piece of text file stored on user's computer in the form of name-value pair. Cookies are used by websites to keep track of visitors e.g. to keep user information like username etc. If any web application using cookies, Server send cookies and client browser will store it. The browser then returns the cookie to the server at the next time the page is requested. The most common example of using a cookie is to store User information, User preferences, Password Remember Option etc.It is also one of the common and mostly asked interview questions. Some facts about Cookie Here are a few facts to know about cookies: · Cookies are domain specific i.e. a domain cannot read or write to a cookie created by another domain. This is done by the browser for security purpose. · Cookies are browser specific. Each browser stores the cookies in a different location. The cookies are browser specific and so a cookie created in one browser(e.g in Google Chrome...