Essential C# Interview Questions | Toptal® (2024)

Interview Questions

1

.

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()); }}

View answer

The output will be:

location is null1/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.

2

.

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

View answer

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.

3

.

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 */}

View answer

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.

Apply to Join Toptal's Development Network

and enjoy reliable, steady, remote Freelance C# DeveloperJobs

Apply as a Freelancer

4

.

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.

5

.

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?

View answer

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.

6

.

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

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

View answer

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.

7

.

It is possible to store mixed datatypes such as int, string, float, char all in one array?

View answer

Yes! It is possible to do so because the array can be of type object that can not only store any datatype but also the object of the class as shown below:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication8{ class Program { class Customer { public int ID { get; set; } public string Name { get; set; } public override string ToString() { return this.Name; } } static void Main(string[] args) { object[] array = new object[3]; array[0] = 101; array[1] = "C#"; Customer c = new Customer(); c.ID = 55; c.Name = "Manish"; array[2] = c; foreach (object obj in array) { Console.WriteLine(obj); } Console.ReadLine(); } }}

8

.

Compare structs and classes in C#. What do they have in common? How do they differ?

View answer

Classes and Structs in C# do have a few things in common, namely:

  • Are compound data types
  • Can contain methods and events
  • Can support interfaces

But there are a number of differences. Here’s a comparison:

Classes:

  • Support inheritance
  • Are reference (pointer) types
  • The reference can be null
  • Have memory overhead per new instance

Structs:

  • Do not support inheritance
  • Are value types
  • Are passed by value (like integers)
  • Cannot have a null reference (unless Nullable is used)
  • Do not have memory overhead per new instance (unless “boxed”)

9

.

What is the output of the program below?

public class TestStatic { public static int TestValue; public TestStatic() { if (TestValue == 0) { TestValue = 5; } } static TestStatic() { if (TestValue == 0) { TestValue = 10; } } public void Print() { if (TestValue == 5) { TestValue = 6; } Console.WriteLine("TestValue : " + TestValue); } } public void Main(string[] args) { TestStatic t = new TestStatic(); t.Print(); }

View answer

TestValue : 10

The static constructor of a class is called before any instance of the class is created. The static constructor called here initializes the TestValue variable first.

10

.

class ClassA{ public ClassA() { } public ClassA(int pValue) { }}

At the client side:

class Program{ static void Main(string[] args) { ClassA refA = new ClassA(); }}

Question:

Is there a way to modify ClassA so that you can you call the constructor with parameters, when the Main method is called, without creating any other new instances of the ClassA?

View answer

The this keyword is used to call other constructors, to initialize the class object. The following shows the implementation:

class ClassA{ public ClassA() : this(10) { } public ClassA(int pValue) { }}

11

.

What does the following code output?

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace main1{ class Program { static void Main(string[] args) { try { Console.WriteLine("Hello"); } catch (ArgumentNullException) { Console.WriteLine("A"); } catch (Exception) { Console.WriteLine("B"); } finally { Console.WriteLine("C"); } Console.ReadKey(); } }}

View answer

HelloC

12

.

Describe dependency injection.

View answer

Dependency injection is a way to de-couple tightly linked classes, thereby reducing the direct dependency of classes upon each other. There are different ways by which dependency injection can be achived:

  1. Constructor dependency
  2. Property dependency
  3. Method dependency

13

.

Write a C# program that accepts a distance in kilometers, converts it into meters, and then displays the result.

View answer

using system;class abc{ public static Void Main() { int ndistance, nresult; Console.WriteLine("Enter the distance in kilometers"); ndistance = convert.ToInt32(Console.ReadLine()); nresult = ndistance * 1000; Console.WriteLine("Distance in meters: " + nresult); Console.ReadLine(); }}

14

.

Describe boxing and unboxing. Provide an example.

View answer

Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by the value type. Boxing a value type creates an object instance containing the value and stores it on the heap.

Example:

int x = 101;object o = x; // boxing value of x into object oo = 999;x = (int)o; // unboxing value of o into integer x

15

.

You’re given a word string containing at least one $ symbol, e.g.:

"foo bar foo $ bar $ foo bar $ "

Question: How do you remove all but the first occurrence of $ from a given string?

View answer

This problem has two parts: Preserving the first occurrence and replacing all the others.

We can solve it using a regular expression and String.Replace():

