Skip to main content

Top 30 Tricky C# Coding Interview Questions (With Solutions)




 1. Reverse a String Without Built-in Methods

Q: Write a C# method to reverse a string without using built-in reverse functions.

A:

string Reverse(string input) {
    char[] result = new char[input.Length];
    for (int i = 0; i < input.Length; i++)
        result[i] = input[input.Length - 1 - i];
    return new string(result);
}

2. Find Duplicates in an Integer Array

Q: Detect and print duplicates in an integer array.

A:

void FindDuplicates(int[] arr) {
    var seen = new HashSet<int>();
    foreach (int num in arr) {
        if (seen.Contains(num))
            Console.WriteLine("Duplicate: " + num);
        else
            seen.Add(num);
    }
}

3. Custom Sorting Logic using IComparer

Q: Sort a list in descending order with a custom comparer.

A:

class DescComparer : IComparer<int> {
    public int Compare(int x, int y) => y.CompareTo(x); // Descending
}
// Usage
var numbers = new List<int> { 5, 2, 9 };
numbers.Sort(new DescComparer());

4. Check if a Number is Prime

Q: Create a function to check for primality.

A:

bool IsPrime(int number) {
    if (number < 2) return false;
    for (int i = 2; i <= Math.Sqrt(number); i++)
        if (number % i == 0) return false;
    return true;
}

5. Find All Substrings of a String

Q: Print all possible substrings of a given input string.

A:

void FindAllSubstrings(string str) {
    for (int i = 0; i < str.Length; ++i) {
        var subStr = new StringBuilder();
        for (int j = i; j < str.Length; ++j) {
            subStr.Append(str[j]);
            Console.Write(subStr + " ");
        }
    }
}

6. Left Circular Rotation of an Array

Q: Rotate an array left by one position.

A:

void RotateLeft(int[] array) {
    int temp = array[^0];
    for (int i = 1; i < array.Length; i++)
        array[i - 1] = array[i];
    array[array.Length - 1] = temp;
}

7. Implement Insertion Sort

Write an insertion sort algorithm in C#.

