DEV Community

Sonia Mathias
Sonia Mathias

Posted on

C# Interview Questions for Experienced

Introduction to C#:

C# is a general-purpose programming language that covers a wide range of topics such as object-oriented programming, component-oriented programming, static typing, and strong typing. C# is a programming language that is commonly used in the ASP.NET
framework to create websites, web apps, and games. Microsoft launched C# in 2000 as a modern general-purpose programming language that can be used to create applications for a variety of platforms, including Windows, Web, and mobile devices, by using a single programming language. C# is now one of the most widely used programming languages on the planet.

Some Commonly Asked C# Interview Questions For Experienced:

Q1. What is the Diamond problem in C#?

Ans. When two classes V and W both inherit from U, and class X inherits from both V and W, the "diamond problem" occurs. If V and W have overridden a method in U, but X does not, which class of the method does X inherit: V's or W's? As a result, there is an uncertainty in multiple inheritances in C#. It's also known as an ambiguity problem in C# because it doesn't allow multiple inheritances. It can be resolved using the interface in C# which allows multiple class inheritance,
Alt Text

Q2. What is LINQ in C#?

Ans. Language-Integrated Query (LINQ) is a query language that was implemented in.NET 3.5 and Visual Studio 2008. The usefulness of LINQ is that it allows.NET languages (such as C#, VB.NET, and others) to generate requests to extract data from a data source. For a particular type of data source or data format, the user does not need to learn new query languages. It is possible to reuse a query. In C#, LINQ is available in the System. Linq namespace. It includes a variety of classes and methods that can be used to run LINQ queries. This namespace contains the following elements:

  • Enumerable class contains standard query operators that operate on objects which run IEnumerable.
  • Queryable class contains standard query operators that operate on objects which run IQueryable.

Q3. List some differences between delegates and interfaces in C#.

Ans.

Delegate Interface
It is an object that contains a reference to a method only. It contains methods, events, indexers, and properties.
It is applied to a single method at a time. When a class implements an interface, it also implements all of the interface's methods.
You can use a delegate if it is available in your scope. If your class implements the interface, it is used; otherwise, it is not.
Delegate can be implemented as many times as needed. Interface can be implemented only once.
It is used to handle events. It is not used to handle events.
Anonymous methods can be accessed by a delegate. Interface cannot access anonymous methods.
When you use a delegate to access a process, you don't need access to the class's object where the method is declared. When you use a delegate to access a process, you don't need access to the class's object where the method is declared.
You'll need the object of the class that implements an interface to access the method. It cannot support inheritance.
It cannot support inheritance. It can support inheritance.
Delegates are created at run time. Interfaces are created at compile time.
Any method with the same signature as the given delegate can be implemented. If the interface method is implemented, the same name and signature method override.
It has the ability to wrap both static and sealed class methods. It can wrap any method with a signature that is identical to that of the delegate, regardless of which class it belongs to. Static and sealed class methods are not wrapped by the interface. A class can implement any number of interfaces, but it can only override the interfaces' methods.

Q4. List some differences between Class and Structure in C#.

Class Structure
Class is of reference types. Struct is of value types.
Allocation of all reference types is done on heap memory. Allocation of all value types is done on stack memory.
Class is generally used in large programs. Struct is used in small programs.
A class can contain a constructor or destructor. A struct cannot contain parameterless constructor or destructor, but can contain parameterized constructor or static constructor.
A class uses the ‘new’ keyword to create instances. A struct can create an instance, with or without the ‘new’ keyword.
A class can inherit from another class. A struct cannot inherit from another struct or class.
A class can have protected data members. A struct cannot have protected data members.
A class can have virtual or abstract function members. A struct cannot have virtual or abstract function members.
In a class, two variables can contain the reference of the same instance, and any operation on one variable will affect the other variable. In a struct, each variable contains its own copy of data (except the ref and out parameter variables) and any operation on one variable will not affect the other variable.

Q5. Discuss Thread Priority in Multithreading in C#.

Ans. Each thread in a multithreading environment has its own priority. The priority of a thread indicates how often it is granted access to CPU resources. When we generate a thread in C#, we always give it a priority.

A programmer can give a thread explicit priority. A thread's priority is set to Normal by default. ThreadStateException is thrown when a thread reaches its final state, such as Aborted. ArgumentException will be thrown if the value defined for a set operation is not a valid ThreadPriority value. Setting the thread priority to highest would not correspond to real-time execution since the thread priority is either determined by the process priority or parent container. The Thread. Priority property is used to get or set a value that represents a thread's scheduling priority.

Q6. Differentiate between Method Overriding and Method Hiding in C#.

Ans.

Method overriding Method hiding
The method of a parent class must be defined as a virtual method using the virtual keyword, and the method of a child class must be defined as an overridden method using the override keyword. In method hiding, you simply build a method in a parent class and define it with the new keyword in the child class.
Only the implementation of the method is redefined in method overriding. You can totally redefine the method in method hiding.
Overriding is an object type here. Hiding is a reference type here.
The compiler can not override the method if you do not use the override keyword. Instead of overriding the method, the compiler will hide it. If you don't use the new keyword, the compiler will hide the base class's method by default.
When a reference variable in the base class points to an object in the derived class, the overridden method in the derived class is called. When a reference variable in the base class points to an object in the derived class, the hidden method in the base class is called.

Q7. Illustrate Parsing.

Ans. Parsing is a method to convert a string into some other data type. Parse in C# is used to parse a string into a primitive data type.

Syntax:

//Standard Parse
dataType variable_name = dataType.Parse(string_name);

//TryParse takes care of failure, no need for try-catch
dataType outcome;
bool ifSuccessful = dataType.TryParse(string_name, out outcome);
Enter fullscreen mode Exit fullscreen mode

Q8. Differentiate between finalize() and dispose() methods.

Ans.

dispose( ) finalize( )
The dispose( ) method is defined in the IDisposable interface. The finalize( ) method is defined in java.lang.object class.
This method is invoked by the user. This method is invoked by the garbage collector.
The dispose( ) method, whenever invoked, is used to free unmanaged resources and is to be implemented whenever there is a close( ) method. The finalize( ) method frees unmanaged resources before the object is destroyed.
dispose( ) is declared as public. finalize( ) is declared as private.
The dispose( ) method performs action instantaneously. Hence, it does not hamper the performance of websites. The finalize( ) method, being slower, hampers the performance of the websites.

Q9. What are Events in C#?

Ans. User actions such as key presses, clicks, mouse movements, and so on, as well as occurrences such as machine-induced alerts, are examples of events. Applications must respond to events as soon as they occur. Interrupts, for example. Inter-process coordination is accomplished by the use of events. The events are declared and raised in a class, and event handlers are affiliated with them using delegates from the same or another class. The event is published using the class that contains it. The publisher class is what it's called. The subscriber class is another class that accepts this event. The publisher-subscriber model is used for events.

A publisher is an object that includes the event and delegate definitions. This object also defines the event-delegate relationship. The event is triggered by a publisher class object, which then notifies other objects. A subscriber is a type of object that accepts events and responds with a handler. The delegate in the publisher class calls the subscriber class's method (event handler). An event is an encapsulated delegate in C#. The signature for the subscriber class's event handler method is defined by the delegate.

Q10. What is C# Deadlock?

Ans. A deadlock in C# can be described as a situation in which two or more processes are completely motionless or frozen in their execution because they are waiting for each other to finish. A deadlock can occur when a resource, that is shared among multiple threads, is held up and the rest of them are waiting to cause a deadlock.

Q11. Differentiate between System.Array.CopyTo() and System.Array.Clone().

Ans. Array.Clone() returns an object that contains a shallow copy of all the elements in the source array. Array.CopyTo() copies all of the current array's elements to the designated destination array.

Q12. Discuss async and await.

Ans. C# introduced the async and await keywords to render asynchronous programming on the.NET platform easier. In much of the C# ecosystem, these keywords have radically changed how code is written. These keywords were created in response to the difficulties encountered when using the Task and Task classes.

To use the await keyword in the function, the async keyword is added to the method signature. It also tells the compiler to make an asynchronicity-handling state machine. An async method's return type is always Task or Task. Since it is tested by the compiler, there isn't much scope for error.

The await keyword is used to wait for a Task or Task to finish asynchronously. It pauses the current method's execution until the asynchronous task that is being awaited finishes. The await keyword differs from calling.Result() or .Wait() in that it returns the current thread to the thread pool rather than keeping it blocked.

For the remainder of the async process, it generates a new Task or Task object. It assigns this new task as a follow-up to the awaited task and assigns background requirements for the continuation task.

Q13. Describe the accessibility modifier "protected internal".

Ans. The keyword combination, protected internal, is a member access modifier. It makes a data member accessible in any type within its current assembly. This data member is also accessible in an inherited class located in another assembly if the access is made through a variable of the derived class type.
Example:-
Accessing protected internal member within the current assembly:-

public class A
{
   protected internal int x = 0;
}
class B
{
    void fun()
    {
        var obj = new A();
        A.x = 5;
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, x is a protected internal data member of class A. It is accessed in a member function of class B which is in the same assembly. So, this code runs correctly.

Accessing protected internal member within a derived class in another assembly :-

public class A
{
   protected internal int x = 0;
}

class B : A
{
    static void Main()
    {
        var objA = new A();
        var objB = new B();

        // Error as x can only be accessed by classes derived from A.
        // objA.x = 10;
        // Executes because the protected internal member is being accessed through derived class's object
        objB.x = 10;
    }
}
Enter fullscreen mode Exit fullscreen mode

Q14. What is Anonymous Method in C#?

Ans. An anonymous method, which was added in C# 2.0, is a method that doesn't have a name. The delegate keyword is used to define an anonymous method, which the user can then assign to a delegate type variable. The inline method is another name for this method. This method allows you to construct a delegate object without having to write separate methods. Outer variables, which are the variables in the outer method, can be accessed by this method.

Syntax:
delegate(parameter_list)
{
    Code
};
Enter fullscreen mode Exit fullscreen mode

Q15. What are Nullable types in C#?

Ans. The compiler in C# prevents you from assigning a null value to a variable. As a result, C# 2.0 introduces the Nullable type, which allows you to assign a null value to a variable. The Nullable type allows you to give a variable a null value. Nullable types are only compatible with Value Types, not Reference Types, as implemented in C#2.0. Nullable types for Reference Types were implemented in C# 8.0 in 2019 to allow us to specifically define whether or not a reference type can hold a null value. This allowed us to solve the NullReferenceException problem without having to use conditionals. A Nullable type is an object of System.Nullable struct.

Syntax:

Nullable variableName = null;

OR

datatype? variableName = null;

Q16. What is the use of lambda expression in C#?

Ans. A lambda expression is an easy way of defining an anonymous (unnamed) method that can be passed around as a variable or as a parameter to a method call. A function, called delegate, is taken as a parameter by many LINQ methods. The following example shows what a lambda expression looks like:

Func multiplyByThree = n => n * 3;
// Returns 12
int outcome = multiplyByThree(4);

The expression n => n * 3 is an example of a lambda expression. The => operator is known as the "lambda operator". In this example, n is an input parameter to the anonymous method, and the return value of this function is n * 3. Thus, when multiplyByThree is called with a parameter of 4, the outcome is 3 * 4, that is 12.

Q17. Is serialisation of hashtables possible?

Ans. Hashtable is a collection of key-value pairs. It is not possible to serialize hashtables as the .NET Framework does not support the serialization of those objects that implement the IDictionary interface. The XmlSerializer class will show an error each time an attempt is made to serialize a Hashtable.

C# interview questions for experienced candidates are usually designed in a way that can fetch more targeted answers and garner better perspectives. This is done to see if you're the right candidate for the role that's been offered. Here's a comprehensive set of important interview questions covererd on C#.

Top comments (2)

Collapse
 
jayjeckel profile image
Jay Jeckel

Q1: The correct answer is that if both V and W are classes, then class X can't inherit from both, so there is no "diamond problem" in C#.

Also, interfaces don't "allows multiple class inheritance", they don't allow inheritance at all, because you don't inherit an interface, you implement an interface. In C# a class can inherit one other class and it can implement any number of interfaces.

Collapse
 
allanshady profile image
Allan Camilo

Let me consider theses questions. Thanks!