C# Interview Questions

C# is a simple, modern, general purpose programming language developed by Microsoft Corporation. In the following section, enlisted the most important C# interview questions and answers for freshers as well as experienced developers to get the right job.

Explain the C# code execution process?

Compiler time process:
  1. C# Source Code >>> .Net Compiler >>> Byte Code (MSIL + META DATA)
Runtime process:
  1. Byte Code (MSIL + META DATA) >>> Just-In-Time (JIT) Compiler >>> NATIVE CODE
C# code execution life cycle diagram is shown as follows :
Frequently Asked C# Interview Questions and Answers

How do you force your .NET application to run as administrator?

You have to modify the manifest that gets embedded in the program, which will cause Windows (7 or higher) to always run the program as an administrator .
  1. Project>>>Add New Item, select "Application Manifest File".
Change the element to:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

This works on Visual Studio 2008 and higher.

What are the differences between Object and Var?

Each object in C# is derived from Object type , either directly or indirectly. It is a compile time variable and require boxing and unboxing for conversion and it makes it slow. Also, the compiler has little information about the type. Object can store any kind of value because the Object is the base class of all type in .NET framework. Var is also a 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, you can't change type stored in it. It is type-safe i.e. compiler has all information about the stored value, so that it doesn't cause any issue at run-time. Var can store any type of value but It is mandatory to initialize var types at the time of declaration.

What is a NullReferenceException

NullReferenceException means that you are trying to use a reference variable whose value is Nothing/null . When the value is Nothing/null for the reference variable, which means that it is not actually holding a reference to an instance of any object that exists on the heap.
string str = null; str.ToUpper();
Above code throws a NullReferenceException at the second line because you can't call the instance method ToUpper() on a string reference pointing to null.

Why is it wrong to specify access modifiers for methods interfaces?

Interfaces are meant to define public APIs (Application Programming Interface). This is because there is no other use for the methods inside an interface except that a derived class could override it. So any method (or static member) you define in an interface is by definition public. And declaring such methods but leaving the calls to them to subclasses or totally unrelated clients would mean your type definition is incomplete. If you would like to force someone to override a given set of private methods , you might want to declare an abstract class with a series of abstract protected methods.

How to check that a nullable variable is having value?

Use the HasValue property of the Nullable to check whether a nullable variable has value or not:
if (item.HasValue) { }
If the HasValue property is true, the value of the current Nullable object can be accessed with the Value property.

Why this error message: Cross-thread operation not valid

A UI thread creates UI elements and waits and responds to events like mouse clicks and key presses. You can only access the UI elements from the UI thread. There is only one thread (UI thread), that is allowed to access System.Windows.Forms.Control and its subclasses members. Since there is only one thread, all UI operations are queued as work items into that thread. Attempt to access member of System.Windows.Forms.Control from different thread than UI thread will cause cross-thread exception.

Difference between object type and dynamic type variables?

The object types can be assigned values of any other types, value types, reference types , predefined or user-defined types. Also, Compiler has little information about the type. Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at runtime. It is not type-safe, i.e., the compiler doesn't have any information about the type of variable.

What is safe and unsafe code in C#?

The main difference in C# is that a safe code is the one that executes under the supervision of the Common Language Runtime (CLR). ; and, an unsafe code is code that executes outside the context of the CLR. In safe code, the CLR is responsible for various tasks, like:
  1. Managing memory for the objects.
  2. Performing type verification.
  3. Performing garbage collection.

While in unsafe code, a programmer is responsible for:

  1. Calling the memory allocation function.
  2. Making sure that the casting is done right.
  3. Making sure that the memory is released when the work is done.

Why this error message?
No connection could be made because the target machine actively refused it.

This error is occurring because there is no server listening at the hostname and port you assigned. It literally means that the machine exists but that it has no services listening on the specified port . So, no connection can be established. Generally, it happens that something is preventing a connection to the port or hostname. Either there is a firewall blocking the connection or the process that is hosting the service is not listening on that specific port. This may be because it is not running at all or because it is listening on a different port.

Difference Between Select and SelectMany?

Select is a simple one-to-one projection from source element to a result element. While SelectMany is used when there are multiple from clauses in a query expression: each element in the original sequence is used to generate a new sequence. This means that it is used to flatten a sequence in which each of the elements of the sequence is a separate.

Why this exception:
New transaction is not allowed because there are other threads running in the session

This exception is due to Entity Framework creating an implicit transaction during the SaveChanges() call. Invoking SaveChanges() method begins a transaction which automatically rolls back all changes persisted to the database if an exception occurs before iteration completes; otherwise the transaction commits . The best way to work around the error is to use a different pattern (i.e., not saving while in the midst of reading) or by explicitly declaring a transaction.

