0% found this document useful (0 votes)
7 views

C#

Uploaded by

Navya Shree
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

C#

Uploaded by

Navya Shree
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1. What is Object-Oriented Programming (OOP)?

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.

6. What is Polymorphism, and how is it achieved in C#?


Polymorphism in C# allows objects of different classes to be treated as objects of a common base class. It is
achieved through method overriding and interfaces. For example, multiple classes implementing the same
interface can be treated interchangeably.
7. What is the difference between a class and an object in C#?
A class is a blueprint or template for creating objects. It defines the structure and behavior of objects.
An object is an instance of a class, created based on the class's blueprint. It holds specific data values and can
invoke methods defined in the class.
8. How is a constructor different from a method in C#?
A constructor is a special method used to initialize objects when they are created. It has the same name as the
class and doesn't have a return type.
A method is a regular function within a class that performs a specific action and can have various return types.
9. Explain the purpose of the "this" keyword in C#.
The "this" keyword in C# refers to the current instance of a class. It is often used to disambiguate between
class members (fields or methods) and parameters or local variables with the same name. It allows you to
access instance variables within a class.
10. What is method overloading and method overriding in C#?
Method overloading involves defining multiple methods in the same class with the same name but different
parameter lists. It enables a single method name to perform different actions based on the provided arguments.
Method overriding occurs when a derived class provides a specific implementation for a method defined in
the base class. It allows the subclass to customize or extend the behavior of inherited methods.
11. Describe the "base" keyword in C# and its usage.
The "base" keyword in C# is used to refer to the base class (parent class) from within a derived class. It is
often used to call the constructor or methods of the base class when overriding them in the derived class. For
example, base.MethodName() calls the base class's method.

12. What are abstract classes and methods in C#?


- An abstract class in C# is a class that cannot be instantiated directly and serves as a blueprint for other
classes. It may contain abstract methods, which are declared without implementation details and must be
implemented in derived classes. Abstract classes are defined using the abstract keyword.
13. Explain the differences between an interface and an abstract class.
- An interface defines a contract for classes, specifying a set of methods that implementing classes must
provide. It supports multiple inheritance (a class can implement multiple interfaces). - An abstract class is a
class with one or more abstract methods and can also contain concrete methods. It cannot be instantiated
directly but can serve as a base class for other classes. - Classes can implement multiple interfaces but can
inherit from only one class (including abstract classes).
14. What is the difference between value types and reference types in C#?
- Value types store their data directly, and each variable holds a unique copy of the data. Examples include
integers, floats, and structs. - Reference types store references (memory addresses) to their data, allowing
multiple variables to point to the same data. Examples include classes, strings, and arrays.
15. How does C# support multiple inheritance using interfaces?
- C# supports multiple inheritance through interfaces, as a class can implement multiple interfaces. This
allows a class to inherit the contract (methods) defined by multiple interfaces while avoiding the complexities
of multiple inheritance in the traditional sense.
16. What is the purpose of the "sealed" keyword in C#?
- The "sealed" keyword is used to restrict the inheritance of a class. When a class is marked as "sealed," it
cannot be used as a base class for other classes, preventing further derivation.
17. What is a delegate in C#? How is it different from an interface? –
A delegate in C# is a type that represents a reference to a method with a specific signature. Delegates are used
for callback mechanisms and event handling. - Delegates are different from interfaces in that they define
method signatures directly and can hold references to multiple methods. Interfaces, on the other hand, define
a set of methods that implementing classes must provide but don't directly hold method implementations.

18. What is an event in C#? How is it used?


- An event in C# is a language feature used to provide notifications of changes or occurrences in a class. It is
declared using the event keyword and relies on delegates to manage subscribers (event handlers). Events are
commonly used in GUI applications and for event-driven programming.
19. Explain the concept of a static class in C#.
- A static class in C# is a class that cannot be instantiated, and all its members (methods, properties, fields)
must be static. Static classes are often used to define utility functions or to group related methods that don't
require instance-specific data.
20. What is the IDisposable interface, and why is it important?
- The IDisposable interface is used for resource management in C# and defines the Dispose method. It's
essential for releasing unmanaged resources such as files, database connections, or memory when they are no
longer needed. Implementing IDisposable helps ensure proper cleanup and avoids resource leaks.
21. Describe the advantages of using properties in C#
. - Properties provide a controlled way to access and modify the values of class fields (data). - They allow
encapsulation by hiding implementation details while exposing a consistent interface. - Properties enable
validation, computation, or side-effects when getting or setting values. - They can be used with data binding,
making them useful in GUI applications.
22. What is a namespace in C#, and why is it useful?
- A namespace is a container for organizing classes and other types in C#. It helps prevent naming conflicts
by allowing you to group related types under a common name. - Namespaces are essential for code
organization, maintainability, and collaboration in larger projects.
23. How does C# support exception handling? Explain the try-catch-finally block.
C# supports exception handling through the try-catch-finally block:
The try block contains the code where an exception might occur.
The catch block(s) catch and handle specific exceptions if they occur.
The finally block (optional) contains code that always executes, whether an exception occurs or not. It's often
used for cleanup tasks.

24. What is the purpose of the "using" statement in C#?


