C#.Net Interview Questions
Back to:
Interview Questions
Explain the difference between ref and out parameters. Provide an example.
Answer:
ref
parameters must be initialized before being passed to a method, and they can be read and modified.
out
parameters do not need to be initialized before being passed, but they must be assigned a value within the method.
Example:
using System;
class Program
{
static void Main()
{
int x = 5;
int result;
// Using ref
ModifyRef(ref x);
Console.WriteLine($"Value after ref modification: {x}"); // Output: 10
// Using out
InitializeOut(out result);
Console.WriteLine($"Value after out initialization: {result}"); // Output: 42
}
static void ModifyRef(ref int num)
{
num *= 2;
}
static void InitializeOut(out int num)
{
num = 42; // Must assign a value
}
}
How does exception handling work in C#? Provide an example using try, catch, finally.
Answer:
try
block contains code that might throw an exception.
catch
block handles exceptions.
finally
block contains code that executes regardless of whether an exception occurs.
Example:
class Program
{
static void Main()
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // This will throw an exception
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Caught an exception: " + ex.Message);
}
finally
{
Console.WriteLine("This is the finally block, executed regardless of exception.");
}
}
}
What is an anonymous method or lambda expression? Provide an example.
Answer:
- An anonymous method is a method without a name, defined in-line using the
delegate
keyword.
- A lambda expression is a shorthand syntax for anonymous methods using the
=>
operator.
Example:
using System;
class Program
{
static void Main()
{
// Anonymous method
Func<int, int> squareAnonymous = delegate (int x) {
return x * x;
};
// Lambda expression
Func<int, int> squareLambda = x => x * x;
Console.WriteLine("Square (Anonymous): " + squareAnonymous(5)); // Output: 25
Console.WriteLine("Square (Lambda): " + squareLambda(5)); // Output: 25
}
}
Coding Problems: Reverse a String
public class Program
{
public static string ReverseString(string input)
{
char[] arr = input.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
static void Main()
{
string original = "Hello";
string reversed = ReverseString(original);
Console.WriteLine(reversed); // Outputs: olleH
}
}
What are the main features of C#?
- Object-Oriented Programming (OOP)
- Strongly Typed
- Component-oriented
- Interoperability
- Automatic Memory Management (Garbage Collection)
- Modern Language Constructs (e.g., LINQ, async/await
What is the difference between abstract class and interface in C#?
Answer:
- Abstract Class: Can contain method implementations, fields, properties, and constructors. It can be partially implemented and derived classes can inherit from it.
- Interface: Cannot contain fields or constructors. Methods are implicitly abstract and must be implemented by classes that use the interface.
Coding Example:
public abstract class Shape
{
public abstract void Draw();
public void Print()
{
Console.WriteLine("Shape");
}
}
public interface IShape
{
void Draw();
}
public class Circle : Shape, IShape
{
public override void Draw()
{
Console.WriteLine("Drawing Circle");
}
}
class Program
{
static void Main()
{
Circle circle = new Circle();
circle.Draw(); // Drawing Circle
circle.Print(); // Shape
}
}
What is LINQ and how is it used in C#?
Answer:
LINQ (Language Integrated Query) is a feature that allows querying of collections in a declarative manner using query syntax or method syntax. It supports querying in-memory collections, databases, XML, and more.
Coding Example:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Query syntax
var evenNumbers = from number in numbers
where number % 2 == 0
select number;
// Method syntax
var evenNumbersMethodSyntax = numbers.Where(n => n % 2 == 0);
Console.WriteLine("Even numbers (Query syntax):");
foreach (var number in evenNumbers)
{
Console.WriteLine(number);
}
Console.WriteLine("Even numbers (Method syntax):");
foreach (var number in evenNumbersMethodSyntax)
{
Console.WriteLine(number);
}
}
}
What are the access modifiers in C# and what do they do?
public
: Accessible from anywhere.
private
: Accessible only within the class or struct where it is declared.
protected
: Accessible within the class and by derived class instances.
internal
: Accessible within the same assembly.
protected internal
: Accessible within the same assembly and from derived classes.
Coding Problems: Implement a basic implementation of the Singleton pattern.
public class Singleton
{
private static Singleton _instance;
private static readonly object _lock = new object();
private Singleton() { }
public static Singleton Instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
}
}
class Program
{
static void Main()
{
Singleton instance1 = Singleton.Instance;
Singleton instance2 = Singleton.Instance;
Console.WriteLine(ReferenceEquals(instance1, instance2)); // Outputs: True
}
}
What is the difference between method overloading and method overriding? Provide examples.
Answer:
- Overloading: Multiple methods with the same name but different parameters in the same class.
- Overriding: Redefining a method in a derived class that is already defined in the base class using the
override
keyword.
Example:
using System;
class BaseClass
{
public virtual void Display()
{
Console.WriteLine("BaseClass Display");
}
}
class DerivedClass : BaseClass
{
public override void Display()
{
Console.WriteLine("DerivedClass Display");
}
// Method Overloading
public void Display(string message)
{
Console.WriteLine("Message: " + message);
}
}
class Program
{
static void Main()
{
BaseClass baseObj = new BaseClass();
DerivedClass derivedObj = new DerivedClass();
baseObj.Display(); // Output: BaseClass Display
derivedObj.Display(); // Output: DerivedClass Display
derivedObj.Display("Hello!"); // Output: Message: Hello!
}
}
What is the purpose of async and await in C#?
Answer:
async
and await
are used to simplify asynchronous programming. async
is used to mark methods that contain await
calls, and await
is used to wait for the completion of an asynchronous operation without blocking the main thread.
Coding Example:
public class Program
{
public static async Task Main(string[] args)
{
Console.WriteLine("Start");
await LongRunningOperation();
Console.WriteLine("End");
}
public static async Task LongRunningOperation()
{
await Task.Delay(3000); // Simulate a long-running operation
Console.WriteLine("Operation Completed");
}
}
Explain the difference between class and struct in C#.
Answer:
- Class: Classes are reference types. They are stored in the heap and support inheritance, polymorphism, and encapsulation.
- Struct: Structs are value types. They are stored on the stack and are generally used for small data structures. Structs do not support inheritance and are generally used for lightweight objects.
Coding Example:
public class MyClass
{
public int Value;
}
public struct MyStruct
{
public int Value;
}
class Program
{
static void Main()
{
MyClass classInstance1 = new MyClass { Value = 10 };
MyClass classInstance2 = classInstance1;
classInstance2.Value = 20;
MyStruct structInstance1 = new MyStruct { Value = 10 };
MyStruct structInstance2 = structInstance1;
structInstance2.Value = 20;
Console.WriteLine($"Class Value1: {classInstance1.Value}"); // 20
Console.WriteLine($"Class Value2: {classInstance2.Value}"); // 20
Console.WriteLine($"Struct Value1: {structInstance1.Value}"); // 10
Console.WriteLine($"Struct Value2: {structInstance2.Value}"); // 20
}
}
Coding Problems: Find the First Non-Repeating Character in a String
public static char FirstNonRepeatingCharacter(string s)
{
Dictionary<char, int> charCount = new Dictionary<char, int>();
foreach (char c in s)
{
if (charCount.ContainsKey(c))
charCount[c]++;
else
charCount[c] = 1;
}
foreach (char c in s)
{
if (charCount[c] == 1)
return c;
}
throw new InvalidOperationException("No non-repeating characters found.");
}
Coding Problems: Find the largest number in an array
public class Program
{
public static int FindLargest(int[] numbers)
{
int max = numbers[0];
foreach (int num in numbers)
{
if (num > max)
{
max = num;
}
}
return max;
}
static void Main()
{
int[] numbers = { 1, 5, 3, 9, 2 };
int largest = FindLargest(numbers);
Console.WriteLine(largest); // Outputs: 9
}
}
What is C#.Net?
Certainly! C# (pronounced "C-sharp") is a modern, object-oriented programming language developed by Microsoft. It was introduced in 2000 as part of the .NET framework and has since become a popular language for a wide range of applications, from web and desktop development to game development and cloud services.
Key Features of C#:
-
Object-Oriented: C# is designed around the principles of object-oriented programming (OOP), which includes concepts such as classes, objects, inheritance, polymorphism, and encapsulation.
-
Strongly Typed: C# enforces type safety, meaning that type errors are caught at compile time rather than at runtime. This helps in reducing bugs and improving code quality.
-
Modern Syntax: C# syntax is designed to be simple and expressive, with features such as properties, indexers, and events that make it easier to write and understand code.
-
Garbage Collection: C# includes automatic memory management through garbage collection, which helps manage memory allocation and deallocation, reducing the risk of memory leaks and other related issues.
-
Language Integrated Query (LINQ): LINQ is a powerful feature that allows querying of data from various sources (like arrays, collections, databases) using a consistent syntax.
What is the difference between Html.BeginForm() and Html.ActionLink()?
Answer:
Html.BeginForm()
creates a form for submitting data, while Html.ActionLink()
generates a hyperlink to a specific action method.
What are ViewModels? Why are they used?
Answer:
- ViewModels are classes that contain data specifically tailored for Views. They help separate presentation logic from business logic.