30 C# Coding Interview Questions for Beginner, Mid-Level and Expert Developers

c# coding interview questions

C# is one of the leading programming languages from Microsoft. It is used not only in web applications but also for desktop and mobile applications. Since 2014, when it became open source, and after the arrival of .NET core 7, it has been gaining popularity and wide adoption by developers. 

Today’s article will present different coding challenges to evaluate C# developers. These coding challenges are divided into three categories, namely beginner, mid-level and expert programmers. Let’s start with the coding challenges for beginners.

C# Coding Interview Questions for Beginners

Developer Skill Assessment Tool

Junior C# developers should have a strong grip on the basic concepts of the language and .NET framework. When designing coding challenges for junior developers, create questions around language syntax, object-oriented programming, CLR, data structure and collection types, error handling, async and await and asynchronous programming. Here are 10 sample questions in this regard:

Question 1

What will be the output of the below code in a Unix-based system:

using System;
using System.Runtime.InteropServices;
 [DllImport("libc", SetLastError = true)]
private static extern int getpid();
 public static void Main()
{
	int processId = getpid();
    Console.WriteLine($"Process ID: {processId}");
}

Question 2

Guess the output of the below code:

 using System;
 public static void Main()
{
	var coordinates = GetCoordinates();
	(double latitude, double longitude) = coordinates;
    Console.WriteLine($"Latitude: {latitude}, Longitude: {longitude}");
 
	(double, double) GetCoordinates()
	{
    	return (12.34, 56.78);
	}
}

Question 3

What is the issue with the use of HttpClient in the below code:

using System;
using System.Net.Http;
using System.Threading.Tasks;
 
public static async Task Main()
{
	string url = "https://api.example.com/data";
	Console.WriteLine(await GetDataAsync(url));
}
 
public static async Task<string> GetDataAsync(string url)
{
	using HttpClient httpClient = new HttpClient();
	HttpResponseMessage response = await httpClient.GetAsync(url);
	return await response.Content.ReadAsStringAsync();
}

Question 4

Design a basic bank account management system having the below features:

  • Create an account
  • Deposit money
  • Withdraw money
  • Display current account balance

Implement a simple console application that shows the use of the bank account management system.

Question 5

What will be the output of the below code snippet:

using System;
using System.Collections.Generic;
 Dictionary<string, int> dict = new() { ["one"] = 1, ["two"] = 2, ["three"] = 3 };
Console.WriteLine(dict["two"]);

Question 6

Will the below code throw any error? If yes, identify the error.

 using System;
 string input = Console.ReadLine();
int? number = int.TryParse(input, out int result) ? result : null;
Console.WriteLine(number);

Question 7

Implement a program that counts the number of vowels in a given string. The program should ask the user to input a string and then display the number of vowels in the string. Make sure that the program is case-sensitive.

Question 8

Analyze the below code and suggest the output:

 using System;
 object number = 42;
string message = number switch
{
	int i when i > 0 => "Positive",
	int i when i < 0 => "Negative",
	int i => "Zero",
	_ => "Not a number"
};
 
Console.WriteLine(message);

Question 9

Find the issue with the below code snippet:

abstract class Animal
{
	public abstract Animal Clone();
}
 class Cat : Animal
{
	public override Cat Clone()
	{
    	return new Cat();
	}
}

Question 10

What issue exists in the below code:

using System;
 int number = int.Parse(Console.ReadLine());
string message = number switch
{
	> 0 and <= 10 => "Number is between 1 and 10",
	> 10 or < 0 => "Number is greater than 10 or negative",
	_ => "Number is 0"
};
 
Console.WriteLine(message);

C# Coding Interview Questions for Mid-level Engineers

When designing interview questions for mid-level C# developers, you should prepare challenges keeping in mind the understanding of advanced C# concepts, strong analytical capabilities and design patterns. Some areas that should be evaluated include dependency Injection (DI) and Inversion of Control (IoC), SOLID principles, new features of C#11 and .NET 6, ASP Core, Entity framework core, CI/CD and performance tuning. Find below 10 coding challenges which are suited to mid-level C# developers:

Question 1

What is the issue in the below code:

 public interface IProcessor
{
	void Process();
}
 public class TextProcessor : IProcessor
{
	public void Process() { /*...*/ }
}
 public static void InvokeProcessor(IProcessor processor)
{
    processor.Process();
}
 public static void Main()
{
    InvokeProcessor(new());
}

Question 2

What will be the output of the below code:

record Point(int X, int Y);
 var original = new Point(1, 2);
var shifted = original with { X = original.X + 3, Y = original.Y - 1 };
Console.WriteLine(shifted);

Question 3

Develop a banking system with classes representing accounts, transactions and customers. Use init-only properties to make sure that instances of these classes are immutable once they are created.

Question 4

Implement an application that uses target-typed new expressions to create instances of various classes, like repositories, services and DTOs. Design the classes so that they can be easily created using target-typed new expressions.

Question 5

What is the issue in the below code:

public class Employee
{
	public string Name { get; init; }
	public int Age { get; init; }
}
 public static void Main()
{
	Employee employee = new Employee { Name = "John collen", Age = 45 };
	employee.Age = 45;
}

Question 6

What will be the output of below code snippet:

using System;
 int Add(int a, int b) => a + b;
int Subtract(int a, int b) => a - b;
 
Console.WriteLine(Add(3, 4));
Console.WriteLine(Subtract(7, 2));

Question 7

The below code will throw an error. Can you spot that error?