using System;using System.Text.RegularExpressions;class MainClass { public static void Main (string[] args) { string s = "like for example $ you don't have $ network $ access"; Console.WriteLine("before: {0}", s); GroupCollection halves = Regex.Match(s, @"([^$]*\$)(.*)").Groups; string answer = halves[1].Value + halves[2].Value.Replace("$", ""); Console.WriteLine("after: {0}", answer); // like for example $ you don't have network access }}

Explanation:

  • ([^$]*\$)—Group 1 captures any number of non-$ characters, plus a single $ character (escaped with a \)
  • (.*)—Group 2 (greedily) captures everything else

With the first occurrence of $ preserved in halves[1].Value, we can simply use String.Replace() on halves[2].Value to eliminate all $ characters found in the remainder of the string, without the need for a second regular expression.

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 ofwork.

Essential C# Interview Questions | Toptal® (2024)

FAQs

How to prepare for a C# coding interview? ›

Basic C# Coding Concepts and Interview Q&As
  1. Object-Oriented Programming (OOP) Concepts. Question: How would you explain the concept of encapsulation in C#? ...
  2. Delegates and Events. ...
  3. Value Types vs. ...
  4. Exception Handling. ...
  5. LINQ (Language Integrated Query) ...
  6. Asynchronous Programming. ...
  7. Dependency Injection. ...
  8. Multithreading.
May 30, 2024

What is the best answers for interview questions? ›

You can structure your answer by following these three bullet points:
  • Review the job description for qualities that the employer finds valuable.
  • Incorporate ways you've been successful in your previous roles.
  • Highlight the traits or skills you've been praised for by former managers and colleagues.
May 28, 2024

How do I prepare for a .NET interview question? ›

.NET Interview Questions
  1. How does the .NET framework work?
  2. Explain about major components of the .NET framework.
  3. What is an EXE and a DLL?
  4. What is CTS?
  5. Explain CLS.
  6. What is JIT?
  7. What is the difference between int and Int32?
  8. Explain the differences between value type and reference type.
Jan 3, 2024

What questions are asked in a toptal interview? ›

Interview Questions
  • Tell us a bit about the latest project you worked on. ...
  • Talk about a time when you had to make a critical decision during production. ...
  • How would you explain APIs to non-technical stakeholders? ...
  • Here is a simple programming challenge. ...
  • What programming languages do you use?

Is C# coding hard? ›

The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.

Is C# for dummies good? ›

Reading "C# for Dummies" can certainly be a good first step in becoming a programmer in C#. It is a beginner-friendly book that can provide you with a solid foundation in the basics of C# programming.

What is the star method when interviewing? ›

The STAR method is a structured manner of responding to a behavioral-based interview question by discussing the specific situation, task, action, and result of the situation you are describing.

How do I say I don't know in an interview? ›

Know When to Say “I Don't Know”

You can use dialog such as “I haven't dealt with a situation like that before, but I would start by asking these questions.” You can also say “That concept or situation is new to me, I'll have to look into it.” Remember to be transparent with your knowledge.

How to ace an interview? ›

  1. Tell the truth. ...
  2. Listen carefully to the interviewer. ...
  3. Never slight a teacher, friend, employer, or your university. ...
  4. Watch your grammar. ...
  5. Be prepared for personal questions. ...
  6. Wait for the interviewer to mention salary and benefits. ...
  7. Don't expect a job offer at the first interview. ...
  8. Close on a positive, enthusiastic note.

Is C# and .NET the same? ›

NET is a framework that provides a runtime environment and libraries, while C# is a programming language primarily used for building applications within the . NET framework. Understanding their differences and relationship is essential for developers looking to leverage the power of these technologies effectively.

What is the .NET Framework in C#? ›

The .NET Framework is an open-source platform for developing Windows-based applications, often referred to as Microsoft .net. The .NET Framework includes a variety of developer tools and class libraries. The .NET Framework works with applications developed in C#, F#, Visual Basic, and other popular programming ...

How to explain .NET project in interview? ›

During the interview, be prepared to discuss the technical aspects of your . NET project. Explain the architecture, design patterns, and programming languages you employed. Highlight any challenging problems you solved and the innovative solutions you implemented.

Why should we hire you? ›

A: When answering, focus on your relevant skills, experience, and achievements that make you the best fit for the role.You should hire me because I am a hard worker who wants to help your company succeed. I have the skills and experience needed for the job, and I am eager to learn and grow with your team .

How to pass an algorithm interview? ›

How to answer algorithm interview questions
  1. Learn about data structures. ...
  2. Understand the problem. ...
  3. Talk through the brute-force solution. ...
  4. Optimize your solution. ...
  5. Code your solution. ...
  6. Debug your solution. ...
  7. Test your solution.

How much does Toptal pay per hour? ›

The average Toptal salary ranges from approximately $45,856 per year for Operations Coordinator to $167,107 per year for Partner. Average Toptal hourly pay ranges from approximately $19.90 per hour for Customer Service Representative to $24.25 per hour for Product Manager.

How should I prepare for coding interviews? ›

How to prepare for a coding interview
  1. Review common technical terms. Coding encompasses a wide variety of programming languages , and each has its own set of terms and processes. ...
  2. Research the company. ...
  3. Prepare to share your projects. ...
  4. Have a mock interview.
Jul 1, 2024

How can I be a good C# coder? ›

A C# programmer needs the ability to translate abstract concepts into working code. This means being able to take a problem and break it down into manageable pieces that can be coded. It also means being able to troubleshoot code when things go wrong.

Is it easy to code in C#? ›

C# is easy to learn

In addition to the time you can save during project development, you'll also spend less time learning C# as opposed to the more difficult programming languages out there. Thanks to its simplicity and easy-to-use features, C# offers a fairly low learning curve for beginners.

How to crack coding interviews easily? ›

How To Crack A Coding Interview?
  1. Review the job description. ...
  2. Research the organisation. ...
  3. Revise your resume. ...
  4. Research learning resources. ...
  5. Choose the programming language. ...
  6. Practice coding in writing. ...
  7. Learn to code for software and system designs. ...
  8. Review your work.
Sep 8, 2023

Top Articles
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 5911

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.