C%23 Interview Questions
Try Aihirely for
Smarter Interview Prep
Experience real-time AI support tailored to your Resume.
Boost your confidence and ace every question with
AI Mock Interview.
Question: What is method overloading in C#?
Answer:
Method Overloading in C# is a feature that allows a class to have more than one method with the same name, but with different method signatures. This means you can define multiple methods with the same name as long as their parameter lists (number, type, or order of parameters) are different.
Method overloading is particularly useful when you want to perform similar operations on different types of data or with a different number of parameters, and you want to use the same method name for clarity and convenience.
Key Points of Method Overloading:
- Same Method Name: All overloaded methods must share the same name.
- Different Signatures: The methods must differ by the number of parameters, the type of parameters, or the order of parameters.
- Return Type: The return type does not play a role in overloading. You cannot overload methods only by changing the return type.
Examples of Method Overloading in C#:
Example 1: Overloading Methods by Number of Parameters
using System;
class Calculator
{
// Method to add two integers
public int Add(int a, int b)
{
return a + b;
}
// Overloaded method to add three integers
public int Add(int a, int b, int c)
{
return a + b + c;
}
}
class Program
{
static void Main()
{
Calculator calc = new Calculator();
Console.WriteLine("Sum of 2 numbers: " + calc.Add(10, 20)); // Calls the method with two parameters
Console.WriteLine("Sum of 3 numbers: " + calc.Add(10, 20, 30)); // Calls the method with three parameters
}
}
Output:
Sum of 2 numbers: 30
Sum of 3 numbers: 60
In this example, both Add
methods have the same name, but they differ in the number of parameters.
Example 2: Overloading Methods by Type of Parameters
using System;
class Calculator
{
// Method to add two integers
public int Add(int a, int b)
{
return a + b;
}
// Overloaded method to add two doubles
public double Add(double a, double b)
{
return a + b;
}
}
class Program
{
static void Main()
{
Calculator calc = new Calculator();
Console.WriteLine("Sum of two integers: " + calc.Add(10, 20)); // Calls the method for integers
Console.WriteLine("Sum of two doubles: " + calc.Add(10.5, 20.5)); // Calls the method for doubles
}
}
Output:
Sum of two integers: 30
Sum of two doubles: 31
In this example, the Add
method is overloaded based on the type of parameters. One method accepts int
types, while the other accepts double
types.
Example 3: Overloading Methods by Order of Parameters
using System;
class Calculator
{
// Method to subtract two integers
public int Subtract(int a, int b)
{
return a - b;
}
// Overloaded method to subtract integers, but parameters in different order
public int Subtract(double a, int b)
{
return (int)(a - b); // Convert double to int for result
}
}
class Program
{
static void Main()
{
Calculator calc = new Calculator();
Console.WriteLine("Subtract integers: " + calc.Subtract(10, 5)); // Calls the first method
Console.WriteLine("Subtract double and integer: " + calc.Subtract(10.5, 5)); // Calls the overloaded method
}
}
Output:
Subtract integers: 5
Subtract double and integer: 5
Here, both methods perform subtraction, but they have different parameter orders: one takes int
first, while the other takes double
first.
When to Use Method Overloading:
- Handling Different Data Types: When you need the same operation to work on different types of data (e.g.,
int
,double
,string
). - Working with Different Numbers of Parameters: If the operation requires varying numbers of parameters (e.g., adding two or three numbers).
- Improving Readability and Maintainability: Instead of having multiple methods with different names for similar actions, overloading allows you to use the same method name, making your code more readable and easier to maintain.
Method Overloading vs Method Overriding:
- Overloading: Multiple methods with the same name but different parameter lists (done at compile time).
- Overriding: A method in a subclass that provides a specific implementation of a method already defined in its superclass (done at runtime).
Limitations of Method Overloading:
- The return type cannot be used to distinguish overloaded methods.
- Overloading is based solely on the method signature (parameter count, type, or order), so it’s important to design method signatures carefully to avoid confusion.
Summary:
Method overloading in C# is a technique that allows you to define multiple methods with the same name but different parameter lists (in terms of number, type, or order of parameters). This improves code clarity and reusability without changing the method name, which helps in handling similar tasks with varying inputs.
Question: What is managed and unmanaged code in C#?
Answer:
In C#, managed code and unmanaged code refer to two different types of code execution environments, with significant differences in how memory and resources are handled.
1. Managed Code:
Managed code refers to code that is written and executed under the control of the Common Language Runtime (CLR), which is the execution engine of the .NET Framework. The CLR handles memory management, type safety, exception handling, garbage collection, and other system-level tasks, making it more secure and easier to work with.
Key Characteristics of Managed Code:
- Memory Management: The CLR automatically manages memory through garbage collection. It allocates memory for objects, and when objects are no longer needed, it automatically frees up the memory.
- Type Safety: Managed code enforces type safety. The CLR ensures that types are used correctly, preventing common errors like invalid type casting.
- Security: Managed code runs within a secure environment, often referred to as a “sandbox,” where access to system resources can be restricted based on security policies.
- Exception Handling: The CLR provides a standardized way to handle exceptions, ensuring that errors are caught and managed properly.
- Runtime Services: The CLR provides various runtime services, such as reflection, debugging, and interoperability with other languages, which are available to managed code.
Example of Managed Code:
using System;
class Program
{
static void Main()
{
// Managed code executed by CLR
Console.WriteLine("Hello, Managed World!");
}
}
In this example, the Console.WriteLine
method is part of the .NET Framework, which runs under the CLR’s management.
2. Unmanaged Code:
Unmanaged code, on the other hand, refers to code that runs directly on the Windows operating system or hardware without the control or services of the CLR. It does not have the benefit of memory management, garbage collection, or type safety that managed code provides.
Unmanaged code typically refers to code written in languages like C or C++, where the programmer is responsible for managing memory manually (using malloc
, free
, etc.). When using unmanaged code, you need to manually allocate and free memory, and manage pointer operations.
Key Characteristics of Unmanaged Code:
- Manual Memory Management: Unmanaged code requires explicit allocation and deallocation of memory. Failure to do so can result in memory leaks or access violations.
- Direct Access to Hardware: Unmanaged code has more direct access to system resources, hardware, and APIs, which can offer better performance in certain cases.
- No Automatic Garbage Collection: Since unmanaged code does not run under the CLR, it does not benefit from garbage collection. Developers must ensure that memory is freed when it’s no longer needed.
- Risk of Memory Corruption: Due to the lack of type safety and garbage collection, unmanaged code can be more prone to errors like buffer overflows, invalid memory access, and pointer issues.
Example of Unmanaged Code (C/C++):
##include <iostream>
int main() {
// Unmanaged code executed directly by the OS
std::cout << "Hello, Unmanaged World!" << std::endl;
return 0;
}
In this C++ example, the code runs directly on the operating system without any intermediary like the CLR.
Managed vs Unmanaged Code in C#:
In C#, code is typically managed, but it is possible to interact with unmanaged code using P/Invoke (Platform Invocation) or unsafe code.
-
P/Invoke (Platform Invocation): This is a feature of the .NET Framework that allows managed code to call unmanaged functions, typically those in native libraries (like DLLs). This enables C# code to interact with the operating system or third-party unmanaged libraries.
-
Unsafe Code: C# allows “unsafe” code, which gives the ability to use pointers and perform direct memory manipulation, typically required when working with unmanaged resources. However, using unsafe code requires enabling the “unsafe” feature in your project.
Example of Calling Unmanaged Code from Managed Code (P/Invoke):
using System;
using System.Runtime.InteropServices;
class Program
{
// Declare a P/Invoke method to call an unmanaged function
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
static void Main()
{
IntPtr handle = GetModuleHandle("kernel32.dll");
Console.WriteLine("Module Handle: " + handle);
}
}
In this example, GetModuleHandle
is an unmanaged Windows function that is called from managed code via P/Invoke.
Managed vs Unmanaged Code Summary:
Feature | Managed Code | Unmanaged Code |
---|---|---|
Execution Environment | Runs under the CLR (Common Language Runtime) | Runs directly on the operating system or hardware |
Memory Management | Managed by garbage collector (GC) | Manual memory management using pointers and allocation/deallocation |
Type Safety | Enforced by the CLR | No built-in type safety; pointer operations can lead to errors |
Security | Runs in a secure environment (sandbox) | May access low-level system resources, less secure |
Performance | Can be less efficient due to abstraction layers | Can be more efficient due to direct access to hardware |
Error Handling | Handled by CLR with exception handling | Errors must be handled manually, and can lead to crashes if not managed properly |
When to Use Managed vs Unmanaged Code:
-
Managed Code:
- Preferred for most general application development where safety, productivity, and maintainability are important.
- Ideal for web, desktop, and enterprise applications where you don’t need low-level system access.
-
Unmanaged Code:
- Preferred when performance is critical, or when you need direct access to hardware or system resources.
- Used in systems programming, embedded software, or when working with legacy APIs or libraries.
Summary:
In C#, managed code runs under the control of the CLR and benefits from features like automatic memory management, security, and exception handling. Unmanaged code, on the other hand, runs directly on the system or hardware and requires manual memory management, offering higher performance but greater risk of errors. C# allows interacting with unmanaged code through features like P/Invoke and unsafe code, enabling flexibility when needed.
Read More
If you can’t get enough from this article, Aihirely has plenty more related information, such as C# interview questions, C# interview experiences, and details about various C# job positions. Click here to check it out.