Introduction
C# is an object-oriented programming language used to develop web apps, websites, desktop apps, and many more applications. It allows code reuse and duplication of code.
Let's explore the comprehensive set of categorised C# interview questions and answers below:
- C# Interview Questions for Freshers
- C# Interview Questions for Experienced
- C# Coding Problems
- C# MCQs
C# Interview Questions for Freshers
Let us go through some easy level C# interview questions and answers.
1. What is C#?
Ans: C# is a modern general-purpose programming language developed by Microsoft. It is used to develop various applications, including Windows desktop applications, mobile applications, and web apps. It runs on .Net framework. C# is mainly a type-safe language, ensuring the internal consistency of each type. For example, C# restricts you from treating a string type like an integer type when you deal with it.
2. What are the features of C#?
Ans: Some features of C# are mentioned below:
- Strong type checking.
- Automatic memory management.
- Object-oriented programming.
- Interoperability with other languages.
- Component-based architecture.
- Delegate type for events and callbacks.
3. What is an object in C#?
Ans: An object in C# is an instance of a class. It holds the values of the properties defined in the class and can access the methods of the class. An object is created using the "new" operator followed by the name of the class. The values of the object's properties can be accessed and modified using dot notation.
Objects are used to encapsulate data and behavior in a single unit, making it easier to organize and manipulate code.
4. What is a class in C#?
Ans: A class in C# is a blueprint or a template that defines the properties, fields, and methods that an object of that class should have. A class is a fundamental building block in oops and encapsulates data and behavior.
Syntax
class class_name
{
// Fields
// methods
}
For example, you can create a class named "Person" that has properties like "Name" and "DOB" and methods like "Speak" and "Walk." When you create an instance of the "Person" class, you have an object that has the properties and methods defined in the "Person" class.
5. What is inheritance in C#?
Ans: Inheritance in C# is an oop feature that allows a class to inherit properties and methods from a base class. This enhances code reusability and helps to reduce duplication of code. The derived class inherits the base class members and can also add its members, making it a specialized version of the base class. The parent class is the class being inherited by the derived class.
Syntax
class derived-class : base-class
{
// Code
}
Inheritance promotes code modularity and enables the creation of new classes built upon existing ones.
6. What is an interface in C#?
Ans: An interface in C# is a blueprint that defines a set of methods and properties that a class must implement. Interfaces provide a way to specify the contract that a class must follow and allow for multiple inheritances in C#. They are used to define a common behavior that multiple classes can implement, promoting code reuse and making it easier to maintain and update the code.
All the members of the interface are public and abstract by default.
Interfaces are declared using the "interface" keyword in C# and can be implemented by classes using the "implements" keyword, providing total abstraction.
The syntax to declare the interface.
interface <interfaceName >
{
// code
}
The syntax to implement the interface.
class class_name : interface_name
7. What is an abstract class in C#?
Ans: An abstract class in C# is a class that cannot be instantiated on its own but is intended to be used as a base class for other classes. An abstract class is declared using the "abstract" keyword and is used to provide a common implementation for its derived classes. An abstract class can have methods, constructors, or destructors.
Example
Output
The child is walking
Walking
It allows for code reuse and can contain abstract methods, which are methods that do not have a concrete implementation and must be overridden in the derived classes.
8. What is a constructor in C#?
Ans: A constructor in C# is a special method that is called when an object of a class is created. It is used to initialize the properties of the object and perform any other necessary setup. A constructor has the same name as the class and does not have a return type. Two types of constructors in C# are:
- Default constructor.
- Parameterized constructor.
Syntax
class Example
{
// Constructor
public Example() {}
}
// Object of Example class
Example obj = new Example();
9. What is a delegate in C#?
Ans: A delegate in C# is a type that represents a method with a specific signature. It acts as a reference to a method and can be passed as a parameter to another method. Delegates are used to implement events and callbacks in C# and provide a way to pass methods as arguments to other methods, allowing for more dynamic and flexible code.
10. Define arrays with the help of an example in C#.
Ans: Array data structure groups similar elements under a single block where memory allocation of the array elements is dynamic. The members in the array are linearly and can be accessed using an index value starting from 0. This means that the first element of the array is at the 0th position, and the last element of the array will be the total number of elements - 1.
There are three types of arrays in C#:
- Single Dimensional.
- Multi-Dimensional.
-
Jagged Array.
Syntax:
< Data Type > [ ] < Array_Name >
Example
Output
1
Black
Explanation:
In the above program, the first array of "numbers" is of int type storing five numbers, and the value of element at index 0 in that array is printed. The second array, "colors," of string data type storing strings, and the value of the element at index 3 in the colors array is printed, i.e., Black.
11. How is C# different from C?
C# is a modern, object-oriented programming language that was designed by Microsoft specifically for the .NET platform. Compared to C, C# includes many additional features such as garbage collection, automatic memory management, a unified type system, strong type checking, and a rich set of standard libraries. Additionally, C# supports modern language features such as lambdas, LINQ, and async/await, which are not available in C. While C is a procedural language, C# is more of an object-oriented language.
12. What is Garbage Collection in C#?
In C#, Garbage Collection is a process of management of memory used by an application. When an application creates an object, it is allocated memory from the heap. When the object is no longer needed, the memory it occupies becomes available for reuse. Garbage Collection is the process by which the .NET runtime automatically frees up this memory when it is no longer in use.
We do not have to explicitly free the memory used by an object once it is no longer needed. The Garbage Collector periodically scans the heap to determine which objects are no longer being used by the application and can be safely removed. The Garbage Collector is responsible for reclaiming the memory used by those unused objects, making it available for reuse by the application.
13. What are the types of classes in C#?
There are several types of classes in C#. Let us look at some of them:
-
Regular Class: These are the most common type of classes in C#. They can contain fields, properties, methods, events, and other members. You can use regular classes to define objects that represent real-world entities or abstract concepts.
-
Partial class: These are classes that are split into multiple files. Each file contains a portion of the class definition, and the compiler combines them into a single class.
-
Abstract Class: These are classes that cannot be instantiated directly. Instead, they are designed to be inherited by other classes.
-
Sealed Class: These are classes that cannot be inherited by other classes. Sealed classes are often used to prevent unintended modification of a class, or to improve performance by allowing the compiler to optimize the code.
-
Nested Class: These are classes that are defined within another class. Nested classes can be either static or non-static, and can be used to encapsulate functionality that is only relevant to the containing class.
- Static Class: These are classes that contain only static members, such as fields, methods, and properties.
14. What is Common Language Runtime?
The Common Language Runtime (CLR), is one of the components of the .NET framework. It manages the execution of the .NET programs written in languages like C#. The CLR provides a number of services that are essential for .NET programs to run correctly, including memory management, security, exception handling, and thread management. The CLR also provides just-in-time (JIT) compilation, which compiles the CIL code into machine code at runtime, allowing the code to be optimized for the specific hardware and operating system.
15. What is the difference between an Array and ArrayList in C#?
Array |
ArrayList |
---|---|
The type of element in an array must be specified at the time of creation of the array i.e., they are statically typed. | ArrayLists are dynamically typed which means that we can store elements of any type. |
Arrays have a fixed size and cannot be changed once the array is created. | ArrayLists can resize themselves and are more flexible than arrays. |
Arrays are generally faster because if fixed size. | ArrayLists are slower as they require more memory and performance overhead. |
Arrays are created using [] within which the size is specified. | ArrayLists can be created using ArrayList classand the initial size can be specified. |
16. What is the difference between a struct and a class in C#?
Ans: The difference between a struct and class in C# is:
Struct | Class |
---|---|
Structs are value types, meaning that when you assign a struct to a variable, you create a copy of the struct in memory. | Classes are reference types, meaning that when you assign a class to a variable, you create a reference to an object stored elsewhere in memory. |
Structs are stored on the stack. | Classes are stored on the heap. |
Structs cannot have destructors. | Classes can have destructors. |
Struct does not support the protected modifier. | The class supports protected modifiers. |
17. What is a lambda expression in C#?
Ans: A lambda expression in C# is a shorthand syntax for creating anonymous functions. It allows you to define a method in place without declaring a separate delegate or named method. A lambda expression can be assigned to a delegate type or passed as a parameter to a method that expects a delegate.
Two types of lambda expressions are:
a. Expression lambda
input => expression;
b. Statement lambda
input => { statements };
Example
using System;
public class Example
{
public static void Main(string[] args)
{
List<int> n = new List<int> {5, 6, 4, 1, 9, 2};
var c = n.Count( a =>
{
return a == 4;
});
Console.WriteLine(c);
}
}
Explanation:
The lambda expression in the above program is inside the Count query - a => { return a== 4; }. The Count counts the number of items and will return a boolean as output.
Lambda expressions provide a more concise and readable way to write inline code and can be used to simplify event handling, iteration, and LINQ (Language Integrated Query) operations.
18. What is the difference between an abstract class and an interface in C#?
Ans: The difference between a abstract class and interface in C# is:
Abstract Class |
Interface |
---|---|
An abstract class in C# can contain both abstract and concrete methods and properties, and its derived classes can override its abstract methods to provide their own implementation. | An interface in C# only defines a set of methods and properties that a class must implement without providing any implementation. |
It contains different types of access modifiers. | It contains only public access modifiers. |
The performance is fast. | The performance is slow. |
Abstract class can be implemented using the “:” keyword. | Interface can be implemented using “:” and “,” keywords. |
The “abstract” keyword is used to declare the abstract class. | The “interface” keyword is used to declare the interface. |
Example: public abstract class Person{ public abstract void walk(); }
|
Example: public interface Person{ void walk(); }
|
19. What is LINQ in C#?
Ans: LINQ (Language Integrated Query) is a feature in C# that allows you to write SQL-like queries against various data sources, including arrays, lists, and databases. LINQ provides a unified way to access and manipulate data, making it easier to write and maintain code that works with different types of data sources.
20. Differentiate between a stack and a queue in C#?
Ans: The difference between a stack and a queue in C# is:
Stack |
Queue |
---|---|
A stack is a last-in-first-out (LIFO) data structure, meaning that the last item added to the stack will be the first item removed. | A queue is a first-in-first-out (FIFO) data structure, meaning that the first item added to the queue will be the first item removed. |
Only one pointer is used to access the elements of the stack. | Two pointers are used to access the elements of the queue. |
The push operation is used to insert an element in the stack. | The enqueue operation is used to insert an element in the queue. |
The pop operation is used to delete an element in the stack. | The dequeue operation is used to delete an element in the queue. |
21. What is the difference between a value type and a reference type in C#?
Ans: In C#, value types directly store their data, while reference types store a reference to an object in memory. When a value type is assigned to a variable, a new instance of the value type is created in memory, containing a copy of the data.
Some of the value data types are:
- byte.
- int.
- char.
- long.
- short.
Example:
There is a variable of integer type x = 50. The System stores 50 at some hypothetical location in the memory space allocated for the integer variable x.
On the other hand, reference types store a reference to the memory location where the object is stored rather than storing the data directly. This means that when a reference type is assigned to a variable, it is a reference to the same object in memory rather than a new instance.
Some of the referenced data types are:
- Arrays.
- Class.
- String.
- Delegate.
Example:
Suppose str = “Hello Ninjas”, the system selects the hypothetical location in memory for the variable str. The value of the str is the memory address of the actual location of the data. Hence the reference type stores the address of the location of the actual value.
22. What is the difference between null and non-nullable types in C#?
Ans: A nullable type in C# can be assigned a value of either its type or null, while a non-nullable type cannot be assigned a value of null and must always have a value of its type. Nullable types are useful when a value may not always be present, while non-nullable types are used for values that must always have a value.
23. Which are the access modifiers available in C#?
Ans: In C#, there are five access modifiers that control the accessibility of classes, members, and other elements in a program:
-
public: The member or class is accessible from anywhere in the program.
-
private: The member or class is accessible only within the same class.
-
protected: The member or class is accessible within the same class and in derived classes.
-
internal: The member or class is accessible within the same assembly (a unit of deployment in . NET).
- protected internal: The member or class is accessible within the same assembly and in derived classes.
24. What is the difference between dispose() and finalize() methods in C#?
Ans: The Dispose method in C# is an explicit method that the user can call to release resources held by an object. The Finalize method is an implicit method that the garbage collector automatically calls to release resources when an object is no longer needed. The Dispose method is preferred over the Finalize method as it allows for more immediate and efficient resource management.
25. What is the difference between method overloading and method overriding in C#?
Ans: In C# method overloading involves creating multiple methods with the same name but different parameters in the same class. Method overriding involves creating a method in a derived class with the same name, return type, and parameters as a method in the base class.
Overloading allows for multiple methods with the same name to perform different operations. In contrast, overriding allows for a derived class to provide its own implementation of a method in the base class.
Example of Method Overloading:
using System;
namespace Application
{
class Overloading
{
public int mul(int x, int y)
{
return (x*y);
}
public int mul(int x, int y, int z)
{
return (x*y*z);
}
static void Main(string[] args)
{
Overloading obj = new Overloading();
Console.WriteLine("First method : " + obj.mul(1, 2));
Console.WriteLine("Second method :" + obj.mul(5, 2, 5));
Console.ReadLine();
}
}
}
Output
First method : 2
Second method :50
Explanation:
In the above program, we use two methods with the same name but with different parameters. So the compiler automatically calls the method with two integers parameters when you call mul(1, 2). While the same with the other method, mul(4.5, 2, 5), which has three parameters of double data type.
Example of Method Overriding
Output
First Method :64
Second Method :0
Second Method :21
Explanation:
In the above example, two methods with the same name are created in the “Overriding” and “Childbase” class. In the “Overriding” class, the method multiplies the two numbers with less than zero value. But the “Childbase” class method checks for the negative value.
26. What are the differences between ref and out keywords?
ref keyword | out keyword |
---|---|
If we use ref, the variable must be initialized before it is passed to a method. | Variable does not need to be initialized before it is passed to a method. |
ref assumes that variable has a vlaue. | out assumes that there is no value of the variable and it will initialized by the method. |
The variable passed to the method can be both read and written by the method. | The variable passed can only be written by the method. |
27. What are extension methods in C#?
Extension methods are a feature in C# that allow you to add methods to an existing class without modifying the class itself. Extension methods are defined as static methods in a static class, and they must be in the same namespace as the class being extended.
To use an extension method, you simply need to call it as if it were an instance method of the extended class. The first parameter of the extension method specifies the class being extended, and it is preceded by the this keyword. This tells the compiler that the method is an extension method and should be called as if it were a member of the extended class.
28. Does C# support multiple inheritances?
C# does not support multiple inheritances traditionally, where a class can inherit from multiple base classes. This is because multiple inheritance can lead to problems with ambiguity and complexity in the class hierarchy.
Instead, C# uses interfaces to provide similar functionality to multiple inheritance, which is an interface. An interface defines a contract that a class must implement but does not provide any implementation details.
29. What are the different types of comments in C#?
Various types of comments in C# are as follows:
-
XML comments
Example: ///This is an XML comment
-
Single Line comments
Example: //This is a single-line comment
-
Multi-line comments
Example: /* This is a multi-line comment */
30. List the steps of compiling a C# code.
Steps involved while compiling a C# code include the following:
-
Compilation of Source Code
-
Clubbing of Assembly code with the newly created code
-
Loading of CLR(Common Language Runtime).
- Execution of assembly code through CLR.