C# interview questions and answers

C# aka. "C sharp" is a programming language runs on the .NET Framework and used for building a variety of applications. C# is type-safe, powerful and object-oriented.

What is an object?

An object is an instance of a class using which we can access the properties, methods of that class. An object is created using "New" keyword. An object in memory contain the information about the methods, properties and behavior of that class.

What is Constructors?

Constructor is special method of the class which comes with same name as class.Constructor will be automatically invoked when an instance of the class is created. Constructors are mainly used to initialize private fields of the class while creating an instance for the class. If class does not contain a constructor, then compiler will automatically create a default constructor in the class that initializes all numeric fields in the class to zero and all string and object fields to null. Syntax:
[Access Modifier] ClassName([Parameters])
{
}
Example of default constructor:

public class MyClass
{
    public MyClass()
    {
    }
}


Types of Constructors

Below are the constructor types:
Default Constructor
Parameterized Constructor
Copy Constructor
Static Constructor
Private Constructor

What is the difference between ref & out parameters?

An argument passed as ref must be initialized before passing to the method whereas out parameter needs not to be initialized before passing to a method.

What is difference between constants and read-only

The "readonly" keyword is different than that of const keyword.
A const field can only be initialized at the declaration of the field. A "Const" field is a compile-time constant.

A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. The readonly field can be used for runtime constants.

What are value types and reference types?

Variables those holds actual data and stored on stack are "Value" types.
Ex. int, enum , byte, decimal, double, float, long

Variables those holds reference to the actual data are of "Reference" types.
Ex. string , class, interface, object

What are sealed classes in C#?

In C#, the "sealed" modifier prevents other classes to be inheriting from it.You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties

What is method Overloading?

Overloading is when you have multiple methods in the same scope, with the same name but different signatures. Also known as Compile Time Polymorphism. Ex.
//Overloading
public class OverloadClass
{
    public void someMethod(int id)
    {}
    public void someMethod(string name)
    {}
}

What is method Overriding?

Functions in the extended class with same name and same parameters as in the base class, but with different behaviors. Ex.
//Overriding
public class OverridingClass
{
   public virtual someMethod(int id)
   {
      //Get stuff default location
   }
}

public class test2 : test
{
   public override someMethod(int id)
   {
       //base.getStuff(id);
       //or - Get stuff new location
   }
}

What is the difference between Array and Arraylist?

In an array, we can have items of the same type only. The size of the array is fixed. An ArrayList hold data type of an object, So using array with different types can cause runtime error. It does not have a fixed size.

Which are Access Modifiers available in C#?

All types and type members have an accessibility level, which controls whether they can be used from other code in your assembly or other assemblies.
You can use the following access modifiers to specify the accessibility of a type or member when you declare it:

public: The type or member can be accessed by any other code in the same assembly or another assembly that references it.
private: The type or member can be accessed only by code in the same class or struct.
protected: The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
internal: The type or member can be accessed by any code in the same assembly, but not from another assembly.

What is static constructor?

Static constructor is used to initialize static data members as soon as the class is referenced first time. A static constructor does not take access modifiers or have parameters and can't access any non-static data member of a class.

What is Reference Type in C# ?

Let us explain this with the help of an example. In the code given below,
Employee emp1;
Employee emp2 = new Employee();
emp1 = emp2;
Here emp2 has an object instance of Employee Class. But emp1 object is set as emp2. What this means is that the object emp2 is referred in emp1, rather than copying emp2 instance into emp1. When a change is made in emp2 object, corresponding changes can be seen in emp1 object.

What is Abstract Class in C#?

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.

What is Sealed Classes in c# ?

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

What is the use of var keyword in C#?

This is the new feature in C# 3.0. This enable us to declare a variable whose type is implicitly inferred from the expression used to initialize the variable.
eg.
var age = 10;
Because the initialization value (10) of the variable age is integer type of age will be treated as integer type of variable. There are few limitation of the var type of variables.

Set dropdown text selected from textbox value

