Basic and Advance C# Questions
Basic and Advance C# Questions
1. What is C#?
o Object-Oriented
o Type-Safety
o Garbage Collection
o Language Interoperability
o Exception Handling
o Multithreading support
o Task is part of the TPL and is used for parallel programming and
asynchronous operations. Thread represents a separate line of
execution but lacks the overhead and management features of
Task.
7. What is the difference between readonly and const in C#?
o Value types hold the data directly and are stored in the stack
(e.g., int, struct). Reference types store references to the data,
which is stored in the heap (e.g., class, array).
o lock is used to ensure that only one thread can access a critical
section of code at a time, which helps in synchronizing access to
shared resources.
**************************************************************************
***********
1. What is the difference between int and Int32 in C#?
Both int and Int32 represent the same data type in C#. int is an alias
for System.Int32. The difference is that int is more commonly used,
while Int32 is part of the .NET Framework's System namespace.
struct Point
public int X;
public int Y;
if (obj is string)
Console.WriteLine("It's a string!");
try
string s = "Hello";
7. How would you handle a situation where you need to allow for
multiple exceptions in one try block?
try
Console.WriteLine(ex.Message);
}
Console.WriteLine(ex.Message);
A null reference occurs when you try to access an object that is not
initialized (i.e., it is set to null).
You can handle null values by using null checks (== null) or null-
coalescing operator (??).
class Animal
{
public void Speak() => base.Speak(); // Calls the base class Speak method
The readonly keyword ensures that a field can only be assigned a value
once, either in its declaration or in the constructor.
class MyClass
12. What is the purpose of the new keyword in method hiding in C#?
class BaseClass
13. How can you force a method to execute after all the objects
have been disposed of in C#?
You can use the Dispose method in a class that implements the
IDisposable interface to clean up resources after an object is no longer
in use.
{
public void Dispose()
// Cleanup resources
These are just some of the topics. Let me know if you'd like more detailed
explanations or examples for the remaining questions!
Sure! Here's the continuation with detailed explanations and examples for
the remaining questions:
arrayList.Add(1);
arrayList.Add("string");
// Thread example
thread.Start();
// Task example
namespace MyApp
class MyClass
}
}
The default keyword is used to return the default value for a type. For
value types, it returns the zeroed value (e.g., 0 for integers, false for
booleans), and for reference types, it returns null.
int x = default(int); // 0
The == operator checks for reference equality for reference types and
value equality for value types. The Equals() method is meant to check
for logical equality, and can be overridden in custom classes to provide
deep comparisons.
Console.WriteLine(str1.Equals(str2)); // True
try
{
int result = 10 / 0; // Throws DivideByZeroException
finally
28. What is the difference between ref and out parameters in C#?
Both ref and out are used to pass parameters by reference, but with
ref, the parameter must be initialized before it is passed, whereas with
out, the parameter doesn't need to be initialized, and it must be
assigned a value before the method exits.
int a = 5;
RefExample(ref a); // a = 15
int b;
OutExample(out b); // b = 10
class MyClass
Console.WriteLine(person.Item2); // John
32. What is the difference between a deep copy and a shallow copy
in C#?
// Shallow copy
class Animal
// Overloading
// Overriding
class BaseClass
interface IAnimal
void Speak();
Console.WriteLine("Process Started...");
process.StartProcess();
}
}
thread.Start();
Value types hold the actual data (e.g., int, double, struct). When a
value type is assigned to a new variable, a copy of the data is created.
interface IShape
{
void Draw();
lock (_lock)
using System;
using System.IO;
FileStream fs = new FileStream("example.txt", FileMode.Open);
yield return 1;
yield return 2;
yield return 3;
Console.WriteLine(number);
Console.WriteLine(value);
void Drive();
}
// In a DI container (e.g., in a framework like ASP.NET Core), you inject
dependencies
51. Explain the Task Parallel Library (TPL) and its usage in C#?
Task.Run(() => {
Console.WriteLine("Task running");
});
await SomeAsyncMethod();
task.Wait();
}
throw new CustomException("Something went wrong");
// IDisposable
// Finalizer
57. What is the async method in C# and when would you use it?
An async method is used to indicate that the method contains
asynchronous operations, making it easier to work with I/O-bound
operations. It allows the method to return a Task and can use await to
call other async methods.
return result;
// Runtime Polymorphism
list.Add(10); // Type-safe
Nullable types allow value types to represent null, which is useful for
cases where you need to represent the absence of a value, especially
with databases.
if (nullableInt.HasValue)
Console.WriteLine(nullableInt.Value);
// Append logic
}
}
Console.WriteLine(method.Name);
65. What are async methods and how do they help with concurrency
in C#?
Async methods are designed to run asynchronously, making it easier
to handle long-running I/O operations without blocking the main
thread. They allow for better responsiveness and scalability in
applications.
return data;
LINQ allows querying of collections (like arrays, lists, etc.) using SQL-
like syntax directly in C#. It provides a more readable and concise way
of filtering, sorting, and transforming data.
where n % 2 == 0
select n;
{
Name = name;
Age = age;
try
int result = 10 / 0;
Console.WriteLine(ex.Message);
finally
ThreadPool.QueueUserWorkItem(state => {
});
int counter = 0;
72. What is unsafe code in C# and why would you use it?
unsafe
Console.WriteLine(*ptr);
if (!disposed)
disposed = true;
notifyDelegate();
MyEvent?.Invoke(this, EventArgs.Empty);
78. What is the yield keyword in C# and when would you use it?
yield return 1;
yield return 2;
// Constructor Injection
_service = service;
// Serialization
// Deserialization
where n > 2
select n;
void Update();
The Singleton pattern ensures that a class has only one instance and
provides a global access point to that instance. It's often used for
shared resources like database connections or configuration settings.
private Singleton() { }
public static Singleton Instance
get
if (instance == null)
return instance;
GC.Collect();
// Use resource
Console.WriteLine(number);
return data;
95. What is Reflection and what are the use cases for it in C#?
yield return 1;
yield return 2;
yield return 3;
// Abstract class
// Interface
void Speak();
// Constructor Injection
_engine = engine;
// Usage
// Serialize
// Deserialize
select num;
void Update();
private Singleton() { }
get
if (instance == null)
return instance;
// Triggering GC manually
GC.Collect();
{
}
Async methods are methods that run asynchronously using the async
keyword. They return Task or Task<T>, and you use await inside these
methods to pause execution until the awaited task completes.
return data;
113. What is Reflection and what are the use cases for it in C#?
yield return 1;
yield return 2;
yield return 3;
A class can inherit only one abstract class, but it can implement
multiple interfaces.
// Abstract Class
// Interface
void Speak();
_engine = engine;
}
// Usage
// Serialize to JSON