About C Sharp Interview Preparation
C Sharp interview questions and answers for freshers and experienced candidates, including basic concepts, advanced topics, practical examples, project discussion points and common HR preparation guidance.
For better preparation, read each question carefully, understand the concept, prepare one real example,
and connect your answer with your project or work experience.
C Sharp Questions List
Quick list of important C Sharp interview questions. Detailed answer previews are available below.
- What is C Sharp Language?
- What are namespaces, and how they are used?
- What is a constructor?
- What is the GAC, and where is it located?
- Why are strings in C# immutable?
- What is DLL Hell, and how does .NET solve it?
- How are methods overloaded?
- How do you prevent a class from being inherited?
- What is the execution entry point for a C# console application?
- How do you initiate a string without escaping each backslash?
- what is c sharp
- What is object-oriented programming (OOP) Language?
- Explain about C# Language.
- Types of comments in C#?
- feature of C# language?
- What is a Class?
- What is object?
- What is Constructors, explain with syntax
- index value of the first element in an array?
- Different between method overriding and method overloading?
- Explain use of Abstract and Sealed Classes in C#?
- What is Static Classes?
- Explain Static Class Members.
- Which are Access Modifiers available in C#?
- Data Types in C#?
- What are sealed classes in C#?
- What are delegates?
- What is the difference between a Struct and a Class?
- What is difference between is and as operators in c#?
- What are C# attributes and its significance?
Question 1: What is C Sharp Language?
Answer: C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. You can use C# to create traditional Windows client applications, XML Web services, distributed components, client-server applications, database applications, and much, much more. Visual C# provides an advanced code editor, convenient user interface designers, integrated debugger, and many other tools to make it easier to develop applications based on version 4.0 of the C# language and version 4.0 of the .NET Framework. C# syntax is highly expressive, yet it is also simple ...
View detailed answer →
Question 2: What are namespaces, and how they are used?
Answer: Namespaces are used to organize classes within the .NET Framework. They dictate the logical structure of the code. They are analogous to Java packages, with the key difference being Java packages define the physical layout of source files (directory structure) while .NET namespaces do not. However, many developers follow this approach and organize their C# source files in directories that correlate with namespaces. The .NET Framework has namespaces defined for its many classes, such as System.Xml--these are utilized via the using statement. Namespaces are assigned to classes via the namespace keyword.
View detailed answer →
Question 3: What is a constructor?
Answer: A constructor is a class member executed when an instance of the class is created. The constructor has the same name as the class, and it can be overloaded via different signatures. Constructors are used for initialization chores.
View detailed answer →
Question 4: What is the GAC, and where is it located?
Answer: The GAC is the Global Assembly Cache. Shared assemblies reside in the GAC; this allows applications to share assemblies instead of having the assembly distributed with each application. Versioning allows multiple assembly versions to exist in the GAC--applications can specify version numbers in the config file. The gacutil command line tool is used to manage the GAC.
View detailed answer →
Question 5: Why are strings in C# immutable?
Answer: Immutable means string values cannot be changed once they have been created. Any modification to a string value results in a completely new string instance, thus an inefficient use of memory and extraneous garbage collection. The mutable System.Text.StringBuilder class should be used when string values will change.
View detailed answer →
Question 6: What is DLL Hell, and how does .NET solve it?
Answer: DLL Hell describes the difficulty in managing DLLs on a system; this includes multiple copies of a DLL, different versions, and so forth. When a DLL (or assembly) is loaded in .NET, it is loaded by name, version, and certificate. The assembly contains all of this information via its metadata. The GAC provides the solution, as you can have multiple versions of a DLL side-by-side.
View detailed answer →
Question 7: How are methods overloaded?
Answer: Methods are overloaded via different signatures (number of parameters and types). Thus, you can overload a method by having different data types, different number of parameters, or a different order of parameters.
View detailed answer →
Question 8: How do you prevent a class from being inherited?
Question 9: What is the execution entry point for a C# console application?
Question 10: How do you initiate a string without escaping each backslash?
Answer: You put an @ sign in front of the double-quoted string. String ex = @"This has a carriage returnrn"
View detailed answer →
Question 11: what is c sharp
Question 12: What is object-oriented programming (OOP) Language?
Answer: Object-oriented programming (OOP) is a programming language model organized around objects rather than "actions" and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data.
View detailed answer →
Question 13: Explain about C# Language.
Answer: C# is a OOPs language, .net framework use to compiled it, to generate machine code.
View detailed answer →
Question 14: Types of comments in C#?
Answer: Single line comments// for single line commentsMultiple line comments/* for multi line comments */XML tags comments/// XML tags displayed in a code comment
View detailed answer →
Question 15: feature of C# language?
Answer: Boolean ConditionsAutomatic Garbage CollectionStandard LibraryAssembly VersioningProperties and EventsDelegates and Events ManagementEasy-to-use GenericsIndexersConditional CompilationSimple MultithreadingLINQ and Lambda ExpressionsIntegration with Windows
View detailed answer →
Question 16: What is a Class?
Answer: a set or category of things having some property or attribute in common and differentiated from others by kind, type, or quality.
View detailed answer →
Question 17: What is object?
Answer: Objects are created from Classes, in C#, is an instance of a class that is created dynamically. Object is also a keyword that is an alias for the predefined type System.
View detailed answer →
Question 18: What is Constructors, explain with syntax
Answer: A is special method of the class that will be automatically invoked when an instance of the class is created is called as constructor.Constructors are mainly used to initialize private fields of the class while creating an instance for the class.When you are not creating a constructor in the class, then compiler will automatically create a default constructor in the class that initializes all numeric fields in the class to zero and all string and object fields to null.Syntax.[Access Modifier] ClassName([Parameters]){}
View detailed answer →
Question 19: index value of the first element in an array?
Question 20: Different between method overriding and method overloading?
Answer: In Overriding methods it will create two or more methods with same name and same parameter in different classes.while Overloading it will create more then one method with same name but different parameter in same class.
View detailed answer →
Question 21: Explain use of Abstract and Sealed Classes in C#?
Answer: The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual.
View detailed answer →
Question 22: What is Static Classes?
Answer: A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated.In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.
View detailed answer →
Question 23: Explain Static Class Members.
Answer: A non-static class can contain static methods, fields, properties, or events.The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
View detailed answer →
Question 24: Which are Access Modifiers available in C#?
Answer: All types and type members have an accessibility level, which controls whether they can be used from other code in your assembly or other assemblies.You can use the following access modifiers to specify the accessibility of a type or member when you declare it:public: The type or member can be accessed by any other code in the same assembly or another assembly that references it.private: The type or member can be accessed only by code in the same class or struct.protected: The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.internal: The type or member ...
View detailed answer →
Question 25: Data Types in C#?
Answer: bool, byte, char, decimal, double, float, int, long, sbyte, short, uint, ulong, ushort.More question coming soon.. we are updating our list of ques and answer... :)keep wait and watch for few days.
View detailed answer →
Question 26: What are sealed classes in C#?
Answer: We create sealed classes when we want to restrict the class to be inherited. Sealed modifier used to prevent derivation from a class. If we forcefully specify a sealed class as base class then a compile-time error occurs.
View detailed answer →
Question 27: What are delegates?
Answer: Delegates are same are function pointers in C++ but the only difference is that they are type safe unlike function pointers. Delegates are required because they can be used to write much more generic type safe functions.
View detailed answer →
Question 28: What is the difference between a Struct and a Class?
Answer: Structs are value-type variables and classes are reference types. Structs stored on the stack, causes additional overhead but faster retrieval. Structs cannot be inherited.
View detailed answer →
Question 29: What is difference between is and as operators in c#?
Answer: “is” operator is used to check the compatibility of an object with a given type and it returns the result as Boolean. “as” operator is used for casting of object to a type or a class
View detailed answer →
Question 30: What are C# attributes and its significance?
Answer: C# provides developers a way to define declarative tags on certain entities eg. Class, method etc. are called attributes. The attribute’s information can be retrieved at runtime using Reflection.
View detailed answer →
Question 31: What is a NullReferenceException and how do I fix it?
Answer: You are trying to use something that is null (or Nothing in VB.NET). This means you either set it to null, or you never set it to anything at all. Like anything else, null gets passed around. If it is null in method "A", it could be that method "B" passed a null to method "A". The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a NullReferenceException.
View detailed answer →
Question 32: How to update the GUI from another thread in C#?
Answer: private delegate void SetControlPropertyThreadSafeDelegate( Control control, string propertyName, object propertyValue);public static void SetControlPropertyThreadSafe( Control control, string propertyName, object propertyValue){ if (control.InvokeRequired) { control.Invoke(new SetControlPropertyThreadSafeDelegate (SetControlPropertyThreadSafe), new object[] { control, propertyName, ...
View detailed answer →
Question 33: How to use reflection to call generic Method?
Answer: You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod: MethodInfo method =typeof(Sample).GetMethod("GenericMethod");MethodInfo generic = method.MakeGenericMethod(myType); generic.Invoke(this,null); EDIT: For a static method, pass null as the first argument to Invoke. That's nothing to do with generic methods - it's just normal reflection.
View detailed answer →
Question 34: How to properly clean up Excel interop objects
Answer: Excel does not quit because your app is still holding references to COM objects. I guess you're invoking at least one member of a COM object without assigning it to a variable. For me it was the excelApp.Worksheets object which I directly used without assigning it to a variable: Worksheet sheet = excelApp.Worksheets.Open(...);...Marshal.ReleaseComObject(sheet); What I didn't know was that internally C# created a wrapper for the Worksheets COM object which didn't get released by my code (because I wasn't aware of it) and was the cause why Excel was not unloaded. I found the solution to my problem on this page, which also has a nice rule for th...
View detailed answer →
Question 35: Why are mutable structs evil?
Answer: Structs are value types which means they are copied when they are passed around. So if you change a copy you are changing only that copy, not the original and not any other copies which might be around. If your struct is immutable then all automatic copies resulting from being passed by value will be the same. If you want to change it you have to consciously do it by creating a new instance of the struct with the modified data. (not a copy)
View detailed answer →
Question 36: How do you convert Byte Array to Hexadecimal String, and vice versa?
Answer: public static string ByteArrayToString(byte[] ba){ StringBuilder hex = new StringBuilder(ba.Length * 2); foreach (byte b in ba) hex.AppendFormat("{0:x2}", b); return hex.ToString();}
View detailed answer →
Question 37: How do I calculate relative time?
Answer: const int SECOND = 1;const int MINUTE = 60 * SECOND;const int HOUR = 60 * MINUTE;const int DAY = 24 * HOUR;const int MONTH = 30 * DAY;var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);double delta = Math.Abs(ts.TotalSeconds);if (delta < 0){ return "not yet";}if (delta < 1 * MINUTE){ return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";}if (delta < 2 * MINUTE){ return "a minute ago";}if (delta < 45 * MINUTE){ return ts.Minutes + " minutes ago";}if (delta < 90 * MINUTE){ return "an hour ago";}if (delta < 24 * HOUR){ return ts.Hours + " hours ago";}if (delta <...
View detailed answer →
Question 38: What is the difference between a Field and a Property in C#?
Answer: Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class. publicclassMyClass{// this is a field. It is private to your class and stores the actual data.privatestring _myField;// this is a property. When you access it uses the underlying field, but only exposes// the contract that will not be affected by the underlying fieldpublicstringMyField{ get {return _myField;}set{ _myField = value;}}}
View detailed answer →
Question 39: Why is it important to override GetHashCode when Equals method is overridden?
Answer: Yes, it is important if your item will be used as a key in a dictionary, or HashSet<T>, etc - since this is used (in the absence of a custom IEqualityComparer<T>) to group items into buckets. If the hash-code for two items does not match, they may never be considered equal (Equals will simply never be called). The GetHashCode() method should reflect the Equals logic; the rules are: if two things are equal (Equals(...) == true) then they must return the same value for GetHashCode() if the GetHashCode() is equal, it is not necessary for them to be the same; this is a collision, and Equals will be called to see if it is a real equali...
View detailed answer →
Question 40: How to force my .NET App to run as administrator on Windows 7?
Answer: You'll want to modify the manifest that gets embedded in the program. This works on VS2008 and higher: Project + Add New Item, select "Application Manifest File". Change the <requestedExecutionLevel> element to: <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/> The user gets the UAC prompt when they start the program. Use wisely, their patience can wear out quickly.
View detailed answer →
Question 41: Top reason to use C# language?
Answer: Modern, general-purpose programming language Object oriented. Component oriented. Easy to learn. Structured language. It produces efficient programs. It can be compiled on a variety of computer platforms. Part of .Net Framework.
View detailed answer →
Question 42: Types of Constructors
Answer: Basically constructors are 5 types those are Default Constructor Parameterized Constructor Copy Constructor Static Constructor Private Constructor
View detailed answer →
Question 43: What is C#?
Answer: C# is an object oriented, type safe and managed language that is compiled by .Net framework to generate Microsoft Intermediate Language.
View detailed answer →
Question 44: Can multiple catch blocks be executed?
Answer: No, Multiple catch blocks can’t be executed. Once the proper catch code executed, the control is transferred to the finally block and then the code that follows the finally block gets executed.
View detailed answer →
Question 45: What is the difference between public, static and void?
Answer: Public declared variables or methods are accessible anywhere in the application. Static declared variables or methods are globally accessible without creating an instance of the class. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created. And Void is a type modifier that states that the method or variable does not return any value
View detailed answer →
Question 46: Define Constructors?
Answer: A constructor is a member function in a class that has the same name as its class. The constructor is automatically invoked whenever an object class is created. It constructs the values of data members while initializing the class.
View detailed answer →
Question 47: What is Jagged Arrays?
Answer: The array which has elements of type array is called jagged array. The elements can be of different dimensions and sizes. We can also call jagged array as Array of arrays.
View detailed answer →
Question 48: What is the difference between ref & out parameters?
Answer: An argument passed as ref must be initialized before passing to the method whereas out parameter needs not to be initialized before passing to a method.
View detailed answer →
Question 49: What is the use of using statement in C#?
Answer: The using block is used to obtain a resource and use it and then automatically dispose of when the execution of block completed.
View detailed answer →
Question 50: Can "this" be used within a static method?
Answer: We can’t use ‘This’ in a static method because we can only use static variables/methods in a static method.
View detailed answer →
Question 51: What is difference between constants and read-only?
Answer: Constant variables are declared and initialized at compile time. The value can’t be changed after wards. Read-only variables will be initialized only from the Static constructor of the class. Read only is used only when we want to assign the value at run time.
View detailed answer →
Question 52: What is an interface class?
Answer: Interface is an abstract class which has only public abstract methods and the methods only have the declaration and not the definition. These abstract methods must be implemented in the inherited classes.
View detailed answer →
Question 53: What are Custom Control and User Control?
Answer: Custom Controls are controls generated as compiled code (Dlls), those are easier to use and can be added to toolbox. Developers can drag and drop controls to their web forms. Attributes can be set at design time. We can easily add custom controls to Multiple Applications (If Shared Dlls), If they are private then we can copy to dll to bin directory of web application and then add reference and can use them. User Controls are very much similar to ASP include files, and are easy to create. User controls can’t be placed in the toolbox and dragged – dropped from it. They have their design and code behind. The file extension for user c...
View detailed answer →
Question 54: What is the difference between Array and Arraylist?
Answer: In an array, we can have items of the same type only. The size of the array is fixed. An arraylist is similar to an array but it doesn’t have a fixed size.
View detailed answer →
Question 55: What are the differences between System.String and System.Text.StringBuilder classes?
Answer: System.String is immutable. When we modify the value of a string variable then a new memory is allocated to the new value and the previous memory allocation released. System.StringBuilder was designed to have concept of a mutable string where a variety of operations can be performed without allocation separate memory location for the modified string.
View detailed answer →
Question 56: What's the difference between the System.Array.CopyTo() and System.Array.Clone() ?
Answer: Using Clone() method, we creates a new array object containing all the elements in the original array and using CopyTo() method, all the elements of existing array copies into another existing array. Both the methods perform a shallow copy.
View detailed answer →
Question 57: How can we sort the elements of the array in descending order?
Question 58: What's the difference between an interface and abstract class?
Answer: Interfaces have all the methods having only declaration but no definition. In an abstract class, we can have some concrete methods. In an interface class, all the methods are public. An abstract class may have private methods.
View detailed answer →
Question 59: What is the difference between Finalize() and Dispose() methods?
Answer: Dispose() is called when we want for an object to release any unmanaged resources with them. On the other hand Finalize() is used for the same purpose but it doesn’t assure the garbage collection of an object.
View detailed answer →
Question 60: What are circular references?
Answer: Circular reference is situation in which two or more resources are interdependent on each other causes the lock condition and make the resources unusable.
View detailed answer →
Question 61: What are generics in C#.NET?
Answer: Generics are used to make reusable code classes to decrease the code redundancy, increase type safety and performance. Using generics, we can create collection classes. To create generic collection, System.Collections.Generic namespace should be used instead of classes such as ArrayList in the System.Collections namespace. Generics promotes the usage of parameterized types.
View detailed answer →
Question 62: What is an object pool in .NET?
Answer: An object pool is a container having objects ready to be used. It tracks the object that is currently in use, total number of objects in the pool. This reduces the overhead of creating and re-creating objects.
View detailed answer →
Question 63: List down the commonly used types of exceptions in .Net?
Answer: ArgumentException, ArgumentNullException , ArgumentOutOfRangeException, ArithmeticException, DivideByZeroException ,OverflowException , IndexOutOfRangeException ,InvalidCastException ,InvalidOperationException , IOEndOfStreamException , NullReferenceException , OutOfMemoryException , StackOverflowException etc.
View detailed answer →
Question 64: What are Custom Exceptions?
Answer: Sometimes there are some errors that need to be handeled as per user requirements. Custom exceptions are used for them and are used defined exceptions.
View detailed answer →
Question 65: How do you inherit a class into other class in C#?
Answer: Colon is used as inheritance operator in C#. Just place a colon and then the class name. publicclassDerivedClass:BaseClass
View detailed answer →
Question 66: What is the difference between method overriding and method overloading?
Answer: In method overriding, we change the method definition in the derived class that changes the method behavior. Method overloading is creating a method with the same name within the same class having different signatures.
View detailed answer →
Question 67: What are the different ways a method can be overloaded?
Answer: Methods can be overloaded using different data types for parameter, different order of parameters, and different number of parameters.
View detailed answer →
Question 68: Why can't you specify the accessibility modifier for methods inside the interface?
Answer: In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That’s why they all are public.
View detailed answer →
Question 69: How can we set class to be inherited, but prevent the method from being over-ridden?
Answer: Declare the class as public and make the method sealed to prevent it from being overridden.
View detailed answer →
Question 70: What happens if the inherited interfaces have conflicting method names?
Answer: Implement is up to you as the method is inside your own class. There might be problem when the methods from different interfaces expect different data, but as far as compiler cares you’re okay.
View detailed answer →
Question 71: How to implement singleton design pattern in C#?
Answer: In singleton pattern, a class can only have one instance and provides access point to it globally. Eg:{ private static readonly singleton _instance=new singleton(); }
View detailed answer →
Question 72: What is the difference between directcast and ctype?
Answer: DirectCast is used to convert the type of an object that requires the run-time type to be the same as the specified type in DirectCast. Ctype is used for conversion where the conversion is defined between the expression and the type.
View detailed answer →
Question 73: Is C# code is managed or unmanaged code?
Answer: C# is managed code because Common language runtime can compile C# code to Intermediate language.
View detailed answer →
Question 74: Famous Insurance company has a requirement to calculate the age of their customer based on the date of birth received as a string from the user.
Write a program that receives the customer date of birth in the format (dd-mm-yyyy).
Pass this value to a method, 'calculateAge' which returns the calculated age. Keep the method 'static'.
Method to implement:
public static int calculateAge(string dateOfBirth)
Sample Input :
Enter the date of birth (dd-mm-yyyy): 22-10-1984
Sample Output:
36
Answer: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;public class Person{ DateTime dob; public DateTime Dob { get{return dob;} set{dob=value;} }public void DisplayDetails(){ Console.WriteLine(calculateAge(dob));}public static int calculateAge(DateTime dob){ int age=0; age=DateTime.Now.Year-dob.Year; return age; }}namespace DateEx1 //DO NOT CHANGE the namespace name{ public class Program //DO NOT CHANGE the class name { public static void Main(string[] args) //DO NOT CHANGE the 'Main' method signature { Person person=new Person(); Console.WriteLine("Enter the date of birth (dd-mm-yyyy):...
View detailed answer →
Question 75: C SHARP IN GAMING?
Answer: C# is widely-used to create games using the Unity game engine, which is the most popular game engine today. More than a third of top games are made with Unity, and there are approximately 770 million active users of games created using the Unity engine. Unity is also used for VR, with 90% of all Samsung Gear and 53% of all Oculus Rift VR games developed using Unity.
View detailed answer →