In some cases we need to set dropdown list items exact text by matching the value entered in textbox. For that purpose we can use .keyup event in jQuery. In .keyup event simply take the value of textbox and assign that value to the value of dropdown. Once you set value it's corresponding text will be get displayed as selected.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
     <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <title>Get dropdown value</title>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#topics").keyup(function () {
                var value = $("#topics").val();
                if (value == "" || isNaN(value))
                    value = 0;
                $("#topics1").val(value);
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox runat="server" ID="topics"></asp:TextBox>
    <br/><br/>
      <asp:DropDownList ID="topics1" runat="server">
     <asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
    <asp:ListItem Text="C#" Value="1"></asp:ListItem>
    <asp:ListItem Text="jQuery" Value="2"></asp:ListItem>
    <asp:ListItem Text="ASP.NET" Value="3"></asp:ListItem>
    </asp:DropDownList>
    </div>
    </form>
</body>
</html>

Note: You may need some additional validations if user enters data in textbox that does not match to the values in dropdown. Ex. I have just validated in above code if user enters characters other than number using IsNaN


jQuery templates

jQuery templates is a useful plugin developed by Microsofts's ASP.NET team in collaboration with jquery open source team. Templates helps you to manipulate the data at client side and display in browser. It is more useful to display the dataset that is fetched from database using client side Asynch Ajax call.

jQuery Template example

In order to use jQuery templates we either need to download "jquery.tmpl.js" plugin and add reference or we can also refer it from cdn.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
     <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
  <script type="text/javascript">

      $(document).ready(function () {
          debugger;
          var loc = window.location.href;
          $.ajax({
              type: 'POST',
              url: loc + "/GetBookList",
              data: "{}",
              contentType: "application/json; charset=utf-8"

          })
        .success(function (response) {
            debugger;
            $("#bookCollection").tmpl(response.d).appendTo(".book-container");
        })
        .error(function (response) {
            alert(response.d);
        });

      });
  </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="book-container">
    
    </div>
     <script id="bookCollection" type="text/x-jQuery-tmpl">
        <div>
           <h2>${Title}</h2>
            Author: ${Author}
            price: ${Price}
        </div>
    </script>
    </form>
</body>
</html>
Here in above code below script is template to which we are going to bind the data. <script id="bookCollection" type="text/x-jQuery-tmpl"> <div> <h2>${Title}</h2> Author: ${Author} price: ${Price} </div> </script> And by using $("#bookCollection").tmpl(response.d).appendTo(".book-container"); we actually bind the data to the template and append that template to some fixed html like div.


Below code is for reference to get data from code behind method:


 [WebMethod]
        public static List GetBookList()
        {

            return new List()
                       {
                           new Book {Title = "ASP.NET", Author = "Stephen", Price = 350.9},
                           new Book {Title = "WPF", Author = "Murli", Price = 400},
                           new Book {Title = "WCF", Author = "Avinash", Price = 350}
                       };
        }
Refer link to know how to make a ajax call to code behind.


Dynamic in C# 4.0

Dynamic type is introduced C# 4.0. As its name specifies type of the defined variable is decided dynamically at runtime. At compile time the variable that is declared as dynamic is assumed to be support any type or operation. As it does everything at runtime if code is not valid then errors are caught at runtime. Two major disadvantages of dynamic type are No compile time checking and No intelliSense support

Dynamic type example

Suppose we have class called SomeClass that have methods Method1() and Sum(intx, int y).
    public class SomeClass
    {
        public SomeClass()
        {
        }

        public void Method1()
        {
            //Do something
        }

        public int Sum(int x, int y)
        {
            return x + y;
        }
    }

and we are now trying to use the above class using dynamic type.
    public partial class DynamicType : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            dynamic someclass_dy = new SomeClass();
           
            someclass_dy.Method1();

            someclass_dy.Sum(10, 3);

            someclass_dy.SomeOtherMethod();
        }
     }

In above code we have defined dynamic type object of class SomeClass(). and now if you try to access methods from that class it will not show any method in intelliSense, you explicitly need to know the class methods and call them that is because dynamic type does not supports compile time checking. If you notice there is code line someclass_dy.SomeOtherMethod(); where SomeOtherMethod() does not exists in SomeClass() still it will not throw any compile time error, but it will throw runtime error.


Tuple in C# 4.0