When should reflection be used?

Reflection provides the ability to determine things and execute code at runtime. It can be used to inspect assemblies, types, and members and/or dynamically invoke methods in an assembly. This is very important because .NET languages are strongly-typed. Being able to access that metadata is extremely useful. You don't have to use it if you don't want to, but it is extremely handy for dynamic behaviour .

Advantage of Immutable String in C# programming

When you try to modify a string object in C#, a new object will be created. The original string will remain untouched. This technique is called immutability. Advantages:
  1. Immutable strings are cheap to copy, because you don't need to copy all the data - just copy a reference or pointer to the data.
  2. Immutable strings simplify multithreaded programming since reading from a type that cannot change is always safe to do concurrently.
  3. Immutable strings allows for a reduction of memory usage by allowing identical values to be combined together and referenced from multiple locations.
  4. Immutable strings eliminate the need for defensive copies, and reduce the risk of program error.
  5. Immutable strings simplify the design and implementation of certain algorithms because previously computed state can be reused later.

Why this error message:
The Controls collection cannot be modified because the control contains code blocks

There are <%...%> code blocks inside your Page.Header (which is referring to - possibly in a master page). This processing are made during the page render and not on code behind, on the events of the page. Therefore, when you try to add an item to the Controls collection of that control, you get this error message. So, start the code block with < %# instead of < %= : . This changes the code block from a Response.Write code block to a databinding expression. Since <%# ... %> databinding expressions aren't code blocks, the CLR won't complain.

How do you generate a stream from a string?

You can use the MemoryStream class , calling Encoding.GetBytes to turn your string into an array of bytes first.
public static MemoryStream GenerateStreamFromString(string value) { return new MemoryStream(Encoding.UTF8.GetBytes(value ?? "")); }

What is Kestrel?

Kestrel is a full blown web server that is included by default in ASP.NET Core project templates. You can use Kestrel by itself or with a reverse proxy server, such as IIS, Nginx , or Apache. A reverse proxy server receives HTTP requests from the Internet and forwards them to Kestrel after some preliminary handling.
Top 100 C# Interview Questions and Answers for Experience & Freshers

What are the different states of a Thread in C#?

The various states of a Thread in C# include:

  1. Unstarted State - Instance of the thread is created but the start() method is not called.
  2. Ready State (Runnable) - The thread is ready to run and waiting CPU cycle.
  3. Running State - A thread that is running.
  4. Not Runnable State - The thread is in not runnable state, if sleep() or wait() method is called on the thread, or input/output operation is blocked.
  5. Dead State(Terminated) - Thread enters into dead or terminated state.

The request was aborted: Could not create SSL/TLS secure channel

The error is generic and there are many reasons why the SSL/TLS negotiation may fail. ServicePointManager.SecurityProtocol property selects the version of the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocol to use for new connections; existing connections aren't changed. Make sure the ServicePointManager settings are made before the HttpWebRequest is created, else it will not work. Also, you have to enable other security protocol versions to resolve this issue:
ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 SecurityProtocolType.Tls SecurityProtocolType.Tls11 SecurityProtocolType.Ssl3;
//createing HttpWebRequest after ServicePointManager settings HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")
If you create HttpWebRequest before the ServicePointManager settings it will fail and shows the error message.

How to get the URL of the current page in C#?

string url = HttpContext.Current.Request.Url.AbsoluteUri;
The HttpContext Class encapsulates all HTTP-specific information about an individual HTTP request. It provides access to the intrinsic Request, Response, and Server properties for the request. The AbsoluteUri property includes the entire URI stored in the Uri instance, including all fragments and query strings.

Why this error message: Unable to access the IIS Metabase

This error message says that Visual Studio devenv.exe is not running with sufficient privileges to access the IIS process. There are two solutions fo this error:
  1. Run VS as an Administrator and reopen the solution/project.
  2. Edit the web application's project file with a text editor and change this line from True to False:
<UseIIS>False</UseIIS>
The above changes will stop it using IIS and demanding higher privileges.

Why this exception: System.Net.Sockets.SocketException

A SocketException is thrown by the Socket and Dns classes when an error occurs with the network. Most of the time these are connectivity issues due to different IP protocols (IPV4/IPV6) between the two server/computers trying to communicate or extra authentication rules setup on one of the computers for in/out connectivity.

Possible causes for the error:

  1. Wrong IP address.
  2. Wrong port.
  3. Firewall blocking the connection.
Continue....... C# Interview Questions (part-1)