C# Interview
C# Interview
C# Interview
public: It is an access modifier that allows a class member to be accessed from outside the class.
void: It is a return type used for methods that do not return any value.
What is an object?
An object is an instance of a class. It is a self-contained unit that contains both data [person name,
height] and the methods [drink, eat] that operate on the data.
Define Constructors.
Constructors are special methods in a class used to initialize objects of that class. They have the same
name as the class and are called when an object of the class is created.
Example:
class Person
// Constructor
Name = name;
Age = age;
using System;
class Program
Console.WriteLine();
What is serialization?
Serialization is the process of converting an object's state into a byte stream. It is used for saving or
transmitting objects, and then deserialization is the process of recreating the object from the byte
stream.
continue: Used to skip the current iteration of a loop and move to the next iteration. It doesn't exit the
loop but just continues with the next iteration.
XML comments: Special comments that start with /// and are used for documenting code to generate
XML documentation files.
Compilation: Translates C# code into an intermediate language called Common Intermediate Language
(CIL).
Parameter arrays: Use the params keyword to pass a variable number of arguments in an array.
Named parameters: Pass values by specifying the parameter names when calling a method.
C# Access Modifiers:
Public: Public members are accessible from anywhere in the code.
Private: Private members are accessible only within the class they are declared.
Protected: Protected members are accessible within the class and its derived classes.
Internal: Internal members are accessible within the same assembly (a compiled code unit).
Protected Internal: Protected Internal members are accessible within the same assembly and its derived
classes.
Private Protected: Private Protected members are accessible within the same assembly and its derived
classes but not from outside.
Default (No Modifier): Default members are accessible within the same assembly but not from outside.
Advantages of C#:
Object-oriented programming.
It's a part of the Microsoft ecosystem, making it a choice for Windows and .NET development.
C# Features (Briefly):
Object-Oriented: C# is based on object-oriented principles, allowing you to model real-world entities
using classes and objects.
Type Safety: C# enforces strict data type checking at compile-time, reducing runtime errors.
Memory Management: It includes automatic memory management through garbage collection, helping
to prevent memory leaks.
Interoperability: C# can work seamlessly with other languages and platforms, making it suitable for a
wide range of applications.
Platform Independence: C# applications can run on various platforms, thanks to the .NET Framework
and .NET Core.
Rich Standard Library: C# offers a comprehensive class library (BCL) with pre-built functions and classes
for common tasks.
Exception Handling: It provides robust exception handling for graceful error recovery and reporting.
Asynchronous Programming: C# supports asynchronous programming using async and await, enhancing
responsiveness in applications.
Strongly Typed: C# requires explicit data type declarations, enhancing code clarity and safety.
Security Features: It offers security features like code access security, making it suitable for secure
applications.
Delegates and Events: C# supports delegates and events, enabling the implementation of event-driven
applications.
LINQ (Language-Integrated Query): LINQ allows developers to query data from various sources using a
SQL-like syntax.
Reflection: It provides the ability to inspect and manipulate code at runtime, enhancing flexibility.
Properties and Indexers: C# offers properties to control access to class members and indexers to access
elements using square brackets.
Exception Handling: C# has a robust exception-handling mechanism to deal with unexpected errors and
exceptions gracefully.
Abstract Class:
An abstract class is a blueprint for other classes. It can't be instantiated on its own. It may contain
abstract methods (methods without implementation) that must be implemented by derived classes. It
allows the creation a common base for related classes.
Finalize blocks: There's no concept of "finalize blocks" in C#. Finalize is used for resource cleanup.
Interface:
An interface defines a contract for classes to follow. It specifies a set of methods and properties a class
must implement. Classes that implement an interface must provide implementations for all its members.
Partial Class:
A partial class is a class that can be split into multiple files. It allows you to separate the code for a single
class into multiple files while treating it as a single entity. Useful for code organization and collaboration.
Constants: Constants are declared with the const keyword and are assigned a value that can't be
changed throughout the program. They are compile-time constants.
Interface Class:
There is no specific concept called "interface class" in C#. It may refer to a class that implements an
interface or a class containing methods related to an interface.
Value types (e.g., structs, primitives): Stored on the stack, and variables store the actual data. Changes
are isolated to the specific variable.
Sealed Classes:
Sealed classes cannot be inherited or used as a base for other classes. They are designed to prevent
further derivation. Used when you want to ensure a class's implementation remains unchanged.
Method Overloading:
Method overloading allows you to define multiple methods in the same class with the same name but
different parameter lists. The method called depends on the number or types of arguments provided
when invoking the method. It's a way to provide multiple ways to perform the same task with different
inputs.
ArrayList: A dynamic collection that can store elements of different data types. It can grow or shrink in
size dynamically.
Clone(): Creates a shallow copy of the array. The new array references the same elements as the original,
but changes in one won't affect the other.
Sort Array in Descending Order:
Use Array.Sort() to sort in ascending order and then reverse the array with Array.Reverse() to achieve a
descending order.
Interface: Contains only method and property signatures. Classes that implement an interface must
provide implementations for all its members. A class can implement multiple interfaces but inherit from
only one class.
Finalize(): A method used for automatic cleanup by the garbage collector, but it's not guaranteed when it
will be called. It's less predictable and less commonly used.
Circular References:
Circular references occur when two or more objects reference each other, creating an infinite loop in
memory management. This can lead to memory leaks and unpredictable behavior.
Generics in C# .NET:
Generics allow you to create classes, interfaces, methods, or delegates with type parameters. They
provide type safety and code reusability by letting you use the same code with different data types.
ArgumentNullException: when the argument is null when it is not expected. Example: Required field.
NullReferenceException: thrown when attempting to access a member or method of a null object. Ex:
String text=” null”. Int length = text.length;
IndexOutOfRangeException: to access an array or collection with an index that is out of bounds. Ex:int[]
ar= {1,2,3}; int value=ar[5];
Custom Exceptions:
Custom exceptions are user-defined exception classes that extend the base System.Exception class. They
allow you to create specific exception types tailored to your application's needs.
Delegates:
Delegates are type-safe function pointers in C#. They can reference methods with matching signatures
and are used for implementing callbacks, event handling, and dynamic method invocation.
Method Overloading: Multiple methods in the same class with the same name but different parameters.
They provide different ways to use the same method name with different inputs.
Class: Reference type, stored on the heap, used for more complex objects. Supports inheritance, can
have null values.
as: Attempts to cast an object to a specific type and returns the casted object or null if the cast fails.
Multicast Delegate:
A delegate that can hold references to multiple methods. When invoked, it calls all the referenced
methods in the order they were added.
Indexers in C# .NET:
Indexers are properties that allow you to access elements of a collection or class using array-like syntax.
They use special get and set methods to provide element access.
throw ex: Throws an exception while resetting the call stack information, potentially losing the original
exception context.
Provide a public static method to return the single instance, creating it if it doesn't exist.
Difference Between DirectCast and CType:
DirectCast: Requires an exact type match during the casting operation. If the cast isn't possible, it throws
an exception.
CType: Allows type conversions, and if a direct conversion isn't possible, it tries to use standard type
conversions or returns Nothing if no conversion is possible.
C# Code:
C# code can be both managed and unmanaged. It's managed when running under the Common
Language Runtime (CLR) and unmanaged when it doesn't, such as in some interop scenarios.
Console Application:
A console application in C# is a program that runs in a console or command-line environment. It reads
and writes text from/to the console window and is often used for simple text-based programs.
Namespaces in C#:
Namespaces are used to organize and group related classes, structures, and other types in C#. They help
avoid naming conflicts and make it easier to manage code.
Code reusability: Write code that works with different data types.
SortedDictionary: Uses a balanced tree structure. Efficient for frequent insertions and deletions.
Tuple in C#:
A tuple is a data structure that can hold multiple elements of different data types. It provides a way to
group and pass around related values without creating custom classes or structures.
Events:
Events are a mechanism for communication between objects in C#. They allow one object to notify other
objects when a specific action or state change occurs.
LINQ in C#:
LINQ (Language-Integrated Query) is a feature that enables querying and manipulating data from various
sources, such as collections, databases, or XML, using a SQL-like syntax within C#.
Properties provide a way to encapsulate data and control how it's accessed and modified.
Indexer in C#:
An indexer is a property that allows an object to be indexed like an array. It provides a way to access
elements in a class or collection using square brackets.
I/O Classes in C#:
I/O (Input/Output) classes in C# are used for reading from and writing to various input and output
sources, such as files, streams, and consoles. Examples include FileStream, StreamReader, and
TextWriter.
Abstract Classes: Classes that can't be instantiated and serve as a base for other classes.
Static Classes: Classes that can't be instantiated and contain only static members.
Inheritance in C#:
Inheritance is a mechanism that allows a class to inherit properties and behaviors from another class. C#
supports single inheritance, meaning a class can inherit from one base class. It does not support multiple
inheritance, where a class inherits from multiple base classes.
Unboxing: The reverse process of extracting a value type from an object reference.
Properties in C#:
Properties are a way to expose private fields in a controlled manner. They consist of a get accessor (to
retrieve the value) and a set accessor (to modify the value).
Late Binding vs. Early Binding in C#:
Late Binding: The determination of the method or property to call is made at runtime. It's less efficient
and less type-safe.
Early Binding: The determination is made at compile time. It's more efficient and type-safe.
Arrays in C#:
Arrays are ordered collections of elements with the same data type. They have a fixed size and are zero-
indexed, meaning the first element is at index 0.
Equals() method is used to compare the content or value of objects. It can be overridden to provide
custom comparison logic.
Reflection in C#:
Reflection is the ability of a program to inspect, analyze, and manipulate its own structure and behavior
at runtime. It allows you to query and manipulate information about types, assemblies, and objects.
read-only: Values are determined at runtime, often in the constructor. They can't be changed after
they're assigned, but they are not compile-time constants.
StringBuilder: Mutable; designed for efficient string manipulation, especially when you need to make
many modifications to a string.
static: Specifies that a member belongs to the class itself, not to instances of the class.
void: Return type of a method, indicates the method doesn't return a value.
Jagged Arrays:
Jagged arrays are arrays of arrays where each element is an array. They can have varying sizes, allowing
you to create non-rectangular or irregularly shaped data structures.
out: Like ref, but the method is not required to assign a value to the variable. It's typically used for
returning multiple values from a method.
Read-only values are determined at runtime, often in the constructor, and can't be changed after they're
assigned.
Reference Types: Store references to data in memory, so changes affect all references to the same
object. (e.g., class, interface)
Garbage collection
C# is a managed language with automatic memory management through the Common Language
Runtime (CLR).
C# File Extension:
C# source code files typically have the ".cs" extension.
Operators:
Operators are symbols used to perform operations on variables and values. Examples include +, -, *, / for
arithmetic operations and ==, != for comparisons.
C# Type-Safety:
Yes, C# is a type-safe programming language. It enforces strong typing, preventing operations on data
that could lead to type-related errors. This helps catch errors at compile-time rather than runtime.
queue.Enqueue(2);
C# Case-Sensitivity:
Yes, C# is case-sensitive. It treats uppercase and lowercase letters as distinct.
Console in C#:
The Console in C# is a class that provides methods for interacting with the console, allowing input and
output operations like displaying text and reading user input.
Recursion in C#:
Recursion is a programming technique where a function calls itself to solve a problem. In C#, it's
commonly used for tasks like traversing tree structures or solving problems with repeating subproblems.
Compilation
Execution
Polymorphism in C#:
Polymorphism is a concept in C# where objects of different classes can be treated as objects of a
common base class. It allows methods to be called on objects without knowing their specific types.
String.Length in C#:
String.Length in C# is a property that returns the number of characters in a string.
Dynamic type variables are dynamically typed and do not require casting, but may lead to runtime
errors.
Ways to Pass Parameters to a Method in C#:
By value (default)
Keywords in C#:
Keywords are reserved words in C# with special meanings. Examples include if, else, for, class, and
return.
Inheritance in C#:
Inheritance is a mechanism that allows a class to inherit properties and behaviors from another class. It
promotes code reuse and the creation of a hierarchy of classes.
Read-Only Variable:
A read-only variable is one whose value is set once and cannot be changed afterward. It is typically used
to ensure the value remains constant after initialization.
Class is a reference type, stored on the heap, suitable for more complex objects, supports inheritance.
Thread is a lower-level construct for running code concurrently, with more overhead.
Encapsulation in C#:
Encapsulation is the practice of bundling data (attributes) and methods (behavior) into a single unit
called a class. It restricts direct access to some of an object's components, providing data protection and
control.
Destructor in C#:
A destructor is a method in C# that is used to clean up resources or perform cleanup operations when an
object is no longer needed. It is called automatically when an object is about to be destroyed.