6 Essential C# Interview Questions*

Given an array of ints, write a C# method to total all the values that are even numbers.

There are of course many ways to do this, but two of the most straightforward would be either:

static long TotalAllEvenNumbers(int[] intArray) {
  return intArray.Where(i => i % 2 == 0).Sum(i => (long)i);
}

or:

static long TotalAllEvenNumbers(int[] intArray) {
  return (from i in intArray where i % 2 == 0 select (long)i).Sum();
}

Here are the key things to look for in the answer:

  1. Does the candidate take advantage of the C# language constructs which make a one-liner solution possible (i.e., rather than employing a more lengthy solution which contains a loop, conditional statement, and accumulator)?
  2. Does the candidate consider the possibility of overflow. For example, an implementation such as return intArray.Where(i => i % 2 == 0).Sum() (regardless of the return type of the function) might be an “obvious” one-line solution, but the probability of overflow here is high. While the approach used in the answers above of converting to long doesn’t eliminate the possibility, it makes it a highly unlikely that an overflow exception will occur. Note that, if the candidate asks about the expected size of the array and the magnitude of its members, he or she is obviously considering this overflow issue, which is part of what we’re looking to ascertain.
Fields marked with an asterisk (*) are required
Comment submitted succesfully. Thank you.
We are going to review the comment and get back to you as soon as possible.

What is the output of the short program below? Explain your answer.

class Program {
  static String location;
  static DateTime time;
 
  static void Main() {
    Console.WriteLine(location == null ? "location is null" : location);
    Console.WriteLine(time == null ? "time is null" : time.ToString());
  }
}

The output will be:

location is null
1/1/0001 12:00:00 AM

Although both variables are uninitialized, String is a reference type and DateTime is a value type. As a value type, an unitialized DateTime variable is set to a default value of midnight of 1/1/1 (yup, that’s the year 1 A.D.), not null.

Fields marked with an asterisk (*) are required
Comment submitted succesfully. Thank you.
We are going to review the comment and get back to you as soon as possible.

Is the comparison of time and null in the if statement below valid or not? Why or why not?

static DateTime time;
/* ... */
if (time == null)
{
	/* do something */
}

One might think that, since a DateTime variable can never be null (it is automatically initialized to Jan 1, 0001), the compiler would complain when a DateTime variable is compared to null. However, due to type coercion, the compiler does allow it, which can potentially lead to headfakes and pull-out-your-hair bugs.

Specifically, the == operator will cast its operands to different allowable types in order to get a common type on both sides, which it can then compare. That is why something like this will give you the result you expect (as opposed to failing or behaving unexpectedly because the operands are of different types):

double x = 5.0;
int y = 5;
Console.WriteLine(x == y);  // outputs true

However, this can sometimes result in unexpected behavior, as is the case with the comparison of a DateTime variable and null. In such a case, both the DateTime variable and the null literal can be cast to Nullable<DateTime>. Therefore it is legal to compare the two values, even though the result will always be false.

Fields marked with an asterisk (*) are required
Comment submitted succesfully. Thank you.
We are going to review the comment and get back to you as soon as possible.

Given an instance circle of the following class:

public sealed class Circle {
  private double radius;
  
  public double Calculate(Func<double, double> op) {
    return op(radius);
  }
}

write code to calculate the circumference of the circle, without modifying the Circle class itself.

The preferred answer would be of the form:

circle.Calculate(r => 2 * Math.PI * r);

Since we don’t have access to the private radius field of the object, we tell the object itself to calculate the circumference, by passing it the calculation function inline.

A lot of C# programmers shy away from (or don’t understand) function-valued parameters. While in this case the example is a little contrived, the purpose is to see if the applicant understands how to formulate a call to Calculate which matches the method’s definition.

Alternatively, a valid (though less elegant) solution would be to retrieve the radius value itself from the object and then perform the calculation with the result:

var radius = circle.Calculate(r => r);
var circumference = 2 * Math.PI * radius;

Either way works. The main thing we’re looking for here is to see that the candidate is familiar with, and understands how to invoke, the Calculate method.

Fields marked with an asterisk (*) are required
Comment submitted succesfully. Thank you.
We are going to review the comment and get back to you as soon as possible.

What is the output of the program below? Explain your answer.

