C#
C#
Object-Oriented Programming (OOP) is a programming paradigm that focuses on designing and organizing
code around the concept of objects. Objects are instances of classes and encapsulate both data (attributes) and
behaviour (methods) related to a specific entity or concept.
2. What are the four fundamental principles of OOP? (Encapsulation, Inheritance, Abstraction, and
Polymorphism)
Encapsulation: It involves bundling data and methods that operate on that data into a single unit (class). Access
to data is controlled, enhancing data security and integrity.
Inheritance: It allows a class (child or derived class) to inherit properties and behaviors from another class
(parent or base class), promoting code reuse.
Abstraction: It involves hiding complex implementation details while exposing essential features, making it
easier to work with high-level concepts.
Polymorphism: It enables objects of different classes to be treated as objects of a common base class,
facilitating dynamic method invocation and code flexibility.
3. Explain the concept of Encapsulation in C#.
Encapsulation in C# is the practice of bundling data (attributes) and methods (functions) that operate on that
data into a single unit called a class. It helps control access to data by using access modifiers like public,
private, protected, etc., ensuring data integrity and security. Data is typically made private and accessed
through properties or methods.
4. What is Inheritance in C#? How is it implemented?
Inheritance in C# allows a class (derived or child class) to inherit properties and methods from another class
(base or parent class). It promotes code reuse and is implemented using the colon (:) symbol followed by the
base class name in the class definition. Example: class ChildClass : ParentClass.
5. Describe Abstraction in C# and provide an example.
Abstraction in C# involves defining abstract classes and methods that provide a blueprint for derived classes
to implement. An example is an abstract class Shape with an abstract method CalculateArea(). Subclasses
like Circle and Rectangle implement this method differently.
38. Explain the difference between synchronous and asynchronous programming in C#. - Synchronous
programming executes code sequentially, blocking until a task is complete before moving on to the next one.
- Asynchronous programming allows tasks to run concurrently, enabling non-blocking execution. It uses
keywords like "async" and "await" to manage asynchronous operations.
39. What is the purpose of the "async" and "await" keywords in C#? –
The "async" keyword in C# is used to define methods that can be awaited asynchronously. The "await"
keyword is used within an async method to indicate points where the method can yield control back to the
caller while waiting for an asynchronous operation to complete.
40. How can you implement Singleton pattern in C#?
- The Singleton pattern in C# ensures that a class has only one instance and provides a global point of access
to it. You can implement it by: - Making the class constructor private. - Providing a static method to access
the single instance. - Creating the instance on first access and returning it for subsequent calls.
41. What is Dependency Injection (DI) in C#? –
Dependency Injection (DI) is a design pattern in C# that involves supplying a dependent object (dependency)
to a class instead of allowing the class to create the dependency itself. DI promotes loose coupling between
classes, making code more maintainable and testable.
42. Explain the use of the "virtual" and "override" keywords in C#. –
The "virtual" keyword is used in a base class to indicate that a method can be overridden in derived classes.
- The "override" keyword is used in a derived class to specify that a method is intended to override a base
class method. It ensures that the method signature matches that of the base class.
43. What is a lambda expression in C#? How is it used?
- A lambda expression in C# is a concise way to define anonymous methods or delegates. It provides a compact
syntax for defining small, inline functions without the need for a separate method declaration.
44. What is the role of the "using" directive in C#?
- The "using" directive in C# is used to import namespaces, making types from those namespaces accessible
in the current code file. It simplifies code by allowing you to use types without fully qualifying their names.
45. What is a value tuple in C#? –
A value tuple in C# is a data structure that can hold multiple values of different types in a single object. It is
similar to a tuple in other programming languages and provides a way to return multiple values from a method.
46. Explain the concept of events and event handlers in C#? –
Events and event handlers in C# provide a mechanism for implementing the observer pattern. An event is a
notification that something has happened, and an event handler is a method that responds to that event. Classes
can subscribe to events and receive notifications when the event occurs.
47. How can you handle exceptions that occur during asynchronous programming in C#? - During
asynchronous programming in C#, exceptions can be handled using try-catch blocks around asynchronous
code, just like in synchronous code. Additionally, async methods can propagate exceptions using the throw
keyword or by using try-catch blocks in the calling code.
48. What is the purpose of the "yield" keyword in C#? –
The "yield" keyword in C# is used to define an iterator in a method. It allows you to return a sequence of
values one at a time, lazily, as they are requested, without creating and storing the entire sequence in memory.
49. How does C# support operator overloading?
- C# allows you to define custom behaviors for operators such as +, -, *, /, etc., by overloading them in your
classes. Operator overloading enables you to use these operators with user-defined types.
50. What is reflection in C#? –
Reflection in C# is a mechanism that allows you to inspect and interact with the metadata and types of
assemblies, modules, and objects at runtime. It provides the ability to examine and manipulate program
structures dynamically.
51. What is a delegate multicast in C#? –
A delegate multicast in C# refers to the ability of a delegate to hold references to multiple methods. When a
multicast delegate is invoked, it calls all the methods it holds in the order they were added to the delegate.
52. Explain the differences between value types and nullable types in C#? –
Value types store their data directly on the stack or inline within objects. They cannot be assigned a null value
by default. - Nullable types, represented using the Nullable<T> struct or by appending ? to value types, can
store either a value of the underlying type or a null value.
53. What is the role of the "nameof" operator in C#? –
The "nameof" operator in C# is used to obtain the name of a variable, type, or member as a string. It is often
used to improve code maintainability by referencing names through the nameof operator, reducing the risk of
naming errors.
54. What are extension methods in C#?
- Extension methods in C# allow you to add new methods to existing types (classes, structs, interfaces) without
modifying their source code. These methods are defined in static classes and can be called as if they were
instance methods of the extended type.
55. How do you implement a custom exception class in C#?
- To implement a custom exception class in C#, you create a new class that derives from the System.Exception
class or one of its derived classes. You can add custom properties and methods to your exception class to
provide additional information about the exception.
56. What is the difference between an abstract class and an interface in C#? When would you use one
over the other? –
An abstract class can contain both abstract and concrete methods and can have fields and constructors. It
cannot be instantiated directly and is used as a base class for other classes. - An interface contains method and
property declarations but no implementation. It defines a contract that implementing classes must adhere to
and supports multiple inheritance. - Use an abstract class when you want to provide a common base with some
default behavior, and use an interface when you want to define a contract for unrelated classes or support
multiple inheritance.
57. What is the difference between the "ref" and "out" keywords in C#?
- Both "ref" and "out" parameters allow methods to modify the values of variables in the calling code. - The
"ref" keyword indicates that the variable must be initialized before being passed to the method. - The "out"
keyword indicates that the variable does not need to be initialized before being passed to the method, and the
method is expected to assign a value to it.
- The "checked" and "unchecked" keywords in C# are used to control the behavior of integer arithmetic
overflow. "checked" enables overflow checking, causing an exception to be thrown when an overflow occurs.
"unchecked" disables overflow checking, allowing overflows to wrap around without exceptions.
62. How does C# support Asynchronous Programming Models (APM) and Event-based Asynchronous
Pattern (EAP)?
- C# supports APM through methods ending with "Begin" and "End," allowing asynchronous operations to
be started and completed. EAP is a pattern where asynchronous operations raise events when completed, and
it uses event handlers to handle the results.
63. What is the Task Parallel Library (TPL) in C#? –
The Task Parallel Library (TPL) is a set of APIs in C# that simplifies parallel and concurrent programming.
It provides abstractions like tasks and parallel loops to help developers write multithreaded code more easily
and efficiently.
64. What is dependency property in WPF (Windows Presentation Foundation), and how does it differ
from regular properties?
- Dependency properties in WPF are a specific type of property used to enable features like data binding,
styles, templates, and animation. They differ from regular properties in that they have built-in change
notification and value inheritance capabilities, making them more suitable for complex user interface elements
in WPF applications.
65. Explain the concept of Dependency Injection containers in C#.
- Dependency Injection containers in C# are frameworks or libraries that automate the process of resolving
and injecting dependencies into classes. They maintain a container of registered types and their dependencies,
allowing developers to request fully constructed objects with their dependencies automatically injected.
66. What are attributes in C#? How are they used, and can you create custom attributes? - Attributes in
C# are metadata annotations that can be added to elements like classes, methods, properties, and parameters
to provide additional information about those elements. .NET Framework and libraries use attributes
extensively, and you can create custom attributes to add metadata to your code.
67. What is a Finalizer in C#? –
A Finalizer in C# is a special method provided by the .NET runtime for a class. It is used for cleanup
operations on unmanaged resources when an object is being garbage-collected. Finalizers are defined using
the destructor syntax (~ClassName()).
68. How can you implement custom serialization and deserialization in C#? –
To implement custom serialization and deserialization in C#, you can use the ISerializable interface to
control the process. You define the serialization and deserialization logic by implementing the
GetObjectData and constructor (for deserialization) methods.
69. What is the purpose of the "using" statement in C# when dealing with IDisposable objects? –
The "using" statement in C# ensures that objects that implement the IDisposable interface are properly
disposed of when they go out of scope. It automatically calls the Dispose method on the object, releasing
resources and preventing resource leaks.
75. What is the C# Memory Model, and how does it affect multithreaded programming? –
The C# Memory Model defines the rules and guarantees for how memory is accessed and modified by threads
in a multithreaded program. It ensures that programs behave predictably in a multithreaded environment. -
The memory model affects multithreaded programming by defining how reads and writes to memory locations
are ordered and how shared data is accessed and synchronized between threads. Understanding the memory
model is crucial for writing correct and reliable multithreaded code.