Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C# Interview

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

What is C#?

C# is an object-oriented programming language developed by Microsoft. It is widely used for building


Windows applications and web applications.

What is the difference between static, public, and void?


static: It is a modifier that makes a member of a class, or a method belong to the class itself, rather than
to class instances.

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

public string Name;

public int Age;

// Constructor

public Person(string name, int age)

Name = name;

Age = age;

Public void Main(String[] args)

Person p1= new Person(“Shivani”,25);

Instead of Person p1= new Person(); p1.name=”shivani”; p1.Age=25;


What are Jagged Arrays?
Jagged arrays in C# are arrays of arrays. Unlike multi-dimensional arrays, each sub-array in a jagged array
can have a different length.

using System;

class Program

static void Main()

// Declare and initialize a jagged array with different sub-array lengths

int[][] jaggedArray = new int[3][];

jaggedArray[0] = new int[] { 1, 2, 3 };

jaggedArray[1] = new int[] { 4, 5 };

jaggedArray[2] = new int[] { 6, 7, 8, 9 };

// Access and display elements in the jagged array

for (int i = 0; i < jaggedArray.Length; i++)

for (int j = 0; j < jaggedArray[i].Length; j++)

Console.Write(jaggedArray[i][j] + " ");

Console.WriteLine();

What is the difference between out and ref parameters?


ref parameters are used to pass data by reference, allowing a method to modify the value of the
parameter.
out parameters are like ref, but they don't require the variable to be initialized before passing it to the
method. They are typically used to return values from a method.

What is the benefit of the 'using' statement in C#?


The 'using' statement is used for resource management, especially with objects that implement the
IDisposable interface. It ensures that the resource is properly disposed of when it's no longer needed,
which helps in preventing resource leaks and improving code reliability.

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.

Can the "this" keyword be used within a static method?


No, the "this" keyword cannot be used within a static method because it refers to an instance of the class
and static methods are not associated with any instance but with the class itself.

Break and Continue Statement:


break: Used to exit a loop (e.g., for, while, switch) prematurely. It immediately terminates the loop and
proceeds with the code after the loop.

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.

Types of Comments in C#:


Single-line comments: Begin with // and are used to annotate a single line of code.

Multi-line comments: Enclosed in /* and */ and can span multiple lines.

XML comments: Special comments that start with /// and are used for documenting code to generate
XML documentation files.

C# Code Compilation Steps:


