Today, we’ve outlined 15 C# interview questions that every beginner should read once. We’ve mostly covered the fundamentals of C# programming and touched upon a few advanced concepts.
As per the latest TIOBE index, C# stands at the seventh position among the best programming languages to learn first. So you probably made the right decision to start learning the language that can fetch you one of the highest-paying jobs in the IT industry.
Looking at the popularity and the volume of job openings, we’ve picked some of the essential C# interview questions that could increase your chances of getting hired. You must remember that a successful candidate is one who can think a step ahead of the interviewer.
Preparing for C# Interview – Let’s Know How to Start
Before moving on to the C# Interview questions and answers section, let’s read a few interesting facts about CSharp programming.
History Matters
As the world knows C# took its first breath in 2001 at Microsoft Labs. And soon, it went through several transformations under the supervision of Anders Hejlsberg. Hejlsberg missed his graduation in engineering from the Technical University of Denmark. But later went on to author notable programming languages like Turbo Pascal, and Delphi and is currently the man behind the development of C#.
Now, let’s hear a few fun facts about the C# language.
C# Fun Facts
- It puts away all global variables and functions. You must declare them strictly inside a class.
- Local variables can’t push back the variables of the enclosing block.
- C# presents a native boolean type i.e. bool. Unlike C/C++, you can’t translate it to/from an integer.
- You can use pointers only from the blocks marked as unsafe. You won’t be able to dereference any pointer defined outside the unsafe block.
- C# brought in GC (Garbage Collector) to manage memory and avoid memory leaks.
- It fixed the well-known diamond problem by casting out the ability that could lead to multiple inheritance issues.
- C# allows using Enumeration within the boundary of their namespaces.
- It fully supports type reflection and discovery.
The Best 15 C# Interview Questions and Answers
Q-1. What are the essential features of C# language that made it the fourth most used language?
Ans. Following is the list of features behind the popularity of the C# language:
1. Boolean Conditions
2. Automatic Garbage Collection
3. Standard Library
4. Assembly Versioning
5. Properties and Events
6. Delegates and Events Management
7. Easy-to-use Generics
8. Indexers
9. Conditional Compilation
10. Simple Multithreading
11. LINQ and Lambda Expressions
12. Integration with Windows
Q-2. What are the different access modifiers C# language supports?
Ans. Access modifiers define the scope in which an object and its members are accessible. All types and type members in C# support them.
There are following five types of access specifiers available in C#.
A. Public :
It is the most common access specifier in C#. There is no restriction on accessing public members. The scope of its accessibility is inside as well as outside the class.
B. Private :
A private member is accessible from within the body of the class or the structure that defines it. Thus it cannot be accessed from outside the class. It is the default access modifier type if there is no explicit declaration.
C. Protected :
The scope of accessibility is limited to within the class or structure and the class derived ( or Inherited) from this class.
D. Internal :
The internal access modifiers can access the program that contains its declarations and also access within the same assembly level but not from another assembly.
E. Protected Internal :
It is the same as protected and internal access levels. Its accessibility scope is anywhere in the same assembly, in the same class, and also in the classes inherited from that class.
Q-3. What is a constructor and how is it different in C# than in C++?
Ans. As usual, a constructor is a special method of a class that gets invoked automatically on instantiating that class.
The primary purpose of the constructors is to initialize the private members while creating the objects of the class. If a class doesn’t have an explicit constructor, then the compiler automatically creates the default one. It initializes all numeric fields in the class to zero and all string and object fields to null.
Since there is no way a constructor can return values, so it doesn’t have a return type.
A constructor can call another constructor by using the “this” keyword. The “this” keyword represents the current instance of a class.
Syntax:
You can define a constructor with the same class name and without mentioning any return type as:
[Access Modifier] className([Parameters])
{
public className() {
// write the code here
}
}
All these C# interview questions will ensure to check up on your basic understanding of your theoretical as well as syntactical knowledge.
Q-4. What are the different types of constructors available in C#?
Ans. We can classify the constructors into the following five types:
1. Default Constructor:
A constructor without any parameters is the default Constructor. A major drawback of the default Constructor is that all instances of the class get initialized with the same values. It is not possible to initialize them with different values.
2. Parameterized Constructor:
A Constructor with at least one parameter is a Parameterized Constructor. Its advantage is that it enables to initialization of each instance of the class to different values.
3. Copy Constructor:
A Copy Constructor is a parameterized constructor that contains, parameters of the same class type. Its objective is to initialize a new instance to the values of an existing one.
4. Static Constructor:
We create a Static Constructor by declaring a Constructor as static. It gets invoked only once for any number of instances of the class.
5. Private Constructor:
It is not possible to instantiate a class that contains a Private Constructor. Thus we can create a Private Constructor in a class that has only static members.
Q-5. What is a jagged array? Explain with examples.
Ans. A jagged array is a sequential collection of elements which themselves are arrays. It may constitute elements of different dimensions and sizes.
Programmers often call it an “array of arrays” where the length of each array index can differ.
Example:
Declaring the array of four elements:
int[][] jagArray = new int[4][];
In the above declaration, the rows are fixed in size. However, columns can vary as they are not specified.
Initializing the elements in a jagged array:
jagArray[0] = new int[2] { 7, 9 };
jagArray[1] = new int[4] { 12, 42, 26, 38 };
jagArray[2] = new int[6] { 3, 5, 7, 9, 11, 13 };
jagArray[3] = new int[3] { 4, 6, 8 };
Q-6. How does C# differentiate between a struct and a class?
Ans. Class and struct both are user-defined data types. However, there are some differences between them, which are as follows:
Struct:
1. It is a value type in C# and inherits from System.Value
Type.
2. C# stores the Struct value in the stack memory.
3. The Struct
uses the array type. And, it’s good to use Struct
for read-only and lightweight objects.
4. A Struct
doesn’t support inheritance. So it can’t fit as the base type for a class or a Struct
.
5. A Struct can only inherit the interfaces.
6. A Struct can have the constructor only but not the destructor.
7. Using the “new” keyword is not required to instantiate a Struct.
8. The Struct cannot have the default constructor.
9. The Struct is by default sealed class. Hence it will not allow inheritance. It cannot use the abstract, sealed, and base keywords.
10. The Struct cannot use the protected or protected internal access modifier.
11. We cannot initialize a Struct at the time of declaration.
Class:
1. It is a reference type in C# and inherits from System.Object
Type.
2. C# stores the Class object in the heap memory. The GC automatically removes them when needed.
3. The Class uses the collection object type and thus supports operations for complex data type storage.
4. The Class can inherit another Class, interface and it can be the base Class for another Class.
5. The Class can inherit the interfaces and abstract classes.
6. The Class can have both the constructor and the destructor.
7. It is mandatory to use the “new” keyword to create the object for the Class.
8. The Class will have the default constructor.
9. A class can be declared as an abstract and sealed class.
10. A class can use all the available access modifiers.
11. A Class can have the object initializer fields.
Q-7. What is the use of Abstract and Sealed Classes in C#?
Ans.
The abstract keyword allows the creation of classes and class members that are incomplete. Implementation of such classes transpires in the derived class.
However, the sealed keyword stops a class (marked as virtual) or a particular class member from being inherited.
Q-8. What are the possible ways of passing parameters to a function in C#?
Ans. We can use the following approaches to pass parameters in C#.
1. Value parameters:
It makes a copy of the original value of the arguments, into the functional parameters. In this case, any change made to the parameter inside the function has no effect on the actual argument.
2. Reference parameters:
This method copies the address of the memory location of the argument into the formal parameter. Thus, any change in the value of the parameter affects the actual argument.
3. Output parameters:
This method allows a function to return multiple values.
Q-9. What is the difference between ref and out keywords?
Ans. Following are the key differences between ref and out keywords:
Ref:
1. The parameter or the argument must be initialized first before passing it to Ref.
2. It is not mandatory for the called method to initialize or assign values to parameters (passed by reference) before the control returns to the calling function.
3. Passing a parameter value by Ref is useful when its value has to be modified by the called function.
4. It is not compulsory to assign a value to a parameter before using it in the calling method.
5. Ref supports the bi-directional passing of data.
Out:
1. It is not compulsory to initialize a parameter or argument before passing it to an Out.
2. It is mandatory for the called method to assign or initialize values to the parameters before the control returns to the calling method.
3. Declaring a parameter to an Out method is useful when a function returns multiple values.
4. It is compulsory to initialize a parameter value within the calling method before its use.
5. Out supports the passing of data in a uni-directional way only.
Let’s now find out some more in-depth C# interview questions to boost your knowledge.
Q-10. Why can’t static methods access the “this” object?
Ans. It is not possible to use “this” from static methods. It is because the ‘this’ keyword comes into the picture when you create the object of a class. The language subsystem links ‘this’ to every method of the class except static ones.
Moreover, the static methods by design stand outside the class-object relationship. They come to life as soon you define them without needing an object of the class to access them. By the way, you just need the name of the class to call it.
So we can’t use “this” keyword in the body of Static Methods. However, there is a situation known as the Extension Method which does allow to use “this” keyword in static methods.
It is relatively a new concept introduced in C# 3.0. It enables a class to extend without modifying its code.
- Its primary purpose is to extend the capabilities of an existing class.
- To add new methods, first of all, declare them inside a static class. Then, bind them with the target class.
- Every such method must have its first parameter beginning with the class name prefixed with this keyword. The “this” keyword would only act as a binding parameter and will get ignored while calling the method.
Q-11. What is a namespace? And what is its use?
Ans. The namespace keyword is used to declare a scope that contains a set of related objects. You can use a namespace to organize code elements and to create globally unique types. In other words, it provides a way to keep one set of names separate from another.
For example, let’s create a class with the name Console and place it in its own namespace. The explanation for doing this is that it ensures, there is no confusion about when the System.Console
class gets used and when the user-created class gets used.
However, it is bad coding practice to create a class with the name Console. However, there are situations where the name of our class could conflict with the names in the Dot Net library or a third-party library. In such cases, namespace helps you avoid the problems that identical class names would cause. In such scenarios, namespace helps you avoid the problems that identical class names would cause.
This implies that the class names declared in one namespace do not conflict with the same class names declared in another.
The following program demonstrates the use of namespaces.
C# Example
using System;
namespace one
{
class myClass
{
public void func()
{
Console.WriteLine("Inside namespace one");
}
}
}
namespace two
{
class myClass
{
public void func()
{
Console.WriteLine("Inside namespace two");
}
}
}
class TestClass
{
static void Main(string[] args)
{
one.myClass obj = new one.myClass();
two.myClass itm = new two.myClass();
obj.func();
itm.func();
Console.ReadKey();
}
}
Q-12. What is the purpose of the “using” directive in C#?
Ans. The “using” keyword states that the program is using the names in the given namespace.
Let’s take the following example.
C# Example.
// Namespace Declaration
using System;
using techbeamers;
// techbeamers Namespace
namespace techbeamers
{
class myExample
{
public static void myPrint()
{
Console.WriteLine("Example of using directive.");
}
}
}
// Program start class
class UsingDirective
{
// Main begins program execution.
public static void Main()
{
// Call namespace member
myExample.myPrint();
}
}
Explanation.
If we want to call methods without typing their fully-qualified name, we implement the using directive. In the above example, we have declared two using directives. The first, using System directive allows us to type the method names of members of the System namespace without typing the word System every time. In the myPrint() method above, the Console is a class member of the System namespace with the method WriteLine(). Its fully qualified name is <System.Console.WriteLine(…)>.
Similarly, the <using techbeamers> directive enables us to call the members of the techbeamers namespace without typing the fully-qualified name. This is why we can type <myExample.myPrint()> instead of <techbeamers.myExample.myPrint()> every time we want to call that method.
Q-13. How does boxing differ from unboxing in C#?
Ans. These two are the type conversion strategies with some specific differences:
1. Boxing
In the boxing technique, a simple value goes through the conversion and the end result is an object or an interface type. It is none other than the C# runtime (CLR) which uses a <System.Object> to hold the value in the heap memory of the application.
C# Example:
public void doBoxing()
{
int simpleVal = 23;
object newObj = v; //implicit boxing
Console.WriteLine(newObj);
}
2. Unboxing
You just heard about boxing that places a simple value inside an object container.
On the other hand, the unboxing is the opposite of that as it pulls the actual value out of the object container or an interface. However, it is unlike the boxing that CLR does by default and it has to be done intentionally.
The below C# code provides a basic example to show how you can unbox a value in the code.
C# Example:
public void doUnboxing()
{
object newObj=10;
int simpleVal = int (newObj); //explicit Unboxing
Console.WriteLine(simpleVal);
}
Q-14. Which class acts as a base class for all the data types in C#?
Ans. The Object type is the base class of all data types in the C# Common Type System (CTS). It stays at the root of the hierarchy and works as an alias for the classes.
We can assign an Object type to any of the value or reference types, predefined or user-defined types. However, before assigning values, type conversion is mandatory.
Q-15. What is an enum and how does C# implement it?
Ans. An enum is a value type with a set of related named constants often referred to as an enumerator list. You can define it with the enum keyword. It’s a user-defined primitive data type.
Usually, an enum is of an integer type. Though, you can use other types e.g. float, byte, double. However, you need to cast while using it.
An enum helps to define numeric constants in C#. All of its members are of the enum type. There must be a numeric value for each enum type.
The default underlying type of the enumeration element is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
Given below is the example of the enum declaration:
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
Following are some important points about enum:
1. They are strongly-typed constants. Thus an enum of one type cannot be implicitly assigned to another enum type, even though their members have the same values.
2. The enum values are the same as constants. You can print them like a string and process them like an integer.
3. Its default type is int, and the approved types are as follows.byte, sbyte, short, ushort, uint, long, and ulong.
4. All enum type automatically derives from System. Enum and its methods work on enums.
5. Enums are value types constructed on the stack and not on the heap.
Summary – C# Interview Questions and Answers for Beginners
We intend you to succeed in all your endeavors. And we are hopeful the above C# interview questions will help you do that.
In our next posts on C# programming, we’ll add more questions for experienced and bring a few quizzes for you to practice your skills.
If you have any feedback or like to share some ideas, then speak it out in the comment box.
Check out more CSharp Q&A on various programming topics:
1. 50 CSharp Coding Interview Questions
2. 15 CSharp Programming Interview Questions
3. 15 CSharp Interview Questions Every Programmer
4. 15 CSharp Questions on For, While, and If Else
5. 15 CSharp Programming Questions on Classes
6. 20 CSharp OOPS Interview Questions Set-1
7. 20 CSharp OOPS Interview Questions Set-2
8. 25 CSharp OOPs Interview Questions Set-3
9. 35 CSharp Exception Handling Questions
All the Best,
TechBeamers