void InsertionSort(int[] arr) {
    for (int i = 1; i < arr.Length; i++) {
        int key = arr[i], j = i - 1;
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
}

8. Write Binary Search

Efficiently search a sorted array for an item.

int BinarySearch(int[] arr, int key) {
    int low = 0, high = arr.Length - 1;
    while (low <= high) {
        int mid = (low + high) / 2;
        if (arr[mid] == key) return mid;
        if (arr[mid] < key) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}

9. Boxing and Unboxing

Q: Explain and demonstrate boxing/unboxing pitfalls.

A:

object obj = 123;
long l = (long)(int)obj; // Must unbox to the original type (int), then cast to long

10. Object Equality vs Reference Equality

Q: What does this print?

object a = 123; object b = 123; Console.WriteLine(a == b);

A: False — Reference equality for boxed values.

11. String Interning

Q: Does this print True?

string a = "hello";
string b = "he" + "llo";
Console.WriteLine(object.ReferenceEquals(a, b));

A: True — Compiler optimizes and interns string literals.

12. Second Largest in Array

Write code to find the second largest element in an array.

int SecondLargest(int[] arr) {
    int max = int.MinValue, second = int.MinValue;
    foreach (var num in arr) {
        if (num > max) { second = max; max = num; }
        else if (num > second && num != max) second = num;
    }
    return second;
}

13. Merge Two Arrays

Combine two arrays into one.

int[] MergeArrays(int[] a1, int[] a2) {
    return a1.Concat(a2).ToArray();
}

14. Common Elements in Two Arrays

Find common elements between two arrays.

var common = a1.Intersect(a2).ToArray();

15. Rotate an Array

Rotate an array by k positions.

void Rotate(int[] arr, int k) {
    k %= arr.Length;
    Array.Reverse(arr, 0, k);
    Array.Reverse(arr, k, arr.Length - k);
    Array.Reverse(arr, 0, arr.Length);
}

16. Implement a Custom Exception

Create and use a custom exception type.

class MyCustomException : Exception {
    public MyCustomException(string message) : base(message) { }
}

17. Abstract Class vs Interface

Explain and exemplify the difference.

A:

·        Abstract class can have implementation; interfaces cannot.

·        Abstract class can contain constructors; interfaces cannot.

18. Extension Methods

Add a method to an existing class.

public static class StringExtensions {
    public static bool IsPalindrome(this string str) {
        string rev = new string(str.Reverse().ToArray());
        return str.Equals(rev, StringComparison.OrdinalIgnoreCase);
    }
}

19. Delegates vs Interfaces

Explain delegates and how they're different from interfaces.

A: Delegates are type-safe function pointers mainly for event handling. Interfaces define a contract for implementations.

20. Yield Keyword

Describe the purpose of yield.

A: Yields each item on-the-fly; useful for deferred/lazy iteration.

21. Nullable Types & Null Coalescing

Show how to use ?? safely.

int? x = null;
int y = x ?? 5; // y = 5

22. Implicit & Explicit Conversion

Convert data types, showing pitfalls.

double d = 10.5;
int i = (int)d; // Outputs 10, not 11 (truncated)

23. String Concatenation with Nulls

Q: What does this print?

Console.WriteLine(((string)null + null + null) == "");

A: True — nulls are treated as empty strings in concatenation.

24. Find the Output: String Interning and Reference Equality

var x = "AB";
var y = new StringBuilder().Append('A').Append('B').ToString();
var z = string.Intern(y);
Console.WriteLine(x == y); // True
Console.WriteLine(x == z); // True
Console.WriteLine((object)x == (object)y); // False
Console.WriteLine((object)x == (object)z); // True

25. Sealed Classes

What does sealed keyword mean?

A: Prevents further inheritance or method overriding.

26. Profiling & Optimizing C# Apps

Q: How does profiling help performance?

A: Identifies hotspots for optimization and informs caching, lazy initialization, and effective resource use.

27. Caching in C#

Describe types of caching and their pros.

A: In-memory, distributed (e.g., Redis); improve access speed and scalability.

28. Exception Handling - Throw vs Throw ex

What is the difference?

·        throw preserves stack trace.

·        throw ex resets stack trace.

29. LINQ: IEnumerable vs IQueryable

Explain their difference.

·        IEnumerable: works with in-memory collections, client-side.

·        IQueryable: builds queries for external data sources, server-side, deferred execution.

30. What is the ‘using’ Statement For?

A: Ensures IDisposable objects are properly disposed (e.g., files, db connections) even in case of exception.

Comments

Popular posts from this blog

Ace Your .NET Core Coding Interview: Top 20 Algorithmic & Problem-Solving Questions

 Beyond knowing the ins and outs of .NET Core, a successful technical interview often hinges on your ability to solve fundamental coding problems. These questions test your logical thinking, algorithm design, and grasp of basic data structures. This blog post provides 20 essential coding interview questions, complete with explanations and example approaches in C#, to help you shine in your next .NET Core technical assessment. 1. Reverse a String Without Built-in Functions Explanation: A classic that tests your understanding of loops and string manipulation. Question: Write a C# method to reverse a given string without using built-in Reverse() or ToArray() methods. Answer: C# public string ReverseString ( string input ) { if ( string .IsNullOrEmpty(input)) { return input; } char [] charArray = input.ToCharArray(); int left = 0 ; int right = charArray.Length - 1 ; while (left < right) { // Swap characters char...

Cracking the Code: Your Guide to the Top 60 C# Interview Questions

So, you're gearing up for a C# interview? Fantastic! This powerful and versatile language is a cornerstone of modern software development, and landing that C# role can open up a world of exciting opportunities. But navigating the interview process can feel like traversing a complex codebase. Fear not! We've compiled a comprehensive list of the top 60 C# interview questions, complete with detailed answers, to help you ace your next technical challenge. Whether you're just starting your C# journey or you're a seasoned pro looking to brush up your knowledge, this guide has something for you. We've broken down the questions into three levels: Beginner, Intermediate, and Advanced, allowing you to focus on the areas most relevant to your experience. Let's dive in and equip you with the knowledge you need to shine! Beginner Level (1–20) 1. What is C#? C# is a modern, object-oriented programming language developed by Microsoft as part of its .NET platform. It is design...