class Program {
  private static string result;
 
  static void Main() {
    SaySomething();
    Console.WriteLine(result);
  }
 
  static async Task<string> SaySomething() {
    await Task.Delay(5);
    result = "Hello world!";
    return “Something”;
  }
}

Also, would the answer change if we were to replace await Task.Delay(5); with Thread.Sleep(5)? Why or why not?

The answer to the first part of the question (i.e., the version of the code with await Task.Delay(5);) is that the program will just output a blank line (not “Hello world!”). This is because result will still be uninitialized when Console.WriteLine is called.

Most procedural and object-oriented programmers expect a function to execute from beginning to end, or to a return statement, before returning to the calling function. This is not the case with C# async functions. They only execute up until the first await statement, then return to the caller. The function called by await (in this case Task.Delay) is executed asynchronously, and the line after the await statement isn’t signaled to execute until Task.Delay completes (in 5 milliseconds). However, within that time, control has already returned to the caller, which executes the Console.WriteLine statement on a string that hasn’t yet been initialized.

Calling await Task.Delay(5) lets the current thread continue what it is doing, and if it’s done (pending any awaits), returns it to the thread pool. This is the primary benefit of the async/await mechanism. It allows the CLR to service more requests with less threads in the thread pool.

Asynchronous programming has become a lot more common, with the prevalence of devices which perform over-the-network service requests or database requests for many activities. C# has some excellent programming constructs which greatly ease the task of programming asynchronous methods, and a programmer who is aware of them will produce better programs.

With regard to the second part of the question, if await Task.Delay(5); was replaced with Thread.Sleep(5), the program would output Hello world!. An async method without at least one await statement in it operates just like a synchronous method; that is, it will execute from beginning to end, or until it encounters a return statement. Calling Thread.Sleep() simply blocks the currently running thread, so the Thread.Sleep(5) call just adds 5 milliseconds to the execution time of the SaySomething() method.

Fields marked with an asterisk (*) are required
Comment submitted succesfully. Thank you.
We are going to review the comment and get back to you as soon as possible.

What is the output of the program below? Explain your answer.

delegate void Printer();

static void Main()
{
      List printers = new List();
      for (int i = 0; i < 10; i++)
      {
           printers.Add(delegate { Console.WriteLine(i); });
      }

      foreach (var printer in printers)
      {
           printer();
      }
}

This program will output the number 10 ten times.

Here’s why: The delegate is added in the for loop and “reference” (or perhaps “pointer” would be a better choice of words) to i is stored, rather than the value itself. Therefore, after we exit the loop, the variable i has been set to 10, so by the time each delegate is invoked, the value passed to all of them is 10.

Fields marked with an asterisk (*) are required
Comment submitted succesfully. Thank you.
We are going to review the comment and get back to you as soon as possible.
* There is more to interviewing than tricky technical questions, so these are intended merely as a guide. Not every “A” candidate worth hiring will be able to answer them all, nor does answering them all guarantee an “A” candidate. At the end of the day, hiring remains an art, a science — and a lot of work.
Submit an interview question
Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Toptal, LLC.
All fields are required
Thanks for submitting your question.
Our editorial staff will review it shortly. Please note that submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Toptal, LLC.
Patrick Ryder
United States
Pat has over a dozen years of experience developing applications on the .NET platform, including having been part of the development team at Microsoft which created the platform itself. He also develops for Windows native API (Win32/COM), he communicates extremely well, and he has worked in teams of all sizes.
Victor Bueno
United Kingdom
Victor is a seasoned .NET developer with over 17 years of experience focusing on the Microsoft technology stack. He develops a wide range of software, including web apps, back-end services, databases, and mobile apps. He is particularly interested in high-performance multi-threaded development.
Konstantin Startsev
Russia
Konstantin has 9+ years of software engineering experience, including a number of great jobs working with big companies and many jobs with start-up companies and medium-sized mobile and web agencies. Over last few years, he has been developing web solutions for the automation of business processes using C# and ASP.NET MVC or Java with Play! Framework and various front-end frameworks (e.g. jQuery, AngularJS, KnockoutJS, TypeScript etc.).
Alvaro 1506e7

Are you hiring C# developers? We'll find you a great freelance C# developer to join your team.

Alvaro Oliveira
VP of Talent Operations