The <style> section defines CSS styles for a placeholder diagram. The diagram has a background with a linear gradient, rounded corners, padding, margin, and centered text alignment. The placeholder icon within the diagram is sized at 3rem with a slight margin at the bottom. The placeholder text is styled in a color of #9ca3af and a font size of 1rem.
Below are some of the most common C# interview questions along with their answers.
1) What is C#?
C# stands as a straightforward, contemporary, multipurpose programming language. Originated by Microsoft, it is an object-oriented programming language. C# is a secure and controlled language that is compiled by the .NET framework to produce Microsoft intermediate language (machine code).
2) What is the reason behind the invention of C#?
C# is specifically crafted for the Common Language Infrastructure (CLI), encompassing the compiled code and execution environment that empowers users to leverage diverse high-level programming languages across various computer platforms and architectures.
3) What are the main reasons to use C# language?
These are the top reasons to use C# language:
- Easy to learn
- General purpose and object-oriented programming language
- Component oriented
- Structured language
- It can be compiled on a variety of computer platforms
- Produces efficient programs
- Part of the .net framework
4) What is the difference between public, static and void?
You have the ability to reach public declared variables from any part of the application.
Static declared variables can be accessed globally without the need to instantiate the class.
Void is a type modifier indicating that a function does not return any value.
5) What are constructors in C#?
A constructor is a class member function with the identical name as the class itself. Upon instantiation of an object from the class, the constructor is automatically called. Its primary function is to set initial values for the data members during the class initialization process.
6) What are the different types of constructors in C#?
Basically, there are five types of constructors:
- Static constructor
- Private constructor
- Copy constructor
- Default constructor
- Parameterized constructor
7) What is static constructor?
A static constructor is employed to set up static data members when the class is first referenced.
8) What is method overloading in C#?
Method overloading is a technique that allows developers to define multiple functions within a single class that share the same name but have different parameter lists. During the compilation process, the compiler employs overload resolution to identify the precise method that needs to be called.
9) Is overriding of a function possible in the same class?
10) What is array?
An array is a collection of interconnected elements, which can consist of either value types or reference types.
There are three types of array supported by C#:
- Single Dimensional Array : It contains a single row. It is also known as vector array.
- Multi Dimensional Array : It is rectangular and contains rows and columns.
- Jagged Array : It also contains rows and columns but it has an irregular shape.
11) What is ArrayList?
An ArrayList functions as a resizable array, allowing for the addition and removal of elements during program execution. It's important to note that elements within an ArrayList are not automatically arranged in a sorted manner.
12) What is a collection?
A collection functions as a container for instances of different classes, with all classes adhering to the ICollection interface.
13) What is an interface?
Interface is a type of abstract class containing solely public abstract methods. These methods lack a concrete implementation and solely provide method signatures. It is mandatory for these abstract methods to be defined in the subclasses that inherit from the interface.
14) What is the lock statement in C#?
A lock statement is employed to prevent simultaneous access of a critical section of code by multiple threads. When a thread tries to access locked code that is already in use, it will be halted, or blocked, until the lock is released.
15) What is serialization?
If you need to transfer an object over a network, it is necessary to transform the object into a sequence of bytes. This transformation process is known as serialization.
16) How to declare a property in a class?
int m_PersonID = 0;
public int PersonID
{
get { return m_PersonID; }
set { m_PersonID = value; }
}
17) What is the difference between early binding and late binding in C#?
- Static Polymorphism: This form of polymorphism in C# is referred to as compile-time polymorphism or early binding.
- Dynamic Polymorphism: This type of polymorphism in C# is known as run-time polymorphism, late binding, method overriding, or dynamic polymorphism.
18) Which are the access modifiers available in C#?
Following are the access modifiers generally used for accessibility:
- Public : If you define an attribute or method as public, it can be accessed from any code of the project.
- Private : A private defined attribute or method can be accessed by any code within the containing class only.
- Protected : If you define the method or attribute as protected it can be accessed by any method in the inherited classes and any method within the same class.
- Internal : If you define an attribute or a method as internal, it is restricted to classes within the current position assembly.
- Protected internal : If you define an attribute or method as protected internal, access is restricted to classes within the current project assembly or types derived from the containing class.
19) What is the difference between abstract class and interface in C#?
An abstract class is capable of containing both abstract and concrete methods, whereas an interface is limited to only abstract methods.
20) What is the difference between dispose and finalize methods in C#?
The dispose function is manually invoked by the programmer to release unmanaged resources like files, database connections, etc. On the other hand, the finalize method is automatically triggered by the garbage collector to release unmanaged resources such as files, database connections, etc.
The dispose function is part of the IDisposable interface, while the finalize method is associated with the Object class.
21) What is the difference between method overloading and method overriding in C#?
Method arguments need to vary in method overloading, while they should remain consistent in method overriding.
In method overloading, inheritance is unnecessary as it occurs within the same class, unlike method overriding where inheritance is a necessity.
22) What is object pool in .Net?
An object pool is a collection of pre-initialized objects, which helps minimize the performance cost associated with instantiating new objects.
23) What is delegate in C#?
A delegate in C# serves as a reference to a method within an object. It can be likened to a function pointer in C++.
24) What is Hashtable?
A Hashtable is a data structure that stores key/value pairs where values are accessed and stored based on their corresponding keys.
25) What is Reflection?
Reflection enables us to access metadata and assemblies of an object dynamically during runtime.
26) What is Garbage Collection?
Garbage Collection is the automated process of deallocating memory that is being held by objects that are no longer reachable.
27) What is a namespace and is required in C#?
A namespace serves as a system for grouping classes with similar purposes or functionalities under a common name. It can be likened to a module, but it is not mandatory to encompass a class within a namespace, as demonstrated in the subsequent syntax:
namespace C# Tutorial
{
class C# Tutorial
{
public static void someMethod()
{
Console.WriteLine("Creating my namespace");
}
}
}
28) Explain types of Comments in C#.
There exist primarily three categories of comments in C#. These include:
- Single Line Comments
Single line comments consist of text placed on a single line to provide explanations or context within the code.
//Hello! This is a single line comment
- Multiline Comments
Multiline comments are typically composed of two lines. This type of comment is characterized by its structure as described below:
/* Hello! This is a
Multiline Comment */
- XML Comments
XML Comments are typically composed across several lines. They are structured in the following manner:
/// Summary
/// Here, we can write code or anything else
/// Summary
29) What are indexers in C#?
An indexer allows us to retrieve instances of a class or struct using an index similar to arrays. This functionality is sometimes referred to as smart arrays. By defining an indexer for a class, the class functions as a virtual array, enabling us to use the array access operator () to retrieve instances of the class.
30) What is the Partial Class in C#?
A partial class is a crucial component of C# programming. It provides a special ability to spread the implementation of a single class over multiple files, which are then consolidated into a single class file during compilation. The partial keyword is employed to define a partial class, enabling the distribution of interfaces, methods, and structures' functionality across different files for better organization.
Syntax:
It has the following syntax:
public partial Class_name
{
// Write the code
}
31) What are sealed classes in C#?
In C#, sealed classes are designed to limit the necessity for inheritance of the class. The sealed keyword blocks any further extension of the class. After a class is marked as sealed, it becomes impossible to derive from it. If an attempt is made to define a sealed class as a base class, compilation errors will occur.
// Sealed class
sealed class SealedClass
{
}
32) How can we inherit a class into another class in C#?
In C#, we can use a colon as the inheritance operator to derive a class within another class. It is necessary to employ a colon followed by the class name for this purpose.
33) What is the main difference between “is” and “as” operators in C#?
The primary contrast between the "is" and "as" operators in C# lies in their functionalities. The "is" operator verifies whether an object belongs to a particular type, providing a Boolean outcome without conducting any type conversions. Conversely, the "as" operator serves the purpose of converting an object to a defined type or class.
34) What is the mean by throw statement in C#?
This statement allows us to manually raise an exception while the C# program is running.
35) What occurs if there are conflicts between the method names in the inherited interfaces?
When multiple interfaces require varying data in their methods, conflicts may arise. Nonetheless, there should be no issues related to the compiler's functionality.
36) What is tuple in C#?
A Tuple within C# serves as a data structure that gathers various values of different types into a unified entity. This feature proves beneficial for conveying multiple results from a function without the need to create a bespoke class or struct.
37) What is the “using” statement in C#?
The "using" keyword in C# is employed to efficiently handle resources by automatically disposing objects that implement IDisposable when they are no longer in scope. This feature proves to be quite beneficial when dealing with files, network connections, streams, database connections, and various unmanaged resources.
38) What is the mean by Race condition in C#?
In C#, a race condition occurs when numerous threads attempt to access and alter the same resource simultaneously.
39) What does it mean by Jagged Array in C#?
In C#, the jagged array represents an array of arrays, where each individual sub-array can contain a different number of elements. This characteristic distinguishes it from a multidimensional array, allowing for varying lengths in each row and offering greater flexibility in scenarios that do not require uniformity.
40) What is the IEnumerable<> in C#?
In C#, an IEnumerable serves as an abstraction that defines a collection of items that can be iterated through individually. This interface consists of a single function, GetEnumerator, which provides an IEnumerator interface. It allows for the read-only traversal of a collection, enabling convenient usage of a for-each loop with an IEnumerable collection.
41) What are the main differences between constant and Read-only in C#?
There exist multiple variances between constant and Read-only in C#. In this section, we shall elaborate on these distinctions individually:
Constant:
- It is defined via the const keyword.
- The value is allocated at compile-time, and it may not be altered.
- It includes a compile-time constant value.
- It may be utilized in any scenario, such as array sizes.
- Read-only is defined via the readonly keyword.
- The value is allocated at runtime, and it may not be changed later.
- It contains a class instance and the values may vary between different instances.
- It may be utilized for instance-level constant values, which are defined at runtime.
Read-Only:
42) What is the File Handling in C#?
In C#, file manipulation refers to the process of interacting with files such as reading or writing data. The C# programming language provides a variety of classes and functions within the System.IO namespace to execute various file tasks. These functionalities include reading, writing, deleting, and modifying files, facilitating effective control over the data stored within them.
43) What are the boxing and unboxing processes in C#?
Boxing:
In C#, Boxing refers to the transformation of a value datatype variable (like int, char, etc.) into a reference type variable (object). This involves an implicit conversion process where the value is encapsulated within a System.Object or an interface type.
Example:
Let's explore a demonstration of how to represent boxing in C#:
namespace TtechPoint
{
class Boxing
{
public void BoxingConversion()
{
int x = 20; // Value type
object obj = x; // Boxing - converting value type to reference type
}
}
}
Unboxing:
Unboxing refers to the act of converting a Reference type (Object) variable into a value type (e.g., int, char, etc.). This conversion is specifically done through an explicit type conversion process.
Example:
Let's explore a demonstration showcasing unboxing in C#:
int x = 18; // value type is int and allocated value 18
Object Obj = x; // Boxing
int a = (int)Obj; // Unboxing
44) Write a program to reverse a string in C#.
using System;
class TtechPoint
{
static void Main()
{
Console.Write("Enter a string to Reverse: ");
string input = Console.ReadLine();
char[] charArr = input.ToCharArray(); // Convert string to char array
Array.Reverse(charArr); // Reverse the array
string reversed = new string(charArr);
Console.WriteLine("Reversed String: " + reversed);
}
}
Output:
Enter a string to Reverse: Hello! This is TtechPoint
Reversed String: tnioPhcetT si sihT !olleH
45) Write a program to check if a given string is palindrome or not in C#.
using System;
class TtechPoint
{
static void Main()
{
Console.Write("Enter a String: ");
string input = Console.ReadLine();
bool isPalindrome = true;
int len = input.Length;
for (int x = 0; x < len / 2; x++)
{
if (input[x] != input[len - x - 1])
{
isPalindrome = false;
break;
}
}
if (isPalindrome)
Console.WriteLine("The String is a palindrome.");
else
Console.WriteLine("The String is not a palindrome.");
}
}
Output:
Enter a String: 64
The String is not a palindrome.
Enter a String: 77
The String is a palindrome.
46) What is the use of Async and Await in C#?
In C#, async and await are employed for asynchronous programming, facilitating the non-blocking execution of tasks. These features enhance application responsiveness by releasing resources during the wait for time-consuming operations like file I/O, database queries, and HTTP requests. The Async and Await keywords are essential for defining asynchronous methods.
47) What is the LINQ in C#?
LINQ, which is short for Language Integrated Query, plays a vital role in C#. This functionality empowers developers to interact with and modify various data types such as collections, arrays, data sets, SQL Server, and XML using a clear, uniform, and succinct SQL-like syntax. By allowing the integration of SQL-like queries within C#, LINQ delivers robust and effective data querying functionalities. It streamlines data handling and extraction processes, ultimately enhancing efficiency and code readability in C# programming.
48) What does it mean by the Constructor Chaining in C#?
Constructor chaining refers to the practice of one constructor calling another constructor within the same class or base class. This technique helps in preventing redundancy in code within a class and guarantees correct initialization. It simplifies the process of object creation by providing multiple options for creating objects with different parameters, thereby enhancing the flexibility and readability of the code.
49) Write a program to find the third largest integer in an array using only one loop in C#.
using System;
class TtechPoint
{
static void Main()
{
int[] array = { 17, 65, 42, 87, 6, 12, 72, 56 };
int first = int.MinValue, sec = int.MinValue, third = int.MinValue;
foreach (int num in array)
{
if (num > first)
{
third = sec;
sec = first;
first = num;
}
else if (num > sec && num < first)
{
third = sec;
sec = num;
}
else if (num > third && num < sec)
{
third = num;
}
}
if (third == int.MinValue)
Console.WriteLine("The Third largest number not found in the array!");
else
Console.WriteLine("The Third largest number in the array is: " + third);
}
}
Output:
The Third largest number in the array is: 65
50) What keyword is used to perform duck typing in C#?
The Dynamic Keyword is employed to enable duck typing in C#.