(Must read this link or search other link: https://www.simplilearn.com/tutorials/c-sharp-tutorial/c-sharp-interview-questions). In below we write some important question from upper link:
1. What is C#?
C# is an object-oriented programming language compiled by the .NET framework to generate Microsoft Intermediate Language.
Can multiple catch blocks be executed?
No, you cannot execute multiple catch blocks of the same type.
2. What is the difference between static, public, and void?
Public declared variables can be accessed from anywhere in the application.
Static declared variables can be accessed globally without needing to create an instance of the class.
Void is a type modifier which states the method and is used to specify the return type of a method in C#.
3. What is an object?
An object is a class instance that can be used to access class methods. The “New” keyword can be used to construct an object.
4. Define Constructors.
A constructor is a member function with the same name as its class. It is automatically invoked when an object is created and initializes all data members.
5. What are Jagged Arrays?
Arrays comprising elements of type array are called Jagged Arrays. They can have elements of various dimensions and sizes.
6. What is the difference between out and ref parameters?
When an argument is passed as a ref, it must be initialized before passing to the method.
An out parameter need not be initialized before passing to a method.
7. What is the benefit of ‘using’ statement in C#?
The ‘using’ statement is used to obtain a resource for processing before automatically disposing it when execution is completed.
8. What is serialization?
Serialization is the process of converting an object into a stream of bytes for transport through a network.
9. Can “this” command be used within a static method?
No, “this” command cannot be used within a static method.
10. Differentiate between Break and Continue Statement.
Continue statement: Used to skip the current iteration and proceed to the next iteration of the loop.
Break statement: Used to exit the loop immediately.
11. List the different types of comments in C#.
The different types of comments in C# are:
· XML comments
· Single Line comments
· Multi-line comments
12. Explain the four steps involved in the C# code compilation.
The four steps of code compilation in C# include:
· Source code compilation in managed code.
· Merging newly created code with assembly code.
· Loading the Common Language Runtime (CLR).
· Executing assembly through CLR.
13. Discuss the various methods to pass parameters in a method.
The various methods of passing parameters in a method include:
· Output parameters
· Value parameters
· Reference parameters
14. Name all the C# access modifiers.
The C# access modifiers are:
· Private
· Public
· Internal
· Protected
15. Mention all the advantages of C#
The advantages of C# include:
· Component-oriented
· Object-oriented
· Easy syntax
· Part of the .NET framework
· Easy to learn and maintain
16. Mention the important IDEs for C# development provided by Microsoft.
The important IDEs for C# development provided by Microsoft are:
· MonoDevelop
· Visual Studio Code (VS Code)
· Browxy
· Visual Studio Express (VSE)
· Visual Web Developer (VWD)
17. Why do we use C# language?
We use the C# language because it is component-oriented, easy to pass parameters, can be compiled on many platforms, follows a structured approach, and is easy to learn and read.
18. Mention the features of C# briefly.
Some of the main features of C# are:
· Type safety
· Object-oriented
· Cross-platform
· Platform-independent
· General-purpose
19. What is meant by Unmanaged or Managed Code?
Managed code is executed by the Common Language Runtime (CLR), while unmanaged code is executed by a runtime that is not part of the .NET platform.
20. What is meant by an Abstract Class?
An abstract class is a type of class whose objects cannot be instantiated and may contain one or more abstract methods.
21. Differentiate between finalize blocks and finalize.
Finalize blocks are used for exception handling and are always called after try and catch blocks. Finalize methods, on the other hand, are called just before garbage collection.
22. What is meant by an Interface?
An interface is a class that only contains method declarations and no implementation.
23. What is meant by a Partial Class?
A partial class breaks a class's definition into various parts in the same or other source code files.
24. What is the difference between read-only and constants?
Constants are declared and initialized at compile time and cannot be changed, while read-only variables can be assigned a value at runtime but cannot be changed thereafter. (Read = Runtime technique to remember)
25. What is an interface class?
An interface class is an abstract class with only public abstract methods that must be implemented in inherited classes.
26. What are reference types and value types?
Value types store data values directly, while reference types store references to the memory location of the data.
27. What are User Control and Custom Control?
Custom Controls are compiled code and can be added to the toolbox, while User Controls are similar to ASP include files and cannot be added to the toolbox.
28. What are sealed classes in C#?
Sealed classes are classes that cannot be inherited or overridden.
29. What is method overloading?
Method overloading is the ability to define multiple methods with the same name but different parameter lists.
30. What is the difference between ArrayList and Array?
An array has a fixed size and can only contain elements of the same type, while an ArrayList can dynamically grow in size and can contain elements of different types.
31. Is it possible for a private virtual method to be overridden?
No, a private virtual method cannot be overridden as it is not accessible outside the class.
32. Describe the accessibility modifier “protected internal”.
Protected internal variables or methods can be accessed within the same assembly and from classes that inherit the parent class.
33. What are the differences between System.String and System.Text.StringBuilder classes?
System.String is immutable, while System.Text.StringBuilder is mutable and allows for efficient manipulation of strings.
34. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method creates a new array with the same elements as the original, while the CopyTo() method copies elements into an existing array.
35. How can the Array elements be sorted in descending order?
You can sort the array using the Sort() method and then reverse the array.
36. What’s the difference between an abstract and interface class?
An interface can only contain method declarations, while an abstract class can contain method implementations.
37. What is the difference between Dispose() and Finalize() methods?
Dispose() is used to release unmanaged resources, while Finalize() is called before garbage collection but does not guarantee cleanup.
38. What are circular references?
Circular references occur when two or more resources depend on each other, causing a deadlock condition.
39. What are generics in C# .NET?
Generics allow for the creation of classes and methods that can work with any data type.
40. What is an object pool in .NET?
An object pool is a container that holds objects ready to be used, reducing the need for object creation and destruction.
41. List down the most commonly used types of exceptions in .NET
· ArgumentException
· ArithmeticException
· DivideByZeroException
· OverflowException
· InvalidCastException
· InvalidOperationException
· NullReferenceException
· OutOfMemoryException
· StackOverflowException
42. What are Custom Exceptions?
Custom exceptions are user-defined exceptions used to handle errors according to specific requirements.
43. What are delegates?
Delegates are type-safe function pointers used in C# for creating generic, type-safe functions. We can pass whole method as method via delegate.
44. What is the difference between method overriding and method overloading?
Method overriding replaces a method definition in a derived class, changing its behavior, while method overloading involves creating multiple methods with the same name but different signatures in the same class.
45. How do you inherit a class into another class in C#?
In C#, you use the colon (:) operator to denote inheritance, followed by the class name.
46. What are the various ways that a method can be overloaded?
Methods can be overloaded by using different data types, different orders, or different numbers of parameters.
47. Why can’t the accessibility modifier (public, private, internal, protected) be specified for methods within the interface?
All methods in an interface are implicitly public because they are meant to be overridden in derived classes.
48. How can we set the class to be inherited, but prevent the method from being overridden? The class needs to be declared as public, and the method needs to be sealed.
49. What happens if the method names in the inherited interfaces conflict?
There may be conflicts if the methods expect different data types, but the compiler should handle this without issue.
50. What is the difference between a Struct and a Class?
Structs are value types, while classes are reference types. Structs are value types, stored on the stack, ideal for small data structures with no inheritance. Classes are reference types, stored on the heap, suitable for complex objects, inheritance, and polymorphism.
51. How to use nullable types in .NET?
Nullable types in .NET allow value types to have null values.
52. How can we make an array with non-standard values?
You can create an array with non-default values using
int[] arrayWithNonStandardValues = Enumerable.Repeat(42, 5).ToArray();
53. What is the difference between “is” and “as” operators in C#?
The "is" operator checks compatibility and returns a Boolean, while the "as" operator is used for casting and returns null on failure.
54. What is a multicast delegate?
A multicast delegate can point to multiple methods simultaneously.
55. What are indexers in C# .NET?
(ক্লাসের এলিমেন্টকে এ্যারের মতো ব্যবহার করতে দেয়)।
Indexers in C# are similar to arrays, allowing class instances to be indexed.
Indexers provide a way to access elements of a collection or class as if they were arrays, enabling convenient and intuitive access to internal data structures without exposing them directly.
You would use an indexer instead of directly using an array when you want to encapsulate the data structure within a class, providing controlled access and potentially adding additional functionality or validation beyond simple array access.
56. What is the distinction between “throw” and “throw ex” in .NET?
"throw" retains the original error stack, while "throw ex" keeps the stack trace from the throw point.
57. What are C# attributes and their significance?
C# attributes provide declarative tags for classes and methods, allowing runtime retrieval of associated information.
58. In C#, how do you implement the singleton design pattern?
Singleton design pattern ensures a class has only one instance globally accessible.
59. What’s the distinction between directcast and ctype?
DirectCast is used for runtime type conversion, while CType is used for conversion between expression and type.
60. Is C# code managed or unmanaged code?
C# code is managed code compiled to Intermediate Language by the Common Language Runtime.
61. What is a Console application?
A console application runs in the command prompt window.
62. What are namespaces in C#?
Namespaces help avoid naming conflicts by organizing code into distinct sets of names.
63. What is the distinction between the Dispose() and Finalize() methods?
Dispose() is used to release resources explicitly, while Finalize() is a destructor called by the garbage collector.
64. Write features of Generics in C#?
Generics in C# allow for type-safe, reusable code by defining type parameters.
65. Difference between SortedList and SortedDictionary in C#?
SortedList is a collection of key/value pairs sorted by keys, while SortedDictionary maintains keys in sorted order.
66. What is Singleton design pattern in C#?
Singleton design pattern ensures a class has only one instance globally accessible.
67. What is tuple in C#?
Tuple is a data structure that holds multiple related values.
68. What are Events?
Events are notifications that something has occurred.
69. What is Constructor Chaining in C#?
Constructor chaining allows one constructor to call another constructor in the same class.
70. What is a multicasting delegate in C#?
A multicasting delegate can point to multiple methods simultaneously.
71. What are Accessibility Modifiers in C#?
Accessibility modifiers control the visibility and accessibility of members in classes, structs, and interfaces.
72. What is a Virtual Method in C#?
A virtual method can be overridden in derived classes to change its behavior.
73. What is Multithreading with .NET?
Multithreading allows multiple threads to execute independently within a single process.
74. In C#, what is a Hash table class?
A Hash table class represents a collection of key/value pairs organized based on the hash code of the keys.
75. What is LINQ in C#?
LINQ (Language Integrated Query) allows querying data sources in C#.
76. Why can’t a private virtual procedure in C# be overridden?
Private virtual methods are not accessible outside the class and cannot be overridden.
77. What is File Handling in C#?
File handling involves operations such as creating, reading, writing, and deleting files.
78. What do you understand about Get and Set Accessor properties?
Get and Set accessors are used to control access to class fields, providing encapsulation.
79. What is the Race condition in C#?
A race condition occurs when two or more threads access shared data and try to change it at the same time.
80. Why are Async and Await used in C#?
Async and Await keywords are used for asynchronous programming, allowing non-blocking execution of tasks.
81. What is an Indexer in C#?
An indexer is a property that allows accessing elements of a class using array-like syntax. (ক্লাসের এলিমেন্টকে এ্যারের মতো ব্যবহার করতে দেয়)।
82. What is Thread Pooling in C#?
Thread pooling involves reusing a group of threads to execute multiple tasks efficiently.
83. What information can you provide regarding the XSD file in C#?
XSD (XML Schema Definition) defines the structure of XML data.
84. What are I/O classes in C#?
I/O classes in C# are used for file operations like creation, deletion, reading, and writing.
85. What exactly do you mean by regular expressions in C#?
Regular expressions are patterns used for matching strings, offering powerful text processing capabilities.
86. Why we use Exception
in a catch block in C# instead of ex
?
In C#, using catch (Exception)
without ex
(the variable) is when you don’t need details about the exception but still want to handle it (e.g., cleanup). If you rethrow with throw;
(not throw ex;
), it preserves the original exception’s stack trace. Omitting ex
avoids accidentally modifying or resetting the stack trace (which happens if you use throw ex;
). Use catch (Exception ex)
only if you need to log or inspect the exception before rethrowing.
Catch(Exception) { throw; }
.
More Quesion on this link: https://www.simplilearn.com/c-sharp-oops-interview-questions-answers-article
1. Define Encapsulation?
Encapsulation is the process of binding/combining the data members and member functions into a single unit.
2. How do you define Abstraction?
Abstraction hides implementation details and highlights essential features.
3. State the meaning of Inheritance.
Inheritance is the process of deriving a new class from an existing one.
4. What do you understand by Polymorphism?
Polymorphism is when a message can be processed in different ways.
5. What are the two types of Polymorphism?
Two types are Compile-time Polymorphism (Overloading) and Runtime Polymorphism (Overriding).
6. Define method Overloading.
Method overloading is curating several methods with the same name but different parameters and types.
7. When and why should one use the method of Overloading?
Use method overloading when a class needs to perform tasks with multiple possibilities for input.
8. Define Constructor.
A constructor is a unique method of a class automatically invoked when an instance is created, used to initialize class fields.
9. Define the use of Private Constructor in C#.
Private constructor pauses object creation, commonly used in Singleton classes and to prevent inheritance.
10. How do you define Destructor?
Destructor frees dynamically allocated memory and releases resources upon object destruction.
11. Define Namespaces.
Namespaces organize code into a system, preventing naming conflicts.
12. Define Virtual?
Virtual modifies a method/property/indexer/event in a base class, allowing it to be overridden.
13. Define Override in C#?
Override extends a virtual member of a base class into a derived class.
14. State the meaning of Interface.
An interface is similar to a class but without implementation, containing declarations of events/indexers/properties.
15. Why should one use Interface?
Interfaces are used for extensibility, implementation hiding, accessing objects, and loose coupling.
16. Define Implicit Interface Implementation.
The most common way to implement interface members without specifying the interface name.
17. Define the meaning of Explicit Interface Implementation.
Another way to implement interface members where the interface name isn’t specified, used to avoid member access through class instances.
18. What do you mean by Encapsulation?
Encapsulation wraps/hides properties and methods, used to hide code and data within a class.
- What do you understand by the term Abstraction? Abstraction presents only necessary details to the intended user.
20. When can one use Abstract Class?
Abstract classes provide default implementation of methods while allowing others to be overridden, ideal for base classes.
21. What is the type of members one can define in an Abstract Class?
Static and non-static members including properties, fields, indexers, and abstract classes.
22. Can we restrict object creation in C#?
Yes, using abstract classes, static classes, or private/protected constructors.
23. Is it possible to inherit Enum in C#?
No, enums are sealed by default and cannot be inherited.
24. Define Constant?
Constants are immutable values visible at compile time, defined using the “const” keyword.
- State the types of Design Patterns.
· Three types: Creational (Object creation),
· Structural (Class/Object composition)
· Behavioral (Class/Object communication).
26. Is it possible to serialize Hashtable?
No, Hashtable cannot be serialized due to .Net Framework restrictions.
27. How can one catch multiple exceptions at once in C#?
Using a condition statement to catch multiple exceptions.
28. Define Accessors.
Accessors are the get and set portions of a property.
29. Define Property in C#.net.
Properties provide a flexible mechanism to read, write, or process private field values.
30. Define Base keywords.
Base keyword accesses members of the base class from a derived class.
31. Struct vs class
Category | Struct | Class |
Type | It is value type | It is reference type |
Inherits from | It inherits from System.Value type | It inherits from System.Object type |
Used for | Usually used for smaller amounts of data | Usually used for large amounts of data |
Inherited to | It can not be inherited to other type | It can be inherited to other class |
Abstract | It can not be abstract | It can be abstract type |
New keyword | No need to create object by new keyword | Can not use an object of a class with using new keyword |
Default constructor | Do not have permission to create any default constructor | You can create a default constructor |
32. IList vs List
IList
and List
are both interfaces and classes in C# that are used for collections, but they serve different purposes:
IList
Interface:
- IList
stands for “Indexed List” and is part of the System.Collections
namespace.
- It represents a non-generic collection of objects that can be individually accessed by index.
- It defines methods to add, remove, and retrieve elements at specified positions in the list.
- IList
is implemented by several classes in .NET, including ArrayList
, CollectionBase
, etc.
- It is the base interface for arrays and lists in .NET.
List
Class:
- List
is a generic collection class in C# and is part of the System.Collections.Generic
namespace.
- It is an implementation of the IList<T>
generic interface.
- List
provides a strongly-typed collection of objects, meaning you can specify the type of elements it can hold when you instantiate it.
- It offers similar functionality to IList
but with type safety, improved performance, and syntax enhancements due to being strongly-typed.
- List
provides methods like Add
, Remove
, Contains
, IndexOf
, etc., for manipulating the collection.
Here’s a summary of the differences:
-
IList
is an interface, whileList
is a concrete class. -
IList
is not type-safe (it predates generics), whileList
is strongly-typed due to being a generic class. -
List
provides more functionality out of the box and is preferred for most scenarios where a generic list is needed. -
IList
is more generic and can be useful when dealing with different implementations of lists or when needing to accept various types of lists as method parameters.
In general, if you’re working with a specific type of list and type safety is important, it’s preferable to use List<T>
. However, if you’re designing a method or class that needs to accept various types of lists, IList
might be more appropriate.
33. Strongly-typed vs not type-safe
Apologies for any confusion. Let me clarify the terms “strongly-typed” and “not type-safe”:
- Strongly-Typed:
- In a strongly-typed language like C#, every variable and expression has a type known at compile time.
- Strong typing helps catch errors at compile time, reducing the likelihood of runtime errors.
- For example, when you declare a variable of type int
, you can only assign integer values to it. This type safety prevents you from assigning incompatible types, like a string, to that variable.
- List<T>
is strongly-typed because it allows you to specify the type of elements it holds (T
). This means the compiler can enforce type safety, ensuring that you only add, remove, or manipulate elements of the specified type.
- Not Type-Safe:
- When we say something is not type-safe, it means the language or construct doesn’t ensure type correctness at compile time.
- IList
, being a non-generic interface, is not type-safe because it operates on object
references rather than specific types.
- For example, when you use IList
, you can add any object to the list without any compile-time checks on the type. This can lead to runtime errors if you attempt to retrieve an item and cast it to an incompatible type.
- Due to its lack of type safety, using IList
might result in more runtime errors compared to List<T>
, where type safety is enforced by the compiler.
So, to summarize, “strongly-typed” means that types are enforced at compile time, reducing errors, while “not type-safe” implies that types are not enforced, potentially leading to runtime errors.
34. Overloading is a type of Compile time polymorphism and Overriding is a type of run time polymorphism
35. An enum is a special "class" that represents a group of constants.
36. Boxing is the process of converting from value type to reference type.
37. Unboxing is the process of converting reference type to value type. Unboxing is explicit conversion process.
38. What’s the difference between SDK and Runtime in .NET Core? Click to see answers in stackoverflow