The using statement in C# is primarily used for resource management, especially when working with objects
that implement the IDisposable interface. It ensures that resources are properly disposed of when they go out
of scope, reducing the risk of resource leaks.
25. What is the difference between a struct and a class in C#?
- A struct is a value type, while a class is a reference type. - Structs are typically used for lightweight, small
data types, while classes are used for more complex objects. - Structs are copied by value, whereas classes are
copied by reference.
26. Explain the concept of access modifiers in C#.
- Access modifiers in C# control the visibility and accessibility of class members (fields, properties, methods,
etc.). Common access modifiers include: - public: The member is accessible from any code. - private: The
member is accessible only within the defining class. - protected: The member is accessible within the defining
class and its derived classes. - internal: The member is accessible within the same assembly. - protected
internal: The member is accessible within the same assembly and its derived classes.
27. What is the role of the "new" keyword in C#?
- The "new" keyword in C# is used for method hiding. When you have a base class method and a derived class
method with the same name, you can use "new" to indicate that the derived class method is intended to hide
the base class method.
28. What is the difference between shallow copy and deep copy in C#?
- A shallow copy duplicates an object's references, but not the objects themselves. In contrast, a deep copy
duplicates both the object and all the objects it references, recursively.
29. What is a static constructor in C#? When does it execute?
- A static constructor in C# is a special constructor used to initialize static members of a class. It executes
once, automatically, before any static members are accessed or any static methods are called, and only if they
are used.
30. How does C# handle method parameters (by value or by reference)?
- By default, C# uses "pass by value" for method parameters. This means a copy of the argument's value is
passed to the method. - To pass parameters by reference, you can use the ref or out keywords, which allow
the method to modify the original variable.
31. What is the purpose of the "readonly" keyword in C#?
- The "readonly" keyword in C# is used to declare a field that can only be assigned a value at the time of
declaration or within the constructor of the class. Once assigned, its value cannot be changed, making it useful
for constants and fields that should not change after initialization.
32. Explain the concept of garbage collection in C#.
- Garbage collection in C# is an automatic memory management process that reclaims memory occupied by
objects that are no longer reachable or in use by the program. The .NET runtime system handles garbage
collection, freeing developers from manual memory management and helping prevent memory leaks.
33. What is the difference between a List and an Array in C#? –
Lists are dynamic and resizable collections, while arrays have a fixed size. - Lists offer more flexibility and
functionality, such as dynamic resizing, adding/removing elements, and LINQ support. - Arrays have a fixed
size determined at declaration, making them less flexible.
34. How can you prevent a base class method from being overridden in C#?
- To prevent a base class method from being overridden in C#, you can use the "sealed" keyword in the
method's declaration in the base class. A sealed method cannot be overridden by derived classes.
35. What is the "as" operator in C# used for? –
The "as" operator in C# is used for safe type casting. It attempts to cast an object to a specified type and
returns null if the cast fails, rather than throwing an exception like the regular cast operator.
36. What is a property accessor in C#? –
A property accessor in C# is a method that gets (accessor) or sets (mutator) the value of a property. Accessors
are used to control how the property's value is retrieved or modified.
37. What is the difference between a private set and a public set for a property in C#?
- A property with a private set can only be modified within the defining class. External code cannot directly
change its value. - A property with a public set can be modified from external code, allowing external code to
change its value.

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.

58. How can you implement thread synchronization in C#? –


Thread synchronization in C# can be achieved using techniques such as locks (using the lock keyword),
mutexes, semaphores, and monitors. These techniques help prevent multiple threads from accessing shared
resources simultaneously and ensure thread safety.
59. Explain the concept of LINQ (Language Integrated Query) in C#.
- LINQ (Language Integrated Query) is a set of language features in C# that allows developers to query and
manipulate data using a SQL-like syntax directly within their C# code. LINQ provides a uniform way to work
with various data sources, including collections, databases, and XML.
60. What is the use of the "volatile" keyword in C#?
- The "volatile" keyword in C# is used to indicate that a field may be modified by multiple threads
simultaneously. It prevents the compiler and the CPU from optimizing or caching access to the field, ensuring
that reads and writes are always done from memory.
61. What is the purpose of the "checked" and "unchecked" keywords in C#?

- 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.

70. Explain the principles of Test-Driven Development (TDD) in C#.


- Test-Driven Development (TDD) is a software development methodology that follows these principles: 1.
Write a failing test: Before writing production code, write a test that specifies the desired behavior or
functionality. 2. Write the minimum code: Write the minimum amount of code necessary to make the test
pass. 3. Refactor: Once the test passes, refactor the code to improve its design while ensuring it still passes the
test. - TDD encourages writing tests first to drive the development process and achieve high code quality and
reliability.
71. What is the difference between synchronous and asynchronous streams in C# 8.0 and later versions?
- In C# 8.0 and later versions, synchronous streams return an IEnumerable<T> that produces data
synchronously as it's requested. Synchronous streams are suitable for working with in-memory collections. -
Asynchronous streams, introduced in C# 8.0, return an IAsyncEnumerable<T> and allow for asynchronous
enumeration of data, making them suitable for working with asynchronous I/O or data sources.
72. How can you implement a custom iterator in C# using the yield return statement? - To implement a
custom iterator in C#, you define a method that returns an IEnumerable<T> and uses the yield return
statement to yield values one at a time. Each time the method encounters yield return, it suspends execution
and returns the value to the caller. - Example: csharp public IEnumerable<int> GetNumbers() { yield
return 1; yield return 2; yield return 3; }
73. What is the role of the "nameof" operator in C# 6.0 and later versions? –
The "nameof" operator in C# 6.0 and later versions returns the name of a variable, type, or member as a string.
It helps improve code maintainability by referencing names through the nameof operator, reducing the risk of
naming errors and making refactoring safer.
74. Explain the concept of pattern matching in C# and provide examples.
- Pattern matching in C# allows you to check if an object matches a specific pattern or structure. It's often used
with the "is" and "switch" expressions. - Example 1 (is expression): csharp if (myObject is int intValue) {
// intValue is assigned if myObject is an integer } - Example 2 (switch expression): csharp switch
(myObject) { case int intValue: // Handle intValue if myObject is an integer break; case string
stringValue: // Handle stringValue if myObject is a string break; default: // Handle other cases break;
}

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.

You might also like