C# Coding Interview Questions

C# Coding Interview Questions

Due to some advancement in the .net framework,  Anders Hejlsberg designs a Language that took the good sides of C++ and C. This programming language is what we have today as C# (https://en.wikipedia.org/wiki/C_Sharp_(programming_language). This happened from 1999 through 2003 when ISO first accepted C#. Since then, the popularity has highly increased. It is hard to randomly point to 5 companies in the top 50 American companies that do not use C#. Yes, there is a high demand for c# developers out there. We will discuss C# Coding Interview Questions here.

C# Coding Interview Questions

In this article, I will be discussing (asking and answering) technical questions that can qualify a candidate fit for a position in a firm coding with c#. The questions will not be specific to a specific level of expertise. It will rather test a candidate’s qualification in terms of general c# coding knowledge.

  • In an attempt to describe Dependency Injection (DI) tell us why it is of importance?

ANSWER: In modern development architectures(the onions architecture being an example), separations of concerts have been a trend to follow, not only because it promised lesser debug time and less-buggy codes, but because it allows easy testing of codes. It also allows for very clean codes to be archived. And also, one other advantage I appreciate is the fact that code reuse is much easier when the codes are well abstracted. You know that what you called affects only this and nothing else.

You try so hard to keep your consuming class ignorance of the class it is calling. The man who is served coffee should never be aware of how the coffee was made. He should trust that the coffee is well made. And the person who is making the coffee should not be aware of who is taking it.

A solid way to archive this is by using Dependency Injection.  According to (Dependency injection – Wikipedia), dependency injection is how an object obtains other objects that it depends on.  There are 3 types of dependency injection. These are 

  • Constructor Dependency
  • Property Dependency
  • Method Dependency
  • Write a program that collects a distance in kilometers, converts it to, meter, then multiplies it by 3 before displaying the result.

ANSWER:

static void Main(string[] args)

{

         decimal distance, result;

           Console.Write(“Insert your distanve in Kilometers: “);

            distance = Convert.ToDecimal(Console.Read());

            result = 3 * (distance * 1000);

       Console.WriteLine($”The distance of: {distance}KM, when converted to Meters (M) and multiplied by 3 is :{result}M”);

 }        

  • What will the following code output on the console?

static void Main(string[] args)

            {

                try

                {

                    Console.WriteLine(“Any Problem: “);

                }

                catch (ArgumentNullException)

                {

                    Console.WriteLine(“Yes, a known problem”);

                }

                catch (Exception)

                {

                    Console.WriteLine(“Yes, an unknown problem”);

                }

                finally

                {

                    Console.WriteLine(“No Problem”);

                }

                Console.ReadKey();

            }

ANSWER: Any Problem: No Problem

  • What is the purpose and effect of the bellow program?

        static long TotalMod2Numbers(int[] numsArray)

        {

            return numsArray.Where(j =>ji % 2 == 0).Sum(j => (long)j);

        }

ANSWER: The above code is a one-liner code that will take an input of an integer array, filter it to collect only the even numbers, stores it in a variable called j, and then the Sum(j => (long)j)  part sums the filtered inputs and then converts it to long.

  • What output will the following code give and why?

static void Main(string[] args) {

            string[] strings = { “abc”, “def”, “ghi” };

            var actions = new List<string>();

            foreach (string str in strings)

                actions.Add(str);

            actions.Reverse();

            foreach (var action in actions)

                Console.WriteLine(action);

        }