public static int MultiplyByFactor(int value)
{
	int factor = 2;
 	int Multiply(int x) => x * factor;
 	if (value > 10)
	{
    	int factor = 3;
	}
 	return Multiply(value);
}
 public static void Main()
{
	Console.WriteLine(MultiplyByFactor(5));
	Console.WriteLine(MultiplyByFactor(15));
}

Question 8

Implement a simple application that manages a list of users and their contact information. Use nullable reference types to ensure that the code handles null values correctly and minimize the risk of null reference exceptions.

Question 9

What is wrong with the below code:

public class User
{
	public string? FirstName { get; set; }
	public string? LastName { get; set; }
 	public string GetFullName()
	{
    	return (FirstName, LastName) switch
    	{
        	(string first, string last) => $"{first} {last}",
        	(string first, null) => first,
        	(null, string last) => last,
        	(null, null) => "Unknown"
    	};

Question 10

Develop a simple web application that uses the minimal APIs feature in ASP.NET Core to expose a RESTful API for managing a list of items, like books or movies. Implement CRUD operations using the new minimal APIs feature.

C# Coding Interview Questions for Expert Developers

When preparing coding challenges for expert-level C# engineers, you should test the advanced features of the language and framework, architecture, CI/CD, cloud services, performance optimization and unit testing. Some of the areas to evaluate include advanced language features, advanced .NET core and ASP.NET core features, advanced entity framework core, performance and diagnostics, design patterns, cloud and microservices. Below we have presented 10 coding challenges for expert C# developers:

Question 1

Is there any security vulnerability in the below code? If yes, identify it and suggest a secure implementation:

using System;
using System.Data.SqlClient;
 public static void Main()
{
	string username = "allen'; DROP TABLE users; --";
	string password = "mypassword";
	GetUser(username, password);
}
 
public static void GetUser(string username, string password)
{
	using (SqlConnection connection = new SqlConnection("your_connection_string"))
	{
    	connection.Open();
 
    	string query = $"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'";
    	using (SqlCommand command = new SqlCommand(query, connection))
    	{
        	SqlDataReader reader = command.ExecuteReader();
        	// ... Process the result
    	}
	}
}

Question 2

Identify the output of the below code.

using System;
using System.Runtime.InteropServices;
 delegate int MyDelegate(int a, int b);
 [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
 
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr LoadLibrary(string fileName);
 private static MyDelegate GetFunctionPointer(string library, string function)
{
	IntPtr libHandle = LoadLibrary(library);
	IntPtr funcPtr = GetProcAddress(libHandle, function);
	return Marshal.GetDelegateForFunctionPointer<MyDelegate>(funcPtr);
}
 public static void Main()
{
	MyDelegate myFunction = GetFunctionPointer("msvcrt.dll", "strcmp");
	int result = myFunction(10, 20);
	Console.WriteLine($"Result: {result}");
}

Question 3

What is the possible performance issue in the below code? Also, suggest how to improve it.

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
 
public static async Task Main()
{
	string[] urls = { "url1", "url2", "url3", "url4", "url5" };
	await DownloadFiles(urls);
}
 public static async Task DownloadFiles(string[] urls)
{
	HttpClient httpClient = new HttpClient();
 	foreach (string url in urls)
	{
    	using MemoryStream memoryStream = await httpClient.GetStreamAsync(url);
    	using FileStream fileStream = new FileStream(Path.GetFileName(url), FileMode.Create, FileAccess.Write);
    	await memoryStream.CopyToAsync(fileStream);
	}
}

Question 4

Suggest the output of the below code:

record Point(int X, int Y);
 public static void Main()
{
	object shape = new Point(3, 4);
    Console.WriteLine(GetSum(shape));
}
 static int GetSum(object obj)
{
	return obj switch
	{
    	Point (var x, var y) => x + y,
    	_ => 0
	};
}

Question 5

Using C# and Entity Framework Core, implement a simple caching strategy for a database query that is frequently executed. The caching strategy should store the results of a query in memory and return the cached data if it is available and not expired. If the cache is expired or unavailable, the implementation should execute the query against the database and update the response in the cache.

Question 6

What is wrong with the below code?

public interface ILogger
{
	void Log(string message);
	void LogError(string message) => Log($"Error: {message}");
}
 public class ConsoleLogger : ILogger
{
	public void Log(string message)
	{
        Console.WriteLine(message);
	}
}
 public static void Main()
{
	ILogger logger = new ConsoleLogger();
	logger.LogError("An error occurred.");
}

Question 7

What will be the output of below code snippet?

public class Product
{
	public string Name { get; init; }
	public decimal Price { get; init; }
}
 
public static void Main()
{
	Product product = new Product { Name = "Bowl", Price = 1.99m };
	//product.Name = "New Bowl"; // This line is commented
    Console.WriteLine(product.Name);
}

Question 8

Using C# and SignalR, develop a real-time chat application. This chat application will allow multiple users to send and receive messages in a chat room. Users should be able to join and leave the chat room. Also, their messages should be broadcast to all connected users in real time.

Question 9

What is wrong with the below code?

 public static void Main()
{
	int x = 5;
	int y = 10;
	int result = Add(x, y);
	Console.WriteLine(result);
 
	static int Add(int a, int b)
	{
    	return a + b + x;
	}
}

Question 10

Using C# and ASP.NET Core, implement a custom authentication middleware that checks for a specific token in the request header. If the token is found and it is valid, the middleware should allow the request to proceed. In case the token is missing or invalid, the middleware should return a 401 Unauthorized status.

Conclusion

This article has provided a collection of C# coding challenges appropriate for novice, intermediate and expert developers. These challenges cover a wide variety of areas and concepts, catering to programmers of varying experience levels and allowing recruiters to test C# and .NET skills in candidates.

Test assessment tool

Further reading: