
35+ Best [ C# ] Interview Questions & Answer [FREQUENTLY ASK]
Last updated on 04th Jul 2020, Blog, Interview Questions
These C# Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of C# . As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer.we are going to cover top 100 C# Interview questions along with their detailed answers. We will be covering C# scenario based interview questions, Questions for interview to both freshers as well as experienced.
1)What does C# mean?
Ans:
Microsoft’s C# is an object-oriented, high-level programming language. C# was designed to be a higher-level programming language compared to C and C++, providing modern features and a simplified syntax while retaining the power and flexibility of those languages.
2)What are the features of C#?
Ans:
- Automatic memory management (garbage collection)
- Language interoperability with other .NET languages
- Exception handling for robust error management
- Extensive standard library and framework support
- Support for generics and collections
3)How do C# and.NET vary from one another?
Ans:
- Microsoft’s C# is an interpreted programming language.
- It is a high-level, object-oriented language that is part of the .NET ecosystem.
- C# is used to write applications for a variety of platforms, including Windows, web, mobile, and gaming.
- It offers a variety of features, including strong typing, garbage collection, and extensive library support.
- Microsoft’s foundation for creating software is known as.NET.
- It provides a comprehensive set of libraries, tools, and runtime environments for building different types of applications.
- .NET includes multiple programming languages, and C# is one of the primary languages used with .NET.
- The .NET framework offers various components like the Common Language Runtime (CLR), Base Class Library (BCL), and ASP.NET for web development.
C-sharp:
.NET:
4)Describe how value types and reference types vary in C#
Ans:
Value types in C# store their data directly within the variable itself, while reference types store a reference (memory address) to the data’s location. Value types are simple types and are allocated on the stack, while reference types include classes, interfaces, arrays, and strings, and are allocated on the heap.
5)What is inheritance in C#?
Ans:
Inheritance in C# is a fundamental object-oriented programming feature that allows a class to inherit attributes, methods, and behavior from another class. A class that derives from another class is referred to as a subclass or derived class, whilst the class it derives from is referred to as the base class or superclass.
6)What is the difference between a class and an object in C#?
Ans:
- A class is a model or template that specifies the composition and operation of objects.
- It acts as a blueprint for creating objects of that class type.
- It defines the properties, methods, and events that the objects of that class will possess.
- It provides the structure for creating multiple objects with similar characteristics.
- Instances of classes are objects.
- It is created based on the blueprint defined by the class.
- It represents a specific entity or instance in memory that has its own state and behavior.
- Objects can be created and manipulated at runtime, and they communicate with one another by calling class-defined methods or making use of class-defined attributes.
Class:
Object:
7) What is the purpose of the C# “using” statement?
Ans:
The phrase “using” statement in C# is used for two purposes: managing resources by automatically disposing them, and importing namespaces to access types and members without fully qualifying them.
8)Describe the distinctions between method overloading and overriding in C-sharp.
Ans:
Method Overriding:
Method overriding allows a derived class to provide a different implementation of a method with the same name and signature as the method in the base class. It enables runtime polymorphism.
Method Overloading:
With method overloading, a class can have numerous methods that share the same name but take a distinct set of arguments. The methods are differentiated based on the number or types of parameters. Method overloading is resolved at compile-time.
9) What are the access modifiers in C#?
Ans:
- public: Accessible from anywhere.
- private: Accessible only within the same type.
- protected: Accessible within the same type and derived types.
- internal: Accessible within the same assembly.
- protected internal: Accessible within the same assembly and derived types.
- private protected: Accessible within the same assembly and derived types in the same assembly.
10) What is a constructor in C#?
Ans:
A constructor in C# is a special method used to initialize objects. It has the same name as the class and is automatically called when an instance of the class is created. Constructors are responsible for initializing the object’s state and can be overloaded to provide different ways of creating objects.
11) Explain the difference between a static class and a non-static class in C#.
Ans:
A static class in C# cannot be instantiated and is used for providing utility functions or methods. All members of a static class must also be static, and they are shared across all instances of the program. On the other hand, a non-static class can be instantiated to create objects and can have both static and instance members.
12)What is the purpose of the “this” keyword in C#?
Ans:
- The “this” keyword in C# serves multiple purposes to enhance object-oriented programming.
- Firstly, it allows access to instance members within a class, resolving any naming conflicts between local variables or parameters and instance variables. This ensures that the intended member is accessed or modified accurately.
- The “this” keyword is utilized for constructor chaining, enabling one constructor to call another within the same class. This facilitates code reuse and initialization of objects by delegating construction tasks to other constructors.
13) What is a delegate in C#?
Ans:
A delegate in C# is a powerful feature that allows methods to be treated as first-class objects. It acts as a function pointer, representing an identifier of a method with a certain signature. Delegates enable flexible and dynamic invocation of methods, making them particularly useful for event handling scenarios.
14) Explain the concept of events in C#.
Ans:
- Events in C# are a mechanism that enables objects to communicate with each other using the publish-subscribe pattern.
- A class declares an event using the “event” keyword, specifying the delegate type for event handlers.
- Objects can subscribe to the event by attaching event handlers, which are methods that match the delegate’s signature.
- When the event occurs, all subscribed event handlers are invoked. Events promote loose coupling and are commonly used for user interfaces, asynchronous operations, and inter-component communication.
15) What is the difference between a class and an interface in C#?
Ans:
- In C#, a class is a blueprint for creating objects, defining their structure, behavior, and state. It can have its own data storage, support inheritance, and contain method implementations.
- In contrast, an interface is a contract that specifies the behaviors (methods, attributes, and events) that a class must provide. It doesn’t have its own data storage and only contains method signatures and property declarations.
- A class may be instantiated, but classes implement interfaces to offer specialized behavior.
16) What is a namespace in C#?
Ans:
In C#, a namespace is used to organize and group related types together, providing a way to avoid naming conflicts and create a hierarchical structure for code organization. It defines type scope and permits access without explicit qualifying inside the same namespace.
17) How do you handle exceptions in C#?
Ans:
- Exceptions are managed using try-catch statements in C#.
- The code that may throw an exception is placed in the try block, and if an exception occurs, it is caught and handled in the catch block.
- Finally, a finally block can be used to execute code that should always run, regardless of whether an exception was thrown or caught.
- Exceptions may also be declared explicitly with the throw keyword. Exception handling allows for controlled error handling and recovery in C# programs.
18) What is a generic class in C#?
Ans:
A generic class in C# is a class that is parameterized by one or more type parameters. It allows for the creation of reusable classes that can work with different data types while maintaining type safety. Generic classes provide flexibility, code reusability, and improved performance compared to non-generic alternatives.
19) What is the purpose of the “as” keyword in C#?
Ans:
- The “as” keyword in C# is used for safe type casting or conversion. Its purpose is to attempt a cast from one type to another, and if the cast is not possible, it returns null instead of throwing an exception.
- When working with reference types or nullable value types, the “as” keyword is often used. The “as” keyword is primarily used with reference types and nullable value types.
20) Explain the concept of LINQ in C#.
Ans:
LINQ (Language Integrated Query) in C# is a robust feature that provides a unified and intuitive method for querying and manipulating data from various sources. It allows programmers to use a declarative query writing syntax, which streamlines data querying and modification.
Key concepts of LINQ in C#:
- Query Expressions
- Standard Query Operators
- Data Sources
- Code Readability
21) What are the different types of collections in C#?
Ans:
List: A dynamic-sized collection that allows adding, removing, and accessing elements by index.
Array: A fixed-sized collection that stores elements of the same type in contiguous memory.
Dictionary: Stores key-value pairs, enabling fast retrieval of values based on their associated keys.
Queue: Represents a first-in, first-out (FIFO) collection, where elements are inserted at the end and removed from the front.
Stack: Represents a last-in, first-out (LIFO) collection, where elements are inserted and removed from the top.
HashSet: Holds a random assortment of items without regard to any arrangement.
22) What is the difference between a struct and a class in C#?
Ans:
In C#, structs are value types stored on the stack, typically used for small, lightweight objects. They do not support inheritance and are copied when assigned or passed to methods. Classes, on the other hand, are reference types stored on the heap, used for more complex objects with behavior and support for inheritance. Class instances are passed by reference, allowing modifications to affect the original object.
23) How do you achieve multiple inheritance in C#?
Ans:
In C#, a class can achieve multiple inheritance of interfaces, but not multiple inheritance of classes.
Multiple Inheritance of Interfaces:
- C# allows a class to implement multiple interfaces, which effectively achieves a form of multiple inheritance.
- By implementing multiple interfaces, a class can inherit and provide implementations for the members defined in each interface.
- This allows the class to exhibit behavior from multiple sources and fulfill different contracts.
24)What is the difference between an abstract class and an interface in C#?
Ans:
In C#, an abstract class can have defined and undefined members, supports inheritance, and allows code reuse. It can also have constructors and fields. On the other hand, an interface only defines undefined members that implementing classes must provide. It does not support inheritance and cannot have constructors or fields. Only one abstract class may be inherited by a class but can implement multiple interfaces.
25)What are extension methods in C#?
Ans:
Extension methods in C# permit the addition of new methods to existing types without modifying the source code of the original type. They provide a way to extend the functionality of classes, structs, or interfaces.
26) What is the difference between a static method and an instance method in C#?
Ans:
Static Methods:
Static methods are associated with the type itself rather than a specific instance of the type. They are declared using the “static” keyword. Since they are not linked to a particular instance, they can be invoked directly on the type without instantiating an instance of the class. Static methods can only access other static members of the same type; they cannot access instance-specific data or alter the state of individual objects.
Instance Methods:
Instance methods are tied to a specific instance of a class or struct. They are called on an instance of the type using the dot notation. Instance methods may access and alter the state of the object they are invoked on in addition to the type’s static members.
27) Explain the concept of thread safety in C#.
Ans:
Thread safety in C# refers to the ability of code or a program to function correctly and produce the expected results when executed concurrently by multiple threads. It involves designing and implementing code in a way that prevents race conditions and ensures the integrity and consistency of shared resources.
Common thread safety mechanisms in C# include:
- Locking
- Synchronization primitives
- Atomic operations
- Thread-safe collections
- Immutable objects
- The “==” operator is a binary operator used for comparing two operands for equality.
- For value types, the “==” operator compares the values of the operands. It returns true if the values are equal and false otherwise.
- For reference types, the “==” operator compares the references of the objects, not their actual values. It returns true if the references point to the same object in memory and false if they point to different objects, even if the objects have identical values.
- The behavior of the “==” operator can be overridden by defining the “==” operator in custom types.
- The “Equals()” method is a method defined in the System. Object class and can be overridden in derived classes to provide custom equality comparison.
- The “Equals()” method compares the values of objects, not the references.
- C#’s automatic memory management feature is garbage collection. It releases memory occupied by no longer-used objects.
- Garbage collection helps prevent memory leaks and dangling references.
- It uses a mark and sweep algorithm to identify and clean up unreferenced objects.
- The process involves marking objects that are still referenced and sweeping through memory to reclaim memory occupied by unreferenced objects.
- Garbage collection is performed by the runtime environment, periodically or when certain conditions are met.
- It relieves developers from manual memory management tasks, making the programming process safer and more convenient.
- Nullable types hold either a value or null.
- “??”: null-coalescing operator assigns a default value if null.
- “?.”: null-conditional operator for safe member access.
- Use “HasValue” to check if a nullable type has a value.
- Use “Value” to retrieve the value, but check “HasValue” first to avoid exceptions.
- Nullable reference types (from C# 8.0) enforce non-nullability at compile-time.
- Handle nullable types to represent missing values and avoid null reference exceptions.
- try
- {
- // Code that cause an error
- }
- catch (ExceptionType1 ex1)
- {
- // Exception handling for ExceptionType1
- }
- catch (ExceptionType2 ex2)
- {
- // Exception handling for ExceptionType2
- }
- finally
- {
- // Code that will always execute, irrespective of whether an exception has been raised or caught
- }
- The code that you think could cause an exception is in the “try” block.
- Within the “try” block, if an exception arises, the corresponding “catch” block with a matching exception type is executed.
- You can have multiple “catch” blocks to handle different types of exceptions. The catch blocks should be sorted by increasing levels of specificity.
- No matter if an exception is thrown or captured, the code inside the “finally” block will always run. It is generally used for clearing out clutter or freeing up assets.
- The “finally” block is optional. If you omit it, the “try-catch” block can still handle exceptions, but no additional code will be executed after the catch block.
- A partial class allows the definition of a class to be split into multiple files using the “partial” keyword.
- The partial class files are combined into a single class by the compiler, treating them as a cohesive unit.
- All partial class files must have the same accessibility level and belong to the same namespace.
- Members (methods, properties, fields, etc.) declared in any of the partial class files are shared among all the files.
- Partial classes are useful for organizing large classes or dividing class implementation among multiple developers.
- They allow different developers to work on different parts of the same class without conflicting with each other.
- The “break” statement terminates the innermost loop or switch statement.
- The “continue” statement skips the remaining code within a loop’s current iteration and moves on to the following one.
- “break” is used to break out of a while loop or switch statement early.
- “continue” is used to bypass certain iterations or skip specific code execution within a loop.
- “break” passes control to the statement that comes after the loop or switch.
- “continue” transfers control to the next iteration of the loop.
- Anonymous methods allow you to define a delegate inline without explicitly declaring a named method.
- They are defined using the “delegate” keyword, followed by the parameter list and the method body enclosed in curly braces.
- Anonymous methods are commonly used in event handling and asynchronous programming, where a callback function needs to be defined on the fly.
- Lambda expressions provide a more concise syntax for creating delegate instances. They are essentially anonymous functions that can be used to represent delegate types.
- Lambda expressions are defined using the “=>” operator, which separates the parameter list from the expression or statement body.
- Lambda expressions are used in functional programming, LINQ queries, and asynchronous programming.
- The ICloneable interface provides a way to indicate that an object supports cloning.
- Define your own class and make it implement the ICloneable interface.
- Within the class that implements ICloneable, override the Clone() method to perform the deep copy.
- In the overridden method, create a new instance of the class and copy the properties and fields, ensuring that any nested objects are also cloned.
- Declare a private static variable of the class type within the class to hold the single instance.
- Make the class’s constructor private to prevent external instantiation of the class.
- Create a public static property or method that provides access to the single instance. This property or method should check if an instance already exists and create a new instance if it doesn’t. It should return the existing instance if it already exists.
- Ensure thread safety by implementing a locking mechanism, such as using the lock keyword or a thread-safe singleton implementation like double-checked locking or using the Lazy
class. - The term “async” is used to describe an asynchronous method or lambda expression.
- It indicates that the method contains asynchronous operations that can be awaited.
- It allows the method to use the “await” keyword and enables the method to be suspended and resumed during asynchronous operations.
- The “await” keyword is used to await the completion of an asynchronous operation inside an “async” method.
- It allows the program execution to be suspended until the awaited task or operation is complete.
- It returns the result of the awaited task or operation and resumes execution of the method.
- As a design pattern, Dependency Injection (DI) promotes loose coupling by injecting dependencies into a class from the outside.
- It improves testability by allowing dependencies to be easily mocked or replaced during testing.
- DI facilitates decoupling by relying on abstractions (interfaces or base classes) instead of concrete implementations.
- DI reduces the need for classes to create or manage their dependencies internally.
- Inversion of Control (IoC) containers can be used to handle the creation and management of object instances and their dependencies.
- DI enhances modularity, flexibility, and maintainability of the codebase.
- Visual Studio Express (VCE)
- Visual Studio (VS)
- Visual Web Developer
- Single Line Comment Eg : //
- Multiline Comments Eg: /* */
- XML Comments Eg : ///
- Below is the sample code of sealed class in C# –
- class X {}
- sealed class Y : X {}
- Sealed methods –
- class A
- {
- protected virtual void First() { }
- protected virtual void Second() { }
- }
- class B : A
- {
- sealed protected override void First() {}
- protected override void Second() { }
- }
- Eg: const string _name = “Test”;
- “Const” keyword is used for making an entity constant. We cannot modify the value later in the code. Value assigning is mandatory to constant variables.
- “readonly” variable value can be changed during runtime and value to readonly variables can be assigned in the constructor or at the time of declaration.
- Dispose – This method uses interface – “IDisposable” interface and it will free up both managed and unmanaged codes like – database connection, files etc.
- Finalize – This method is called internally unlike Dispose method which is called explicitly. It is called by garbage collector and can’t be called from the code.
- Finalize – This method is used for garbage collection. So before destroying an object this method is called as part of clean up activity.
- Finally – This method is used for executing the code irrespective of exception occurred or not.
- “throw ex” will replace the stack trace of the exception with stack trace info of re throw point.
- “throw” will preserve the original stack trace info.
- Below are the types of errors in C# –
- Compile Time Error
- Run Time Error
- Static classes/methods/variables are accessible throughout the application without creating instance. Compiler will store the method address as an entry point.
- Public methods or variables are accessible throughout the application.
- Void is used for the methods to indicate it will not return any value.
- decimal
- int
- byte
- enum
- double
- long
- float
- class
- string
- interface
- object
- StringBuilder TestBuilder = new StringBuilder(“Hello”);
- TestBuilder.Remove(2, 3); // result – “He”
- TestBuilder.Insert(2, “lp”); // result – “Help”
- TestBuilder.Replace(‘l’, ‘a’); // result – “Heap”
- StringBuilder is mutable, which means once object for stringbuilder is created, it later be modified either using Append, Remove or Replace.
- String is immutable and it means we cannot modify the string object and will always create new object in memory of string type.
- “CopyTo()” method can be used to copy the elements of one array to other.
- “Clone()” method is used to create a new array to contain all the elements which are in the original array.
- NullReferenceException
- ArgumentNullException
- DivideByZeroException
- IndexOutOfRangeException
- InvalidOperationException
- StackOverflowException etc.
- Generics in c# is used to make the code reusable and which intern decreases the code redundancy and increases the performance and type safety.
- Namespace – “System.Collections.Generic” is available in C# and this should be used over “System.Collections” types.
- Callback Mechanism
- Asynchronous Processing
- Abstract and Encapsulate method
- Multicasting
- Eg: Int? mynullablevar = null;
- double? myFirstno = null;
- double mySecno;
- mySecno = myFirstno ?? 10.11;
- int x = 6;
- int y = 7;
- CalculateMyNumbers addMyNumbers = new
- CalculateMyNumbers(FuncForAddingNumbers);
- CalculateMyNumbers multiplyMyNumbers = new
- CalculateMyNumbers(FuncForMultiplyingNumbers);
- CalculateMyNumbers multiCast = (CalculateMyNumbers) Delegate.Combine (addMyNumbers, multiplyMyNumbers);
- multiCast.Invoke(a,b);
28) In C#, what is the distinction between “==” and “Equals()”?
Ans:
“==” Operator:
“Equals()” Method:
29)What is meant by the term “garbage collection” in C#.
Ans:
30) What is the purpose of the “volatile” keyword in C#?
Ans:
The “volatile” keyword in C# is used to indicate that a field may be modified by multiple threads, and its value should always be read from and written to the main memory rather than being cached in CPU registers or local caches. It ensures that the most up-to-date value of the field is always accessed, even in multi-threaded scenarios.
31) How do you handle nullable types in C#?
Ans:
In C#, nullable types allow you to represent variables that can hold either a valid value of a particular type or a null value. Here are the ways to handle nullable types in C#:
32)What is the purpose of the “var” keyword in C#?
Ans:
The “var” keyword in C# enables implicit type inference during variable declaration. It allows the compiler to determine the type based on the assigned value, enhancing code readability and reducing redundancy.
The use of “var” maintains compile-time type safety, doesn’t impact performance, and is limited to local variables and loop variables. Its purpose is to simplify code and streamline the declaration process.
33) How do you implement a try-catch-finally block in C#?
Ans:
To implement a try-catch-finally block in C#, you can use the following structure:
34) What is the purpose of the “using” directive in C#?
Ans:
Namespace Import:
It allows you to access types defined in other namespaces without specifying the full namespace path each time.
Resource Management:
It ensures proper cleanup of disposable objects by automatically calling their Dispose method when the “using” block is exited.
35)Describe the C# concept of a partial class.
Ans:
36) Explain the concept of polymorphism in C#
Ans:
The ability of objects to be polymorphic in C# is to exhibit different behaviors based on their underlying type. It allows a variable of a base class or interface type to refer to objects of different derived classes, and the appropriate method implementation is determined at runtime.
Polymorphism is achieved through inheritance and method overriding. When a derived class overrides a method from its base class, it provides its own implementation of that method. At runtime, the appropriate method is dynamically bound based on the actual type of the object, allowing for different behavior to be exhibited.
37) What are indexers in C#? How are they used?
Ans:
Indexers in C# are special members of a class that allow objects to be accessed using array-like syntax. They provide a way to define the behavior of accessing elements within a class or structure.
Definition:
A class or structure’s indexers are specified using the “this” keyword and a parameter list.
Accessing Elements:
Indexers, like arrays and collections, allow square bracket access and manipulation of items.
Multiple Indexers:
A class or structure can have multiple indexers, differentiated by their parameter types or numbers.
Getter and Setter Methods:
Similar to properties, indexers are defined with get and set accessors that allow retrieval and assignment of values associated with the supplied indices.
Indexer Overloading:
Like methods and properties, indexers can be overloaded, allowing different behavior based on the number or types of indices.
Usage Scenarios:
Indexers are frequently employed to facilitate access to and manipulation of encapsulated internal data structures or collections.38) What are the advantages of implementing generics in C#?
Ans:
Type safety:
Generics provide compile-time type checking, catching type-related errors early in development.
Performance optimization:
Generics avoid boxing/unboxing operations and unnecessary type conversions, leading to more efficient code execution.
Code clarity:
Generics make code more expressive and self-documenting by specifying expected type parameters.
Collection flexibility:
Generics enable the creation of strongly typed collections, eliminating the need for casting when accessing elements.
Algorithm reusability:
Generics facilitate the creation of generic algorithms that can operate on different data types, enhancing code maintainability.
39)What is the distinction between the break and continue statements in C#?
Ans:
40) What is the function of the C# keyword “volatile”?
Ans:
The “volatile” keyword in C# is used to indicate that a field or variable may be modified by multiple threads concurrently. It assures that the compiler and runtime do not optimize or retain the field’s value because it may be modified by other threads outside the normal execution flow.
41) Explain the concept of serialization and deserialization in C#
Ans:
Serialization is the process of converting an object’s state into a format that can be easily stored or transmitted. It involves transforming the object’s properties, fields, and related data into a serialized format, such as binary, XML, or JSON. The purpose of serialization is to persist the object’s state or transfer it across different systems or platforms.
Deserialization is the opposite procedure of serialization. It involves reconstructing an object from the serialized data. During deserialization, the serialized data is read and interpreted, and the object’s state, properties, and fields are restored to their original values.
42) What is the function of the C# “yield return” statement?
Ans:
To simplify the process of constructing and returning a series of values, iterator methods in C# make use of the “yield return” statement. Without implementing the complete iterator algorithm, you may construct a method that returns an enumerable sequence.
43) Describe the C# concepts of anonymous methods and lambda expressions
Ans:
Anonymous Methods:
Lambda Expressions:
44)How do you implement a deep copy of an object in C#?
Ans:
Here’s an approach to achieve a deep copy:
Implement the ICloneable Interface:
Override the Clone() Method:
45) How is the Singleton pattern implemented in C#?
Ans:
To implement the Singleton pattern in C#, you can follow the following steps:
46) What are the functions of the C# “async” and “await” keywords?
Ans:
async” Keyword:
“await” Keyword:
47) Explain dependency injection in C# and how it facilitates decoupling and testability.
Ans:
48) What are attributes in C#? How can they be used for metadata and declarative programming?
Ans:
Attributes in C# serve as declarative tags that provide additional metadata about types, methods, properties, and other program elements.
Metadata:
Attributes serve as metadata, providing additional information about types, members, or assemblies. They can describe characteristics such as authorship, versioning, security requirements, or data persistence.
Declarative Programming:
Attributes enable declarative programming by allowing you to specify behaviors or instructions without writing explicit code. By applying attributes, you define how the program should behave or be treated in specific contexts.
49) What is the function of the C# keyword “params”?
Ans:
The “params” keyword in C# allows you to designate a method parameter that accepts a range of parameters of the same type. It provides flexibility when working with methods that must receive a variable number of arguments without explicitly defining an array or multiple parameters.
50) What is the distinction between “const” and “readonly” in C#?
Ans:
The readonly keyword is used to declare a member (field or property) that can only be assigned a value at the time of declaration or within the constructor of the containing class. It can have different values for different instances of the class.
Constants are declared with the keyword const that is assigned a value at the time of declaration and cannot be changed thereafter. It has the same value for all instances of the class.
51)What distinguishes a shallow copy from a deep copy in C#?
Ans:
Shallow Copy:
Shallow copies produce a new item and copies the values of the fields from the original object to the new object.
Deep Copy:
A deep copy generates a new object and then continuously copies all the values of the fields, including the objects referenced by the original object’s fields.
52) What is the function of the C# “lock” keyword?
Ans:
The purpose of the “lock” keyword in C# is to ensure mutual exclusion or synchronization in multi-threaded environments. When multiple threads are accessing shared resources concurrently, the “lock” keyword allows only one thread at a time to execute the code block enclosed within the “lock” statement. This prevents race conditions where multiple threads might try to modify the shared resource simultaneously, leading to unpredictable and incorrect results.
53)What are IDE’s provided by Microsoft for C# development?
Ans:
Below are the IDE’s used for C# development –
54)Explain the types of comments in C#?
Ans:
Below are the types of comments in C# –
55)Explain sealed class in C#?
Ans:
Sealed class is used to prevent the class from being inherited from other classes. So “sealed” modifier also can be used with methods to avoid the methods to override in the child classes.
56)Give an example of using sealed class in C#?
Ans:
If any class inherits from class “B” then method – “First” will not be overridable as this method is sealed in class B.
57) List out the differences between Array and ArrayList in C#?
Ans:
Array stores the values or elements of same data type but arraylist stores values of different datatypes. Arrays will use the fixed length but arraylist does not uses fixed length like array.
58)Why to use “using” in C#?
Ans:
“Using” statement calls – “dispose” method internally, whenever any exception occurred in any method call and in “Using” statement objects are read only and cannot be reassignable or modifiable.
59)Explain namespaces in C#?
Ans:
Namespaces are containers for the classes. We will use namespaces for grouping the related classes in C#. “Using” keyword can be used for using the namespace in other namespace.
60) Why to use keyword “const” in C#? Give an example.
Ans:
“Const” keyword is used for making an entity constant. We can’t reassign the value to constant.
61) What is the difference between “constant” and “readonly” variables in C#?
Ans:
62) Explain “static” keyword in C#?
Ans:
“Static” keyword can be used for declaring a static member. If the class is made static then all the members of the class are also made static. If the variable is made static then it will have a single instance and the value change is updated in this instance.
63) What is the difference between “dispose” and “finalize” variables in C#?
Ans:
64) How the exception handling is done in C#?
Ans:
In C# there is a “try… catch” block to handle the error.
65)Can we execute multiple catch blocks in C#?
Ans:
No. Once any exception is occurred it executes specific exception catch block and the control comes out.
66)Why to use “finally” block in C#?
Ans:
“Finally” block will be executed irrespective of exception. So while executing the code in try block when exception is occurred, control is returned to catch block and at last “finally” block will be executed. So closing connection to database / releasing the file handlers can be kept in “finally” block.
67) What is the difference between “finalize” and “finally” methods in C#?
Ans:
68)What is the difference between “throw ex” and “throw” methods in C#?
Ans:
69) Can we have only “try” block without “catch” block in C#?
Ans:
Yes we can have only try block without catch block but we have to have finally block.
70) List out two different types of errors in C#?
Ans:
71)Do we get error while executing “finally” block in C#?
Ans:
Yes. We may get error in finally block.
72 Mention the assembly name where System namespace lies in C#?
Ans:
Assembly Name – mscorlib.dll
73) What are the differences between static, public and void in C#?
Ans:
74) What is the difference between “out” and “ref” parameters in C#?
Ans:
“out” parameter can be passed to a method and it need not be initialized where as “ref” parameter has to be initialized before it is used.
75) Explain Jagged Arrays in C#?
Ans:
If the elements of an array is an array then it’s called as jagged array. The elements can be of different sizes and dimensions.
76)Can we use “this” inside a static method in C#?
Ans:
No. We can’t use “this” in static method.
77)What are value types in C#?
Ans:
Below are the list of value types in C# –
78)What are reference types in C#?
Ans:
Below are the list of reference types in C# –
79) Can we override private virtual method in C#?
Ans:
No. We can’t override private virtual methods as it is not accessible outside the class.
80) Explain access modifier – “protected internal” in C#?
Ans:
“protected internal” can be accessed in the same assembly and the child classes can also access these methods.
81) In try block if we add return statement whether finally block is executed in C#?
Ans:
Yes. Finally block will still be executed in presence of return statement in try block.
82)What you mean by inner exception in C#?
Ans:
Inner exception is a property of exception class which will give you a brief insight of the exception i.e, parent exception and child exception details.
83)Explain String Builder class in C#?
Ans:
This will represent the mutable string of characters and this class cannot be inherited. It allows us to Insert, Remove, Append and Replace the characters. “ToString()” method can be used for the final string obtained from StringBuilder. For example,
84) What is the difference between “StringBuilder” and “String” in C#?
Ans:
85) What is the difference between methods – “System.Array.Clone()” and “System.Array.CopyTo()” in C#?
Ans:
86) How we can sort the array elements in descending order in C#?
Ans:
“Sort()” method is used with “Reverse()” to sort the array in descending order.
87) Explain circular reference in C#?
Ans:
This is a situation where in, multiple resources are dependent on each other and this causes a lock condition and this makes the resource to be unused.
88) List out some of the exceptions in C#?
Ans:
Below are some of the exceptions in C# –
89) Explain Generics in C#?
Ans:
90) Explain object pool in C#?
Ans:
Object pool is used to track the objects which are being used in the code. So object pool reduces the object creation overhead.
91) What you mean by delegate in C#?
Ans:
Delegates are type safe pointers unlike function pointers as in C++. Delegate is used to represent the reference of the methods of some return type and parameters.
92) What are the differences between events and delegates in C#?
Ans:
Main difference between event and delegate is event will provide one more of encapsulation over delegates. So when you are using events destination will listen to it but delegates are naked, which works in subscriber/destination model.
93)Can we use delegates for asynchronous method calls in C#?
Ans:
Yes. We can use delegates for asynchronous method calls.
94).What are the uses of delegates in C#?
Ans:
Below are the list of uses of delegates in C# –
95)What is Nullable Types in C#?
Ans:
Variable types does not hold null values so to hold the null values we have to use nullable types. So nullable types can have values either null or other values as well.
96) Why to use “Nullable Coalescing Operator” (??) in C#?
Ans:
Nullable Coalescing Operator can be used with reference types and nullable value types. So if the first operand of the expression is null then the value of second operand is assigned to the variable. For example,
97)What is the difference between “as” and “is” operators in C#?
Ans:
“as” operator is used for casting object to type or class.
“is” operator is used for checking the object with type and this will return a Boolean value.
98) Define Multicast Delegate in C#?
Ans:
A delegate with multiple handlers are called as multicast delegate. The example to demonstrate the same is given below
public delegate void CalculateMyNumbers(int x, int y);
99)What is the difference between CType and Directcast in C#?
Ans:
CType is used for conversion between type and the expression.
Directcast is used for converting the object type which requires run time type to be the same as specified type.
100) Is C# code is unmanaged or managed code?
Ans:
C# code is managed code because the compiler – CLR will compile the code to Intermediate Language.