C# .NET interview questions

C# .NET quiz questions

  • 1.

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

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

    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.

    View
  • 2.

    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?

    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.

    View
  • 3.

    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.

    Answer:

    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.

    View
  • 4.

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

    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.

    View
  • 5.

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

    Answer:

    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.

    View
  • 6.

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

    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.
    View
  • 7.

    What is a Destructor in C# ? 

    Answer:

    Destructor is a special method that get invoked/called automatically whenever an object of a given class gets destroyed. Main idea behind using destructor is to free the memory used by the object.

    View
  • 8.

    What is a Constructor in C# ?

    Answer:

    Constructor is a special method that get invoked/called automatically, whenever an object of a given class gets instantiated. In our class car, constructor is defined as shown below

    public Car()
    {
     Console.WriteLine("Base Class Car");
    }
    

    When ever an instance of class car is created from the same class or its derived class(Except Few Scenarios), Constructor get called and sequence of code written in the constructor get executed.

    interface Breaks
    {
     void BreakType();
    }
    interface Wheels
    {
     void WheelType();
    }
    class Ford : Breaks, Wheels
    {
     public Ford()
     {
      Console.WriteLine("Derived Class Ford");
     }
     public void Price()
     {
      Console.WriteLine("Ford Price : 100K $");
     }
     public void BreakType()
     {
      Console.WriteLine("Power Break");
     }
     public void WheelType()
     {
      Console.WriteLine("Bridgestone");
     }
    }
    View
  • 9.

    What is an Interface in C# ?

    Answer:

    An interface is similar to a class with method signatures. There wont be any implementation of the methods in an Interface. Classes which implement interface should have an implementation of methods defined in the abstract class.

    View
  • 10.

    What is Sealed Classes in c# ?

    Answer:

    If a class is defined as Sealed, it cannot be inherited in derived class. Example of a sealed class is given below.

    public sealed class Car
    {
     public Car()
     {
      Console.WriteLine("Base Class Car");
     }
     public void DriveType()
     {
      Console.WriteLine("Right Hand ");
     }
    } 
    View
  • 11.

    What is Abstract Class in C#?

    Answer:

    If we don't want a class to be instantiated, define the class as abstract. An abstract class can have abstract and non abstract classes. If a method is defined as abstract, it must be implemented in derived class. For example, in the classes given below, method DriveType is defined as abstract. 

    abstract class Car
    {
     public Car()
     {
      Console.WriteLine("Base Class Car");
     }
     public abstract void DriveType();
    }
    class Ford : Car
    {
     public void DriveType()
     {
      Console.WriteLine("Right Hand ");
     }
    }
    

    Method DriveType get implemented in derived class.

    View
  • 12.

    What is Method Hiding in C# ?

    Answer:

    If the derived class doesn't want to use methods in the base class, derived class can implement it's own version of the same method with same signature. For example, in the classes given below, DriveType() is implemented in the derived class with same signature. This is called Method Hiding.

    class Car
    {
     public void DriveType()
     {
      Console.WriteLine("Right Hand Drive");
     }
    }
    class Ford : Car
    {
     public void DriveType()
     {
      Console.WriteLine("Right Hand ");
     }
    }
    View
  • 13.

    What is overriding in c# ?

    Answer:

    To override a base class method which is defined as virtual, Override keyword is used. In the above example, method DriveType is overridden in the derived class.

    View
  • 14.

    Explain the use of Virtual Keyword in C# ?

    Answer:

    When we want to give permission to a derived class to override a method in base class, Virtual keyword is used. For example. lets us look at the classes Car and Ford as shown below.

    class Car
    {
     public Car()
     {
      Console.WriteLine("Base Class Car");
     }
     public virtual void DriveType()
     {
      Console.WriteLine("Right Hand Drive");
     }
    }
    class Ford : Car
    {
     public Ford()
     {
      Console.WriteLine("Derived Class Ford");
     }
     public void Price()
     {
      Console.WriteLine("Ford Price : 100K $");
     }
     public override void DriveType()
     {
      Console.WriteLine("Right Hand ");
     }
    }
    

    When following lines of code get executed 

    Car CarFord = new Car();
    CarFord.DriveType();
    CarFord = new Ford();
    CarFord.DriveType();
    

    Output is as given below.

    Base Class Car
    Right Hand Drive
    Base Class Car
    Derived Class Ford
    Right Hand
    View
  • 15.

    What is Polymorphism in C# ?

    Answer:

    The ability of a programming language to process objects in different ways depending on their data type or class is known as Polymorphism. There are two types of polymorphism

    • Compile time polymorphism. Best example is Overloading
    • Runtime polymorphism. Best example is Overriding
    View
  • 16.

    Can Multiple Inheritance implemented in C# ?

    Answer:

    In C#, derived classes can inherit from one base class only. If you want to inherit from multiple base classes, use interface.

    View
  • 17.

    Explain Inheritance in C# ?

    Answer:

    In object-oriented programming (OOP), inheritance is a way to reuse code of existing objects. In inheritance, there will be two classes - base class and derived classes. A class can inherit attributes and methods from existing class called base class or parent class. The class which inherits from a base class is called derived classes or child class. For more clarity on this topic, let us have a look at 2 classes shown below. Here Class Car is Base Class and Class Ford is derived class.

    class Car
    {
     public Car()
     {
      Console.WriteLine("Base Class Car");
     }
     public void DriveType()
     {
      Console.WriteLine("Right Hand Drive");
     }
    }
    class Ford : Car
    {
     public Ford()
     {
      Console.WriteLine("Derived Class Ford");
     }
     public void Price()
     {
      Console.WriteLine("Ford Price : 100K $");
     }
    }
    

    When we execute following lines of code ,

    Ford CarFord = new Ford();
    CarFord.DriveType();
    CarFord.Price();
    

    Output Generated is as given below.

    Base Class Car
    Derived Class Ford
    Right Hand Drive
    Ford Price : 100K $
    

    What this means is that, all the methods and attributes of Base Class car are available in Derived Class Ford. When an object of class Ford is created, constructors of the Base and Derived class get invoked. Even though there is no method called DriveType() in Class Ford, we are able to invoke the method because of inheriting Base Class methods to derived class.

    View
  • 18.

    What is Data Encapsulation ?

    Answer:

    Data Encapsulation is defined as the process of hiding the important fields from the end user. In the above example, we had used getters and setters to set value for MinSalary. The idea behind this is that, private field “minimumSalary” is an important part of our classes. So if we give a third party code to have complete control over the field without any validation, it can adversely affect the functionality. This is inline with the OOPS Concept that an external user should know about the what an object does. How it does it, should be decided by the program. So if a user set a negative value for MinSalary, we can put a validation in the set method to avoid negative values as shown below

     

    set
    {
     if(value > 0)
     {
      minSalary = value;
     }
    }
    
    View
  • 19.

    What is Operator Overloading in C# .net ?

    Answer:

    We had seen function overloading in the previous example. For operator Overloading, we will have a look at the example given below. We had defined a class rectangle with two operator overloading methods.

    class Rectangle
    {
     private int Height;
     private int Width;
     public Rectangle(int w,int h)
     {
       Width=w;
       Height=h;
     } 
     public static bool operator >(Rectangle a,Rectangle b)
     {
       return a.Height > b.Height ;
     }
     public static bool operator <(Rectangle a,Rectangle b)
     {
       return a.Height < b.Height ;
     } 
    }
    

    Let us call the operator overloaded functions from the method given below. When first if condition is triggered, the first overloaded function in the rectangle class will be triggered. When second if condition is triggered, the second overloaded function in the rectangle class will be triggered. 

    public static void Main()
    {
    Rectangle obj1 =new Rectangle();
    Rectangle obj2 =new Rectangle();
     if(obj1 > obj2)
     {
      Console.WriteLine("Rectangle1 is greater than Rectangle2");
     } 
     if(obj1 < obj2)
     {
      Console.WriteLine("Rectangle1 is less than Rectangle2");
     }
    }
    View
  • 20.

    What is Function Overloading in C# .net ?

    Answer:

    In Function overloading, n number of functions can be created for the same class. But the signatures of each function should vary. For example

    public class Employee 
    {
     public void Employee() 
     { }
     public void Employee(String Name) 
     { }
    }
    View

© 2017 QuizBucket.org