Top 50 C# Interview Questions and Answers

Posted in /  

Top 50 C# Interview Questions and Answers

Paritosh Louhan
Last updated on September 14, 2022

    C# or C-Sharp is one the most popular programming language used for building applications, mobile applications, and games. It is an object-oriented programming language used with the .NET framework.

    This language has various reasons for being popular; some of them are as follows:

    • Easy to use: C# is easier to use as compared to other programming languages.
    • Suitable for web development: With C#, you can create web applications and apps.
    • Impressive features: C# comes with some fantastic features like interfaces, automatic garbage collection, etc., which help in building better applications.
    • Wide audience: In collaboration with Microsoft, apps created from C# come with a wide target audience.

    If you want to learn and master C#, you can purchase this course here.

    In this blog post, we have listed some of the most popular C# interview questions. These questions will help you prepare for your next interview and are for both beginners and professionals.

    So, let us get started without further ado!

    C# Interview Questions and Answers

    We have divided the list of frequently asked C# interview questions into three levels: Beginner, Intermediate, and Advanced.

    Beginner-Level C# Interview Questions

    1. What is C#?

    C# is an object-oriented programming language developed by Microsoft in 2000. It caters to the needs of all kinds of software, which targets various platforms, including Web, Mobile, and Windows. It supports the concept of objects and classes, with classes having members like properties, events, methods, and fields.

    2. What is an object in C#?

    An object in the C# is an instance of a class that is created dynamically. An object is also a keyword called for the predefined type System object in the .NET framework. The object type is used where there’s a need to build generic routines. However, the non-generic collection of classes in the .NET framework library, like Queue, ArrayList, etc., uses object type to define this collection.

    Let’s elaborate on this with an example: you need to create a program that deals with dolls. For that, we first need an entity for the doll- let’s call that entity a class. A doll can be of various types, i.e., height, hair color, complexion, dress, etc.

    To present a doll, we can create a class with the above properties-height, hair color, complexion, and dress type. These are the members of the class.

    A class can have different members, properties, fields, events, delegates, and methods. These members can also be private, protected, and the public as these properties can be accessed outside the class and can be public. An object is the instance of the class, and a class can have different instances.

    For instance, the Barbie doll is an instance of a doll.

    3. How are C# and C different?

    Properties of C:

    • C is a language that supports procedural programming .
    • It supports pointers.
    • There is no garbage collection present.
    • It can be executed cross-platforms.
    • By using C, you can achieve a low level of abstraction.
    • It has more functions.
    • C gives a top-notch performance.
    • There are a total of 32 keywords used in this language.
    • It is commonly used in engineering and commercial industries.

    Properties of C#:

    • C# supports object-oriented programming.
    • Pointers are used in the unsafe mode only.
    • The Common Language Runtime (CLR) manages garbage collection.
    • .NET framework is required to execute this language.
    • You get a high degree of abstraction.
    • This language is more on design.
    • It gives an objective standard performance.
    • There are a total of 86 keywords used in the C#.
    • The language is used for software performance and other networking-related objectives.

    4. What is CLR?

    Common Language Runtime, CLR is the basic virtual machine component of the .NET framework, which runs the code and offers services to ease the development process. Compilers and tools use the common language runtime’s functionality and let you write code that gets benefits from its managed execution section.

    Additionally, the common language runtime makes it easy to design various components and applications whose objects interact with different languages. Objects written in other languages can easily communicate with each other. Some of the benefits a runtime provides are:

    • Ability to use components developed in other languages
    • Performance improvements
    • Extensible types are given by the class library
    • Support for the free threading to create multithreaded applications
    • Support for custom attributes
    • Garbage collection

    5. What is the difference between managed and unmanaged code in .NET?

    Managed code is the code managed by the Common Language Runtime in the .NET framework. However, Unmanaged code is the code directly executed by the operating system. Some of the common differences between the Managed and Unmanaged code are

    Managed

    Unmanaged Code

    It is managed by the CLR.

    Executed by the operating system.

    Provide security to the application written in the .NET framework.

    Does not provide any security.

    Offer runtime services like exception handling, Garbage collection, etc.

    Doesn’t provide runtime services.

    Memory buffer overflow does not occur.

    Memory buffer overflow occurs.

    Source code is compiled in the IL or MSIL or CIL language.

    The source code has complied directly with the native language.

    6. What is JIT compiler process?

    JIT, a Just-in-time compiler, is a part of the common language runtime in the .NET that helps manage the execution of .NET programs irrespective of any language. The compiler is enabled by default and is activated when the Java method is called.

    The JIT compiler compiles the bytecode into the native machine code to run. So, when the method gets compiled, the Java Virtual Machine calls the compiled code instead of interpreting it. Also, the JIT compiler measures the operational data at run time and uses that data to improve the quality of recompilations.

    7. What is garbage collection in C#?

    The garbage collector is the automatic memory manager that manages the allocation and release of the memory. When you create a class object at runtime, some memory space gets stored in the heap memory; but when all the actions in the object get compiled in the program, the memory space allocated gets wasted. In such cases, garbage collection automatically releases that memory space.

    Garbage collection always works on the Managed Heap and is connected with an internal engine called Optimization Engine. Also, garbage collection occur if any of the following condition gets satisfied:

    • The system has low physical memory
    • If the memory is allocated to various objects in a heap that exceeds the pre-set threshold
    • If the garbage collection method is called

    8. What are the different phases in the garbage collection?

    Garbage collection has mainly three phases, viz:

    • Marking Phase: At this phase, a list of all the live objects is created. This is done by using references from the root objects, and the objects that are not present in the list get deleted from the heap memory.
    • Relocating Phase : The references from the root object, which were in the list of live objects, get updated in the relocating phase so that they refer to the new location where the objects get relocated.
    • Compacting Phase: The heap gets compacted in this phase as the dead space is released and the live objects left get removed.

    9. What are the different types of classes in C#?

    C# has four classes:

    Static Class: This class comes with a static keyword and contains only static members. This class cannot be instantiated; the following are the characteristics of a static class:

    • Static class can only contain static members.
    • Static items share resources between various users.
    • It cannot be instantiated using the new keyword.
    • Static cannot be used with destructors, indexers, or other types.
    • Static constructor in the non-static class runs only when the class is instantiated for the first time.

    Abstract Class:

    A class with the abstract modifier shows that the class is an abstract class. The purpose of this class is to provide a common definition of the base class, which multiple derived classes share. Here are a few characteristics of Abstract Class:

    • It cannot be instantiated.
    • It may contain abstract methods and accessors.
    • You cannot modify an abstract class with a sealed modifier.

    Partial Class:

    Partial Keywords show that other parts of the class, interface, or struct can be defined in the namespace. Common characteristics of a Partial Class are:

    • The definition must be in the same namespace and assembly.
    • All parts should have the same accessibility.
    • Different parts must have declared abstract.
    • Nested partial types are allowed.

    Sealed class: This means a class is sealed to prevent inheritance.

    10. What is the difference between a class and a struct?

    Both Class and Struct are user-defined data types but come with a few differences as follows:

    Class:

    • A class is a user-defined blueprint from which objects are created. A class includes the methods and fields into a single unit.
    • A C# in class inherits from the System. Objective Type.
    • Classes are used for large data and can be inherited from other classes.
    • A class can be an abstract type.
    • We can create a default constructor.

    Struct :

    • A structure can’t be abstract.
    • Struct can’t be inherited from other types.
    • The struct is value in C#, and it inherits from the System.Value Type.
    • You don’t need to create an object with a new keyword.
    • Struct does not have permission to create any default constructor.

    11. What is the difference between the interface and abstract class?

    Abstract class

    Interface

    It contains both definition and declaration parts.

    It only has a declaration part.

    It has a constructor.

    It does not contain static members.

    It contains static members.

    It does not contain static members.

    It is used to implement the core identity of the class.

    It is used to implement the peripheral abilities of the class.

    An abstract class can contain methods, fields, constants, etc.

    The interface can only contain methods.

    It can be fully, partially, interface, or not implemented.

    It should be fully implemented.

    12. What is enum in C#?

    An enum is the value data type in C# and is mainly used to assign the names and string values to integral constants, which makes the program easy to read. It is a primitive data type that is user-defined. Additionally, an enum can be an integer (int, byte, double, float, etc.). But, if you use it beside int., it has to be cast. The underlying default type of the enumeration element is int.

    13. What is the difference between the break and continue in C#?

    Break Statement

    Continue Statement

    This statement let users exit from the loop construct.

    The user cannot exit from the loop construct.

    Can be used with the switch statement. You can also use it in the do-while loop, for-loop, and the while loop.

    Cannot use with a switch statement. You can use it within the for loop, do-while loop, and while loop.

    When the control encounter breaks the statement, it exits immediately.

    It passes automatically when the control encounters the continued statement.

    The break statement causes a loop or switches to terminate the case at the time of execution.

    The continue statement doesn’t cause loop termination; instead, it gets passed to the next termination.

    It cannot be denoted as a break;

    It can be denoted as continue;

    14. What is the difference between ref and out keywords?

    The ref is a keyword in C# that is used to pass arguments for the reference or in other words if any changes made in this argument will reflect in that variable when the control return to the calling method.

    The out is a keyword in C# which is used for passing the arguments to the methods as a reference type.

    Ref

    Out

    You need to analyze the parameters before passing them to ref.

    It is not necessary to initialize the parameters before passing them out.

    No need to initialize the value of a parameter before returning to the calling method.

    It is important to initialize the value.

    Change in passing value of the ref parameter = change in the value of the passed parameter.

    The declaring of parameters is useful when the return has more than one value.

    The data is passed in bi-directional when the ref keyword is used.

    The data is only passed in unidirectional.

    15. What are boxing and unboxing in C#?

    Boxing means converting any value type to the ‘object’ type or to any interface type implemented by using this type. When the CLR boxes a value type, it wraps the value in the System. Object and store it in a managed heap.

    On the other hand, unboxing extracts the value type from the object or from the interface type to the value type which implements the interface. An unboxing operation consists of

    Copying value from the instance into the value-type variable.

    Checking the object instance to ensure that it is the boxed value of the given value type.

    16. What are the properties in C#?

    Properties are known as a special type of class member, which helps provide a flexible mechanism to read, write or compute the values of specific fields. Also called accessors, properties can be used if they are public data members. This access to data easily also promotes the flexibility of the methods. Using properties, you can also achieve encapsulation; it uses pre-defined methods, which are ‘set’ and ‘get’ to access the properties.

    17. What are accessors?

    Accessors are the block of ‘get accessor’ and ‘set accessor,’ which are important to restrict the accessibility of the properties. Based on the ‘set’ and ‘get,’ the properties are defined in different types:

    • Read and Write Properties: When the property contains both set and get methods.
    • Read-only Properties: When there’s only a ‘get’ method.
    • Write-only properties: When there is only a ‘set’ method.
    • Auto implemented properties: When there’s no logic in accessors.

    18. What are early binding and late binding in C#?

    Early Binding:

    In Early binding, the class information is used to solve the method call. Also called Static binding, this occurs at the compile time. Early binding objects are strong type objects or static objects in which the methods, properties, and functions are detected and checked at the time of compilation. The biggest advantage of early binding is the ease of development and performance.

    Late Binding (Dynamic binding):

    In late binding functions, variables, methods, and properties are detected and checked at the run-time. One of the biggest advantages of Late binding is that the objects of this type can accept any object but lack the advantages of early-bound objects.

    19. What is a jagged array?

    A jagged array is the ‘array of array’ where member arrays can be of varied sizes, or you can say that the length of each array can be different.

    20. Can you give an example of a sealed class in C#?

    Here’s an example of a sample code of sealed class in C#:

    class X {}
    
    sealed class Y : X {}
    
     Sealed methods –
    
     class A
    
    {
    
     protected virtual void First() { }
    
     protected virtual void Second() { }
    
    }
    
    class B : A
    
    {
    
     sealed protected override void First() {}
    
     protected override void Second() { }
    
    }

    If any class enters from class B, the method- ‘first’ will not be overridable as it is sealed in class B.

    21. Why do you use ‘using’ in C#?

    ‘Using’ statements call the ‘dispose of’ method internally; using keyword is used to include a namespace in the program.

    22. How to sort an array in c#?

    To sort an array, you can use Array.sort(array) function.

    23. Do multiple inheritances supported in C#?

    No, the C# does’t support multiple inheritances.

    24. What is do-while and for loop?

    While loop helps check the condition first so that it may not enter the loop if the condition is false.

    So while, on the other hand, executes the content of the loop before checking the condition for the while loop.

    For loop is the same as while loop, except that the initialization of a variable, condition check, and increment happens at one place.

    25. What is the difference between a string and StringBuilder in C#?

    String: String is immutable, which means once you create a string object, you can’t modify it. Any operation like replace, insert or append happens to change the string; they will automatically discard the old value and create the new one.

    Example:

    String str = ‘hello’;
    
    //It creates a new string instance instead of changing the old one
    
    str += “help”;
    
    str += “test”;

    StringBuilder:

    String builder is mutable, which means if you create a string builder object, you can perform operations like replace or append without creating new instances every time.

    StringBuilder belongs to the System. Text namespace

    Example:

    StrigBuilder sb = new StringBuilder (“”);
    
    //It doesn’t create new instances every time.
    
    sb.Append (“hello”);
    
    sb.Append (“help);
    
    string str = sb.ToString();

    26. What are the different types of delegates in C#?

    The following are types of delegates in C#:

    • Single Delegates
    • Multicast Delegate
    • Generic Delegates

    Intermediate-Level C# Interview Questions

    27. What are multicast delegates?

    A multicast delegate is the multiple handlers assigned to it multicast delegate. Every handler is assigned a method.

    28. What Nullable type in C#?

    Variable types do not hold null values, so we have to use nullable types to hold null values. Nullable types can either be null or have other values.

    Eg,

    int? null variable =null;

    29. What are the ways you can overload a method?

    Methods can be overloaded using a different order of parameters, the data type of parameter, and by using a different number of parameters.

    30. What is the difference between is and as operators in c#?

    ‘Is’ operator is used to check the compatibility of the object with a specific type, and it returns the Boolean Function.

    ‘As’ is used for casting the object to a type or class.

    31. What is thread.sleep() in threading?

    Thread.Sleep methods are used to pause the thread execution. This method takes the integer value that helps determine how long the thread should sleep. For instance,

    Thread.currenttime.sleep(2000)// 2 Seconds

    32. Can you make the thread sleep for infinite time?

    Yes, by using:

    Thread.sleep(System.Threading.Timeout.Infinite)

    To interrupt this method, you can call Thread.interrupt method

    33. What is serialization?

    Serialization is the process of transferring an object through a network so that you have to convert the object into a different stream of bytes.

    34. What is hashtable in C#?

    A hashtable is a collection of key-value pairs; it contains different values based on the key.

    35. How to implement a singleton design pattern in c#?

    In singleton, a class can have only one instance and provide an access point to it.

    For example,

    Public sealedclass Singleton
    
    {
    
    Private staticreadonly Singleton _instance = newSingleton();

    Which string method is used for the concatenation of two strings?

    The “Concat” method is used to concentrate two strings.

    For instance:

    string.Concat(firstnamestr, lastnamestr)

    36. What do you mean by circular reference in c#?

    A circular reference is a situation where multiple resources are dependent on each other. It causes a look condition, which makes the resources to be unused.

    37. What do you mean by anonymous type in C#?

    This is added in the C# 3.0 version. This allows you to create an object at the compile time.

    Here’s the sample code:

    Var myTestCategory +new {categoryid=1, CategoryName= “category1”);

    38. Explain different types of unit test cases?

    Some of the common unit test cases are as follows:

    • Positive test cases
    • Negative test cases
    • Exception test cases

    Advanced-Level C# Interview Questions

    39. What is a static constructor in C#?

    A constructor is static when it will invoke once by all the number of instances of a class. The static constructor will initialize the static fields of a class.

    For instance:

    class MyClass
    
     {
    
    public string prop1, prop2;
    
    public MyClass(string a, string b)
    
    {
    
    prop1 = a;
    
    prop2 = b;
    
    }
    
    Static MyClass()
    
    {
    
    Console.WriteLine(“Static Constr Test”);
    
    }
    
    public MyClass(MyClass myobj) // Copy Constructor
    
    {
    
    prop1 = myobj.prop1;
    
    prop2 = myobj.prop2;
    
    }
    
     }

    40. What are indexers in C#?

    Indexers are used to allow the classes to be indexed like arrays. They help resemble the property's structure. But the only difference is that indexer’s assessors take parameters.

    For instance:

    Class MyCollection <T>
    
    {
    
    private T[] myArr = new T[100];
    
    public T this[int t]
    
    {
    
    get
    
    {
    
    return myArr[t];
    
    }
    
    set
    
    {
    
    myArr[t] = value;
    
    }
    
    }
    
     }

    41. What are the collection types that are used in the C#?

    Below is the collection type in the C#:

    • Stack
    • Queue
    • SortedList
    • HashTable
    • Bit Array
    • ArrayList

    42. Explain some pre-defined attributes in C#?

    Here are some pre-defined attributes in C#:

    • Obsolete
    • Attribute Usage
    • Conditional

    43. What are the methods and properties of Class in C#?

    Here are some methods and properties of the thread class:

    • CurrentThread
    • CurrentContext
    • IsAlive
    • IsBackground
    • Priority
    • CurrentCulture

    44. What is constructor overloading in C#.net?

    Constructor overloading means you can create n number of constructors for the same class but with different signatures.

    For instance:

    public class Employee { public Employee() { }
    
    public Employee(String Name) { }
    
    }

    45. Explain some exceptions in C#?

    Some of the common exceptions in C# are as follows:

    • NullReferenceException
    • IndexOutOfRangeException
    • DivideByZeroException
    • StackOverflowException
    • InvalidOperationException
    • ArgumentNullException

    46. Why do you use the “const” keyword in C#?

    “const” is used for making an entity constant.

    For instance:

    Const string_name = “techstudy”;

    Once you define a variable as a const, then you can’t reassign the value of that variable (string_name).

    47. How do you measure the size of value type?

    By using the SizeOf operator, you can measure the size of the value.

    Example:

    Console.WriteLine (“the size of Long is {0}.” , sizeof(long));

    Output:

    The Size of long is 8.

    48. What is IDE given by Microsoft for C# development?

    Some of the IDEs used for C# development are as follows:

    • VCE (Visual Studio Express)
    • VS (Visual Studio)
    • Visual Web Developer

    49. What are the attributes in C#?

    Attributes help convey the information for the runtime about the behavior of elements like ‘methods,’ ‘classes,’ ‘enums,’ etc. You can use them to add metadata like classes, comments, compiler instructions, etc.

    50. What do you understand by reflection in C#?

    Reflection in C# is useful in extracting the metadata from data types during runtime.

    Conclusion

    This completes our list of the top C# interview questions for both beginners and professionals. Go through this list to recollect all the C# concepts and ace your upcoming C# interview.

    How many answers do you already know? Do let us in the comments below.

    If you want to get familiar with some more C#.NET interview questions, purchase this course here.

    People are also reading:

    FAQs


    There is a need for the Conversion of data types in C# to prevent runtime errors during the conversion of data types.

    C# supports only the Explicit data conversion.

    The subsets of the int data type are long, float, and double.

    The correct way of incrementing operators in C# is c+=1.

    You can define a reference variable using the 'ref' reference modifier.

    Leave a Comment on this Post

    0 Comments