Preprocessing: Involves handling preprocessor directives (#if, #else, #endif) and macro substitutions.

Compilation: Translates C# code into an intermediate language called Common Intermediate Language
(CIL).

Assembly Generation: Converts CIL into assembly (DLL or EXE).

Execution: The assembly is executed by the Common Language Runtime (CLR).

Passing Parameters in C#:


Value parameters: Pass by value; a copy of the value is passed.
Reference parameters: Pass by reference using ref or out keywords, allowing modification of the original
value.

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.

Strongly typed language.

Memory management via garbage collection.

Versatile and extensible through .NET Framework.

Good support for multithreading.

Modern language features and libraries.

IDEs for C# Development by Microsoft:


Visual Studio

Visual Studio Code

Why Use C#?


C# is used for developing Windows applications, web applications, games, and more.

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.

Unmanaged vs. Managed Code:


Unmanaged code: Code written in languages like C or C++ that don't run under the control of a runtime
environment. It's directly executed by the operating system.
Managed code: Code written in languages like C# that runs within a runtime environment (Common
Language Runtime in C#). It benefits from features like automatic memory management and enhanced
security.

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 vs. Finalize:


finalize: It's a method in C# used for cleaning up resources like file handles or database connections. It's
called automatically by the garbage collector before an object is reclaimed.

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.

Read-only vs. Constants:


read-only: Variables declared as read-only can only be assigned a value at the time of declaration or
within the constructor of the class. Their values can't be changed after that.

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.

Reference Types vs. Value Types:


Reference types (e.g., classes, interfaces): Stored on the heap, and variables store references to their
memory locations. Changes made to one reference affect all references to the same object.

Value types (e.g., structs, primitives): Stored on the stack, and variables store the actual data. Changes
are isolated to the specific variable.

User Control vs. Custom Control:


User Control: A user control is a reusable UI component created by combining existing controls (e.g.,
buttons, textboxes) into a single unit. It's easier to design and use in Windows Forms applications.
Custom Control: A custom control is a more complex, custom-built UI element often extending existing
controls. It provides greater flexibility but is more complex to create and use.

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 vs. Array:


Array: A fixed-size collection that stores elements of the same data type. Its size is determined at
creation and cannot change.

ArrayList: A dynamic collection that can store elements of different data types. It can grow or shrink in
size dynamically.

Private Virtual Method Override:


No, a private method can't be overridden because it's not accessible outside the class it's defined in.
Overriding is for changing behavior in derived classes, and private methods can't be accessed in derived
classes.

Accessibility Modifier "protected internal":


protected internal means a member is accessible within the current assembly and any derived classes,
even if they are in a different assembly. It provides a broader level of access.

System.String vs. System.Text.StringBuilder:


System.String: Immutable (can't be changed after creation), ideal for storing constant strings. Creates a
new string for every modification.

System.Text.StringBuilder: Mutable (can be modified), efficient for building or modifying strings, as it


avoids creating new instances for each change.

System.Array.CopyTo() vs. System.Array.Clone():


CopyTo(): Copies elements from one array to another. You specify the destination array and index.

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.

Abstract Class vs. Interface:


Abstract Class: Can have method implementations and fields. It can't be instantiated and is meant to be
extended by derived classes.

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.

Dispose() vs. Finalize() Methods:


Dispose(): Used for manual cleanup of unmanaged resources (e.g., file handles, database connections).
It should be called explicitly by the developer.

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.

Object Pool in .NET:


An object pool is a collection of reusable objects, often used to manage expensive-to-create objects. It
improves performance by recycling and reusing objects rather than creating new ones each time.

Commonly Used Exception Types in .NET:


FormatException: Thrown when the format of a value is not valid. (given string but the data type is int
type )

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];

IO.IOException: Thrown for various input/output-related errors.

DivideByZeroException: number divided by zero.[Arithmetic Exception]


FileNotFoundException:attempt to access file that does not exists.

InvalidOperationException: when the object is in an inapplicable state. Example: empty list(count=0)

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 Overriding vs. Method Overloading:


Method Overriding: A derived class provides a specific implementation for a method defined in the base
class, replacing the base class's behavior.

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.

Inheriting a Class in C#:


Use the : symbol to inherit a class. For example class DerivedClass : BaseClass.

Ways to Overload a Method:


Change the number of parameters.

Change the data types of parameters.

Change the order of parameters (but with different types).

Use different combinations of parameters.

Accessibility Modifier in Interface Methods:


Interface methods are implicitly public and cannot have other access modifiers specified. They are
meant to be part of a contract that derived classes must follow.

Inheriting a Class and Preventing Method Override:


Use the sealed keyword on a method in the base class to prevent it from being overridden in derived
classes. The class itself can still be inherited.

Method Name Conflicts in Inherited Interfaces:


If method names conflict in inherited interfaces, you need to explicitly implement the interfaces in the
derived class and provide different implementations with different names.
Struct vs. Class:
Struct: Value type, stored on the stack, suitable for small, lightweight data structures. Cannot be
inherited, no null value.

Class: Reference type, stored on the heap, used for more complex objects. Supports inheritance, can
have null values.

Nullable Types in .NET:


Use the ? modifier after a value type (e.g., int?) to make it nullable. Nullable types allow the variable to
have a null value in addition to its normal value range.

Creating an Array with Non-Standard Values:


Initialize an array with custom values by specifying them when you create the array, like: int[] numbers =
new int[] { 1, 2, 3, 4 };

"is" vs. "as" Operators:


is: Checks if an object is of a specific type and returns a boolean.

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.

Difference Between "throw" and "throw ex" in .NET:


throw: Throws an exception while preserving the original call stack information.

throw ex: Throws an exception while resetting the call stack information, potentially losing the original
exception context.

C# Attributes and Significance:


Attributes are metadata applied to code elements. They provide information to compilers, tools, and
runtime about how to process the code. Used for documentation, diagnostics, and code generation.

Implementing the Singleton Design Pattern in C#:


Use a private static instance of the class.

Create a private constructor to prevent external instantiation.

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.

Features of Generics in C#:


Type safety: Ensures data types are known at compile time.

Code reusability: Write code that works with different data types.

Performance: Reduces boxing/unboxing operations.

Strongly typed collections: Create type-safe data structures.

SortedList vs. SortedDictionary in C#:


SortedList: Uses an array and maintains elements in sorted order. Good for frequent read access.

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.

Constructor Chaining in C#:


Constructor chaining allows one constructor of a class to call another constructor in the same class,
often with different parameters. It helps avoid code duplication when creating different object
initialization scenarios.
Multicasting Delegate in C#:
A multicasting delegate is a delegate that can hold references to multiple methods. When invoked, it
calls all the referenced methods in the order they were added.

Virtual Method in C#:


A virtual method is a method in a base class that can be overridden by derived classes. This enables
polymorphism, allowing different classes to provide their own implementation of the method.

Multithreading with .NET:


Multithreading is the concurrent execution of multiple threads in a single application. In .NET, it allows
your program to perform multiple tasks at the same time, improving performance and responsiveness.

Hash Table Class in C#:


A hash table is a data structure in C# that stores key-value pairs. It uses a hash code to efficiently locate
and retrieve values based on their keys.

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

Private Virtual Procedure Override:


A private virtual method can't be overridden because it's private and not accessible from derived classes.
Overriding is only possible when the method can be accessed in derived classes.

File Handling in C#:


File handling involves reading from and writing to files. C# provides classes like File, FileStream, and
StreamWriter to work with files.

Get and Set Accessor Properties:


Get accessor: Retrieves the value of a property.

Set accessor: Sets the value of a property.

Properties provide a way to encapsulate data and control how it's accessed and modified.

Async and Await in C#:


async and await are used to write asynchronous code in C#. They allow non-blocking execution of tasks,
improving application responsiveness. async methods can "await" other asynchronous operations.

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.

Regular Expressions in C#:


Regular expressions are patterns used for matching and manipulating text. In C#, the
System.Text.RegularExpressions namespace provides classes to work with regular expressions for tasks
like text search and manipulation.

Types of Classes in C#:


There are primarily four types of classes in C#:

Regular Classes: Standard classes used for creating objects.

Abstract Classes: Classes that can't be instantiated and serve as a base for other classes.

Sealed Classes: Classes that can't be inherited.

Static Classes: Classes that can't be instantiated and contain only static members.

Garbage Collection in C#:


Garbage collection is the automatic process of reclaiming memory occupied by objects that are no
longer in use. The .NET runtime manages this to free up resources and prevent memory leaks.

Extension Methods in C#:


Extension methods allow you to add new methods to existing classes without modifying their source
code. They're defined as static methods in static classes and are used to extend the functionality of
types.

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.

Boxing and Unboxing in C#:


Boxing: The process of converting a value type (e.g., int) to an object reference. It wraps the value in an
object.

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.

Equality Operator (==) vs. Equals() Method in C#:


== checks if two variables reference the same memory location or have the same value for value types.

Equals() method is used to compare the content or value of objects. It can be overridden to provide
custom comparison logic.

Ways to Overload a Method in C#:


Change the number of parameters.

Change the data types of parameters.

Change the order of parameters.

Use different combinations of parameters.

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.

Constant vs. Readonly in C#:


const: Values are known at compile-time and cannot change. They are compile-time constants.

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.

String vs. StringBuilder in C#:


String: Immutable; when you modify a string, it creates a new one. Suitable for constant values.

StringBuilder: Mutable; designed for efficient string manipulation, especially when you need to make
many modifications to a string.

Multiple Catch Blocks Execution:


Only one catch block will be executed, the first one that matches the exception type. If no matching
catch block is found, the program terminates.
Public, Static, and Void:
public: Access modifier, allows members to be accessed from outside the class.

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.

Ref vs. Out Parameters:


ref: Used to pass a variable as a method parameter, allowing the method to read and modify the
variable's value.

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.

Constants vs. Read-only:


Constants are known at compile-time and cannot change.

Read-only values are determined at runtime, often in the constructor, and can't be changed after they're
assigned.

Value Types vs. Reference Types:


Value Types: Store the actual data directly, and changes do not affect other variables. (e.g., int, struct)

Reference Types: Store references to data in memory, so changes affect all references to the same
object. (e.g., class, interface)

Sealed Classes in C#:


Sealed classes are classes that cannot be inherited. They prevent other classes from extending or
deriving from them.

Benefits of Using C#:


Type safety

Garbage collection

Rich class library (BCL)

Modern language features

Interoperability with .NET Framework

Strong community and tool support


IDEs for C# Development by Microsoft:
Visual Studio

Visual Studio Code

Multiple Inheritances in C#:


C# supports single inheritance for classes but allows multiple interface inheritance. Classes cannot
inherit from multiple classes, but they can implement multiple interfaces.

C++ vs. C#:


C++ and C# are different programming languages.

C++ is a multi-paradigm language with manual memory management.

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.

Symbols for Code Blocks:


{ and } are used to mark the start and end of a code block in C#.

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.

C# Syntax to Catch an Exception:


try {

// Code that may throw an exception

catch (Exception ex) {

// Handle the exception, ex contains details

Removing an Element from a Queue:


Queue<int> queue = new Queue<int>();
queue.Enqueue(1);

queue.Enqueue(2);

int removedElement = queue.Dequeue(); // Removes and returns the element.

Keyword to Exit Loop:


The break keyword is used to exit from a loop in C#.

Members of Namespaces in C#:


Namespaces can contain classes, interfaces, enums, structs, and other namespaces.

Private Virtual Method Overriding:


No, a private virtual method cannot be overridden in C# because it's not accessible in derived classes.

Symbol to Terminate a Statement:


A semicolon (;) is used to terminate a statement in C#.

C# Case-Sensitivity:
Yes, C# is case-sensitive. It treats uppercase and lowercase letters as distinct.

Symbol for Single-Line Comment:


Double forward slashes (//) mark the beginning of a single-line comment in C#.

Symbols for Multi-Line Comment:

Multi-line comments begin with /* and end with */.

Statement to Declare a Variable:


To declare a variable in C#, use the syntax: datatype variableName;

Data Type for Storing Text Value:


The string data type is used to store text values in C#.

Syntax to Define a Constant:


To define a constant in C#, use the const keyword: const datatype constantName = value;

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.

Foreach Loop in C#:


Yes, you can use a foreach loop in C# to iterate over elements in collections like arrays, lists, and
dictionaries.
Throw Statement in C#:
The throw statement is used to raise exceptions in C#. It is used to signal that an error or exceptional
condition has occurred.

Class for UInt in C#:


The UInt data type in C# is derived from the System.ValueType class.

Access Specifier for Main() Method:


The Main() method in C# should have the public access specifier to be the entry point of a program.

Use of Pointers in C#:


Pointers in C# allow you to work with memory directly and can be used for tasks like interop with
unmanaged code. They are not typically used in managed C# code due to safety and security concerns.

Symbol to Access Variables/Fields in a Class:


A dot (.) is used to access variables and fields inside a class.

Variable Declaration in C#:


To declare a variable in C#, use the syntax: datatype variableName;

Exception Handling in C#:


Exception handling in C# is done using try, catch, finally, and throw. You enclose code that might throw
an exception in a try block, and use catch to handle exceptions and finally to ensure code is executed,
regardless of whether an exception is thrown.

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.

Steps of Code Compilation in C#:


Preprocessing

Compilation

Intermediate Language Generation

Just-In-Time (JIT) Compilation

Execution

Access Modifiers in C#:


Some common access modifiers are public, private, protected, internal, protected internal, and private
protected.
Parameter for Returning Multiple Values:
To return multiple values from a function in C#, you can use the out or ref parameters.

Abstract Class in C#:


An abstract class is a class that cannot be instantiated and is meant to be a base for other classes. It may
contain abstract methods (methods without implementation) that derived classes must implement.

Default Interface Method in C#:


In C#, the default implementation for an interface method is an empty method (with no code) in the
implementing class. You can provide custom implementation in the implementing class.

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.

Role of Access Modifier in C#:


Access modifiers control the visibility and accessibility of classes, methods, and fields. They specify
where a class or member can be accessed from and by which code.

Types of Constructors in C#:


There are three types of constructors in C#: default constructors, parameterized constructors, and copy
constructors.

Syntax for Declaring an Object of a Class:


To declare an object of a class in C#, use the syntax: ClassName objectName = new ClassName();

Symbol to Define Variable Type for Array:


The square brackets [] are used to define the variable type when declaring an array in C#.

String.Length in C#:
String.Length in C# is a property that returns the number of characters in a string.

Operator for Comparing Strings:


The != operator is used to decide whether two given strings have different values in C#.

Object vs. Dynamic Type Variables:


Object type variables are statically typed and require casting for member access.

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)

By reference (ref keyword)

As output (out keyword)

Using parameter arrays (params keyword)

Running an Infinite Loop with for Statement:


You can run an infinite loop with for(;;) in C# by omitting the initialization, condition, and iterator
expressions. This creates an unconditional infinite loop.

Data Types in C#:


Common data types in C# include int, string, double, char, bool, and more.

Keywords in C#:
Keywords are reserved words in C# with special meanings. Examples include if, else, for, class, and
return.

Local Variable in C#:


A local variable is a variable declared within a method, constructor, or block of code and is only
accessible within that scope.

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.

C# and Multiple Inheritances:


C# does not support multiple inheritances to avoid issues like the diamond problem, which can occur
when a class inherits from two classes with conflicting members. C# uses interfaces to achieve similar
functionality while avoiding these conflicts.

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.

Changing Variable Value While Debugging:


Yes, you can change the value of a variable while debugging an application in most debugging
environments, allowing you to inspect and modify variable values during runtime.

StreamReader and StreamWriter in C#:


StreamReader is used for reading text from a file.
StreamWriter is used for writing text to a file. They simplify file input and output operations in C#.

File Handling in C#:


File handling in C# involves reading from and writing to files. It uses classes like FileStream,
StreamReader, and StreamWriter to work with files.

Boxing and Unboxing:


Boxing is the process of converting a value type to an object type.

Unboxing is the reverse process, converting an object back to a value type.

Struct vs. Class in C#:


Struct is a value type, stored on the stack, often used for small, lightweight data.

Class is a reference type, stored on the heap, suitable for more complex objects, supports inheritance.

Task vs. Thread in C#:


Task is a higher-level abstraction that represents an asynchronous operation, making better use of
system resources.

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.

Accessibility Modifier in Interface Methods:


Interface methods are always public and cannot have other access modifiers specified. They are meant
to be part of a contract that derived classes must follow.

You might also like