ANSWER: The following code takes an array of strings(“abc” “def” “ghi” ), passes the value to a list called “action,” which is a list of strings. The program then reverses the supposed “abc def ghi” (Each in a different line) output. Putting ghi first, then, def next, then abc last. The action.Reverse(); is responsible for the reverse effect.

  • Will an expression such as if(datetime == null) {//do logic}  if datetime is a variable of type  static datetime.

ANSWER: The DateTime cannot be null because it automatically initiates to its default value which is Jan 1, 0001. And there would be an error comparing DateTime to null.

However, this would not be the case. Due to coercion (or implicit casting), this is made possible. The ‘==’ operation does an implicit casting on the DateTime variable, and good enough, both the null literal and the DateTime variable can be converted(cast) to Nullable<DateTime> type. Programs lines like this should be avoided, except the outcome is strongly known. The Outcome of the following program will always be false, even if the variable DateTime was initialized or not.

  • What is Marshaling and why is it important?

ANSWER: There is a demarcation between managed and unmanaged resources in a codebase. This is mostly because of how different environments and languages handle resources or objects. There however, needs to be a way to make resources from both the managed environments and the unmanaged environments understand and communicate with each other. Resources that the Common Language Runtime (CLR) has control over are usually termed Managed. This is what Marshaling does. It is a jobber responsible for the interfacing between managed and unmanaged resources, making for a smooth relationship between them.

  • What is the difference between Early Binding and Late Binding?

ANSWER: Early binding means that the targeted function is found and known at compile-time, and late binding, also known as dynamic binding, means that the compiler does not know the type of objects or methods it is holding until runtime. When the dynamic keyword is used as a data type, the type of the variable used will only be known at runtime, which is a good example of late binding.

  • What are the differences between out and res keywords in c#?

ANSWER: When out is used, the parameter passed MUST be modified by the method. But when the ref is used, the parameter modification by the method is OPTIONAL. When a parameter is passed using ref, it is compulsory to initialize that parameter. Meanwhile, an empty parameter can be passed using the out keyword.

  • How do async/ await work in .net explain using a code sample.

ANSWER: In most cases, functions calling other functions for value don’t immediately use the value is called. Imagine the whole operation and compilation processes waiting for a result it is yet to require. The async keyword is used to indicate that a method is asynchronous. By asynchronous, I mean the method can run in the background, not stopping the entire method’s execution and only giving out its results when needed. The await keyword indicates to the program that its result or results are needed. Thereby causing a wait for the result. It is most useful for saving time in an application’s execution time. It is also useful for making interactive application UIs.

In the below code, The value of the ‘DownloadDocsPageAsync’ method’s result is not determined when it was called to be assigned to the variable fetching. Its value comes when the await keyword is being called on the fetching variable. This suspended execution is caused by the async. 

using System;

using System.Net.Http;

using System.Threading.Tasks;

public class AwaitOperator {

        public static async Task Main()

        {

            Task<int> fetching= DownloadDocsPageAsync();

            Console.WriteLine($”{nameof(Main)}: Launched downloading.”);

            int bytesLoaded = await fetching;

            Console.WriteLine($”{nameof(Main)}: Downloaded {bytesLoaded} bytes.”);

        }

        private static async Task<int> DownloadDocsPageAsync()

        {

            Console.WriteLine($”{nameof(DownloadDocsPageAsync)}: About to begin downloading.”);

            var client = new HttpClient();

            byte[] content = await client.GetByteArrayAsync(“https://docs.microsoft.com/en-us/”);

            Console.WriteLine($”{nameof(DownloadDocsPageAsync)}: Finished downloading.”);

            return content.Length;

        }

    }

  • What is LINQ in C#?

ANSWER: Back in the days, c# developers also had to know SQL. This was just a requirement to retrieve or manipulate data in a relational database management system. They had to acquire other skills in other to manipulate data in other data sources like XML ADO.net data source etc. 

LINQ means Language Integrated Query. It is a unified query syntax with C#. Now, LINQ is all you need to know to query data from any available data source as far as the source implements IQuueryable. Although it came with new syntaxes, the learning curve was low, especially because it is still the old familiar c#.

  • What is the difference between abstract methods and virtual methods?

ANSWER: According to Microsoft Docs, when the virtual keyword is used on an event, method, property, or indexer, it means that the method can be overwritten by whichever class inherits it.

According to Microsoft Doc, when an abstract reference is being used on a method, it indicated that the method has no implementation or is incomplete.

Virtual MethodsAbstract Methods
1.Abstract methods can only be found in abstract classes,Virtual methods can be found both in abstract and non-abstract classes.
2.Overriding abstract classes are not optional, but a mustIt is optional to override virtual methods, except they are in abstract classes.
3.Abstract methods have no bodies or implementationsVirtual methods have implementations

Also read Sell me this Pen: Best Ways to Answer the Interview Question

C# Coding Interview Questions

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top