Tuple is a new class introduced in C# 4.0. Tuple basically provides way to group the items of different data types. A static Tuple class provides 8 overloads of create method to create Tuple of size 1 to 8. Also using new keyword and nesting tuples you can create more sized Tuple. Now for example tuple created with 3 elements called 3-tuple or triple that can hold three elements of any type. So first element may be firstname that is string, second element may be phone number that is int and salary which is double may be the third element. And we can read those values using item property of tuple like for 3-tuple it will tuple.Item1, tuple.Item2 and tuple.Item3.

Tuple example 3-tuple

     var tuple3 = new Tuple("Johan", 1234567890, 56000.90);
     Console.WriteLine(tuple3.Item1);
     Console.WriteLine(tuple3.Item2);
     Console.WriteLine(tuple3.Item3);

In above example it will print
Output:
  Johan
  1234567890
  56000.90

Lazy loading C#. Lazy initialization.

C# 4.0 introduced new class Lazy which provided for Lazy initialization. Lazy instantiation here means object is not created until it is get used first time. Primary use of Lazy initialization is performance improvements, reduce program memory requirements.Lazy provides thread safe object initialization.

Lasy<T> example to load object lazily

public partial class LazyClass : System.Web.UI.Page 
{
 private Lazy<List<string>> lazyItems = null; 
 public LazyClass() 
 { 
   lazyItems = new Lazy<List<string>>(GetItems); 
 } 
 public List<string> GetItems() 
 {
      List<string> items = new List<string>(); 
      for (int i = 0; i < 10; i++) 
       { 
          items.Add(string.Format("Item {0}", i)); 
       } return items;
 }

 public List<string> GetItemValues { get { return lazyItems.Value; } } 
}

So in above example we have defined private Lazy<List<string>> lazyItems = null; and then in constructor we have delegate the call to GetItems method which will return list of items. But here it will not generate and return list until we call "lazyItems.Value".


Skip in Linq C#

Skip() in Linq avoids or skips the given number of elements from the sequence.

Skip() example in Linq

  protected void Page_Load(object sender, EventArgs e)
        {
            var numArr = new int[5];
            numArr[0] = 9;
            numArr[1] = 6;
            numArr[2] = 3;
            numArr[3] = 5;
            numArr[4] = 2;

            var numbers = numArr.Skip(3);
            foreach (var number in numbers)
            {
                Console.WriteLine(number);
            }
// Output will be 5, 2

So in above example of skip in linq, we have numArr.Skip(3);, that will skip first three elements from array and print remaining array elements.

Take() in Linq C#

In Linq i.e. System.Linq, Take operator is used to get the first specified number of elements a sequence.

Linq Take() example

using System.Linq;
protected void Page_Load(object sender, EventArgs e)
        {
            var numArray = new int[5];
            numArray[0] = 95;
            numArray[1] = 66;
            numArray[2] = 3;
            numArray[3] = 54;
            numArray[4] = 2;


            var numbers = numArray.Take(3);
            foreach (var number in numbers)
            {
                Console.WriteLine(number);
            }
        }
//It will print 95, 66, 3.

So in above sample code of Take() we have numArray.Take(3) that means it will return us the sequence of first three elements from array.

AsEnumerable() in Linq

AsEnumerable() method in Linq is used to cast or convert given type into it's IEnumerable type. AsEnumerable() basically changes the compile time type of given type that implements IEnumerable to IEnumerable itself.

Sample code to use AsEnumerable() in Linq

 protected void Page_Load(object sender, EventArgs e)
  {
      var numArray = new int[5];
      numArray[0] = 5;
      numArray[1] = 10;
      numArray[2] = 7;
      numArray[3] = 9;
      numArray[4] = 1;

      var numbers = numArray.AsEnumerable();
      foreach (var number in numbers)
       {
          Console.WriteLine(number);
       }
  }

Convert ToList() in Linq

In C# Linq, there is .ToList() extension method that is used to convert IEnumerable to List of type. Like .ToArray(), ToList() also forces immediate query execution and stores query result in List.

Example that shows how to convert array to list

 protected void Page_Load(object sender, EventArgs e)
  {
     string[] language = { "C#", "C++", "Java", "Pascal", "Cobol" };
     List languageList = language.ToList();

     foreach (string lang in languageList)
     {
                Console.WriteLine(lang);
     }
  }