C# Interview Questions on constructors


1) What is a constructor in C#?
Ans) Constructor is a class method that is executed when an object of a class is created. Constructor has the same name as the class, and usually used to initialize the data members of the new object. 

2) In C#, What will happen if you do not explicitly provide a constructor for a class?
Ans) If you do not provide a constructor explicitly for your class, C# will create one by default that instantiates the object and sets all the member variables to their default values.

3) Structs are not reference types. Can structs have constructors?
Ans) Yes, even though Structs are not reference types, structs can have constructors.

4) We cannot create instances of static classes. Can we have constructors for static classes?
Ans) Yes, static classes can also have constructors.

5) Can you prevent a class from being instantiated?
Ans) Yes, a class can be prevented from being instantiated by using a private constructor as shown in the example below.

using System;
namespace TestConsole
{
  class Program
  {
    public static void Main()
    {
      //Error cannot create instance of a class with private constructor
      SampleClass SC = new SampleClass();
    }
  }
  class SampleClass
  {
    double PI = 3.141;
    private SampleClass()
    {
    }
  }
}



6) Can a class or a struct have multiple constructors?
Ans) Yes, a class or a struct can have multiple constructors. Constructors in csharp can be overloaded.

7) Can a child class call the constructor of a base class?
Ans) Yes, a child class can call the constructor of a base class by using the base keyword as shown in the example below.

using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }

  class ChildClass : BaseClass
  {
    public ChildClass(string str): base(str)
    {
    }

    public static void Main()
    {
      ChildClass CC = new ChildClass("Calling base class constructor from child class");
    }
  }
}

8) If a child class instance is created, which class constructor is called first - base class or child class?
Ans) When an instance of a child class is created, the base class constructor is called before the child class constructor. An example is shown below.

using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass()
    {
      Console.WriteLine("I am a base class constructor");
    }
  }
  class ChildClass : BaseClass
  {
    public ChildClass()
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}

9) Will the following code compile?
using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }
  class ChildClass : BaseClass
  {
    public ChildClass()
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}

Ans) No, the above code will not compile. This is because, if a base class does not offer a default constructor, the derived class must make an explicit call to a base class constructor by using the base keyword as shown in the example below.

using System;
namespace TestConsole
{
  class BaseClass
  {
    public BaseClass(string str)
    {
      Console.WriteLine(str);
    }
  }
  class ChildClass : BaseClass
  {
    //Call the base class contructor from child class
    public ChildClass() : base("A call to base class constructor")
    {
      Console.WriteLine("I am a child class constructor");
    }
    public static void Main()
    {
      ChildClass CC = new ChildClass();
    }
  }
}

10) Can a class have static constructor?
Ans) Yes, a class can have static constructor. Static constructors are called automatically, immediately before any static fields are accessed, and are generally used to initialize static class members. It is called automatically before the first instance is created or any static members are referenced. Static constructors are called before instance constructors. An example is shown below.

using System;
namespace TestConsole
{
  class Program 
  {
    static int I;
    static Program()
    {
      I = 100;
      Console.WriteLine("Static Constructor called");
    }
    public Program()
    {
      Console.WriteLine("Instance Constructor called");
    }
    public static void Main()
    {
      Program P = new Program();
    }
  }
}

11) Can you specify static constructor with access modifiers?
Ans) No, we cannot use access modifiers on static constructor.

12) Can  static constructors have parameters?
Ans) No, static constructors cannot have parameters.

13) What happens if a static constructor throws an exception?
Ans) If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

14) Give 2 scenarios where static constructors can be used?
Ans) 
1. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
2. Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

C#.net Interview Questions on Destructors

1) What is a Destructor?
Ans) A Destructor has the same name as the class with a tilde(~) character and is used to destroy an instance of a class.

2) Can a class have more than 1(one) destructor?
Ans) No, a class can have only 1(one) destructor.

3) Can structs in C# have destructors?
Ans) No, structs can have constructors but not destructors, only classes can have destructors.

4) Can you pass parameters to destructors?
Ans) No, you cannot pass parameters to destructors. Hence, you cannot overload destructors.

5) Can you explicitly call a destructor?
Ans) No, you cannot explicitly call a destructor. Destructors are invoked automatically by the garbage collector.


C# Interview Questions on Abstract and Sealed Class Members

1) What is an abstract class?
Ans) An abstract class is an incomplete class and must be implemented in a derived class. However we left implementation in derived class, the derived class is also called as abstract class.

2) Can you create an instance of an abstract class?
Ans) No, abstract classes are incomplete and you cannot create an instance of an abstract class.

3) What is a sealed class?
Ans) A sealed class is a class that cannot be inherited from. This means, If you have a class called Customer that is marked as sealed. No other class can inherit from Customer class. For example, the below code generates a compile time error "DemoClass cannot derive from sealed type Customer.

using System;
public sealed class Customer
{
}
public class DemoClass : Customer
{
public static void Main()
{
}
}

4) What are abstract methods?
Ans) Abstract methods are methods that only the declaration of the method and no implementation(cannot have body).

5) Will the following code compile?
using System;
public abstract class Customer
{
public abstract void TestMethod()
{
Console.WriteLine("I am customer");
}
}
public class MainClass
{
public static void Main()
{
}
}
Ans) No, abstract methods cannot have body. Hence, the above code will generate a compile time error "Customer.TestMethod() cannot declare a body because it is marked abstract"

6) Is the following code legal?
using System;
public class Customer
{
public abstract void Test();
}
public class MainClass
{
public static void Main()
{
}
}

Ans) No, if a class has even a single abstract member, the class has to be marked abstract. Hence the above code will generate a compile time error stating "Customer.Test() is abstract but it is contained in nonabstract class Customer"

7) How can you force derived classes to provide new method implementations for virtual methods?
Ans) Abstract classes can be used to force derived classes to provide new method implementations for virtual methods(virtual methods which is existing in base class). An example is shown below.

public class BaseClass
{
public virtual void Method()
{
// Original Implementation.
}
}

public abstract class AbstractClass : BaseClass
{
public abstract override void Method();
}

public class NonAbstractChildClass : AbstractClass
{
public override void Method()
{
// New implementation. ( You can change here)
}
}

When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method. In the above example, Method() on class NonAbstractChildClass cannot call Method() on class BaseClass. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.

8) Can a sealed class be used as a base class?
Ans) No, sealed class cannot be used as a base class. A compile time error will be generated.

9) Will the following code compile?
ans)
public abstract sealed class TestDemo
{
public virtual void Method()
{
}
}
No, a class cannot be marked as sealed and abstract at the same time. This is because by definition, a sealed class cannot be a base class and an abstract class can only be a base class.

C# Interview Questions on value types and reference types

1) What are the different data types available in C#?
Ans)
1. Value Types
2. Reference Types

2) Is struct  value type or reference type?
Ans) Value Type

3) Is class   value type or reference type?
Ans) Reference type

4) Are Value types sealed?
Ans) Yes, Value types are sealed.


5) Can Value Types inherit from another class or struct?
Ans) No. 

6) Can Struct inherit from another interface?
Ans) Yes.

7) What is the base class from which all value types are derived?
Ans) System.ValueType

8) Give examples for value types?
Ans)
 Enum
Struct

9) Give examples for reference types?
Ans)
Class
Delegate
Array
Interface

10) What are the differences between value types and reference types?
Ans)
1. Value types are stored on the stack where as reference types are stored on the managed heap.
2. Value type variables directly contain their values where as reference variables holds only a reference to the location of the object that is created on the managed heap.
3. There is no heap allocation or garbage collection overhead for value-type variables. As reference types are stored on the managed heap, they have the over head of object allocation and garbage collection.
4. Value Types cannot inherit from another class or struct. Value types can only inherit from interfaces. Reference types can inherit from another class or interface. 

11) Can you create object of a struct?
Ans) Yes, we can create object of struct like how we create object for class.

12) Can Structs contain explicit parameterless constructors?
Ans) No, Structs cannot contain explicit parameterless constructors.


C# interview questions on strings

1) Will the following code compile and run? 
 Ans) string str = null;
Console.WriteLine(str.Length);

The above code will compile, but at runtime System.NullReferenceException will be thrown.

2) How do you create empty strings in C#? 

 Ans) Using string.empty as shown in the example below.
string EmptyString = string.Empty;

3) What is the difference between System.Text.StringBuilder and System.String?
Ans)  

1. Objects of type StringBuilder are mutable where as objects of type System.String are immutable. 
2. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String.
3. StringBuilder class is present in System.Text namespace where String class is present in System namespace.

4) How do you determine whether a String represents a numeric value?
Ans) To determine whether a String represents a numeric value use TryParse method as shown in the example below. If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.

string str = "Two";
int i = 0;
if(int.TryParse(str,out i))
{
     Console.WriteLine("Yes string contains Integer and it is " + i);
}
else
{
     Console.WriteLine("string does not contain Integer");
}

5) What is the difference between int.Parse and int.TryParse methods? 

Parse method throws an exception if the string you are trying to parse is not a valid number where as TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse.


6) Write a syntax of int.TryParse method?
Ans)
bool isNumeric =  int.TryParse(string param , out int result)

Parameters:
param: The parameter string.
result: The result will store in this variable

Returns:
returns True or False 

IEnumerable and IEnumerator in C# with example

We will discuss here what is IEnumerable, IEnumerator, what are differences between them, where should we use IEnumerable and where to IEnumerator, once we will finish our discussion it will be clear, which one would be best for which situation and why, so let’s see it with example
To better understand we will create a list of age
List<int> ages = new List<int>();
ages.Add(10);
ages.Add(20);
ages.Add(30);
ages.Add(40);
ages.Add(50);
Now convert this list to IEnumerable
IEnumerable<int> age_IEnumerable = (IEnumerable<int>)ages;
foreach (int age in age_IEnumerable)
    Console.WriteLine(age);
There is nothing new, we used foreach here very straight forward, now let’s convert the ages into IEnumerator, there is a method GetEnumerator to convert a list into IEnumerator
IEnumerator<int> age_IEnumerator = ages.GetEnumerator();
while (age_IEnumerator.MoveNext())
    Console.WriteLine(age_IEnumerator.Current);
As you can see here we used while rather than foreach because foreach cannot be used with IEnumerator, but still there is nothing which can suggest us when should we use IEnumerable and where to IEnumerator.
Before we go further, we should know, IEnumerable uses IEnumerator internally also have a function GetEnumeratorto convert into IEnumerator, we should use IEnumerable because it make coding easier and clearer as we can see in above example.
Now let’s discuss the main difference, IEnumerable doesn’t remember the state, which row or record it is iterating while IEnumerator remember it and we are going to see this with example by creating method PrintUpto30 and PrintGreaterThan30
Let’s first check with IEnumerator

As we know IEnumerator persists state so once we will call PrintGreaterThan30 by passing
age_IEnumerator it will print the remaining list, here is the output:

Now let’s check same code with IEnumerable

Now check the output you will see “PrintGreaterThan30 is called” many times something like this


Conclusion:
  1. Both are interface
  2. IEnumerable code are clear and can be used in foreach loop
  3. IEnumerator use While, MoveNext, current to get current record
  4. IEnumerable doesn’t remember state
  5. IEnumerator persists state means which row it is reading
  6. IEnumerator cannot be used in foreach loop
  7. IEnumerable defines one method GetEnumerator which returns an IEnumerator
  8. IEnumerator allows readonly access to a collection

Brief idea about mvc

1) What is MVC (Model View Controller)?
 Ans) MVC is an architectural pattern which separates the representation and user interaction. It’s divided into three sections, Model, View, and Controller. Below is how each one of them handles the task.

View: The View is responsible for the look and feel.
Model: Model represents the real world object and provides data to the View.
Controller: The Controller is responsible for taking the end user request and loading the appropriate Model and View.

2) Is MVC suitable for both Windows and Web applications?
Ans) The MVC architecture is suited for a web application than Windows. For Window applications, MVP, i.e., “Model View Presenter” is more applicable. If you are using WPF and Silverlight, MVVM is more suitable due to bindings

3) What are the differences between 3-layered architecture and MVC?
Ans) MVC is an evolution of a three layered traditional architecture. Many components of the three layered architecture are part of MVC. So below is how the mapping goes:
Functionality3 layered / tiered architectureMVC architecture
Look and FeelUser interfaceView
UI logicUser interfaceController
Business logic /validationsMiddle layerModel
Request is first sent toUser interfaceController
Accessing dataData access layerData Access Layer

MVC interview questions on razor

1) What is Razor in MVC?
Ans) It’s a light weight view engine. Till MVC we had only one view type, i.e., ASPX. Razor was introduced in MVC 3.

2) Why Razor when we already have ASPX?
Ans) Razor View engine is a part of new rendering framework for ASP.NET web pages. Razor is clean, lightweight, and syntax's are easy as compared to ASPX.
 For example, in ASPX to display simple time, we need to write:

<%=DateTime.Now%>  (Asp.net rendering engine uses opening and closing brackets to denote code (<% %>))

In Razor, it’s just one line of code:

@DateTime.Now 

3) Which is a better fit, Razor or ASPX?
Ans) As per Microsoft, Razor is more preferred because it’s light weight and has simple syntax's.


 

C# Interview Questions on Methods / Functions

1) Is the following code compile?
using System;
namespace MethodOverloadingDemo
{
 class AddProgram
 {
  public static void Main()
  {
  }
  public void Sum(int FN, int SN)
  {
   int Result = FN+ SN;
  }
  public int Sum(int FN, int SN)
  {
   int Result = FN+ SN;
  }
 }
}
Ans)  No, The above code does not compile. You cannot overload a method based on the return type. To overload a method in C# either the number or type of parameters should be different. In general the return type of a method is not part of the signature of the method for the purposes of method overloading. 


2) What is the difference between method parameters and method arguments. Give an example?
namespace MethodOverloadingDemo
{
 class AddProgram
 {
  public static void Main()
  {
   int FN = 10;
   int SN = 20;
   //FN and LN are method arguments
   int Total = Sum(FN, SN);
   Console.WriteLine(Total);
  }
  //FirstNumber and SecondNumber are method parameters
  public static int Sum(int FirstNumber, int SecondNumber)
  {
   int Result = FirstNumber + SecondNumber;
   return Result;
  }
 }
}

In the example above FirstNumber and SecondNumber are method parameters where as FN and LN are method arguments. The method definition specifies the names and types of any parameters that are required. When calling code calls the method, it provides concrete values called arguments for each parameter. The arguments must be compatible with the parameter type but the argument name (if any) used in the calling code does not have to be the same as the parameter named defined in the method.

3) Explain the difference between passing parameters by value and passing parameters by reference with an example?


We can pass parameters to a method by value or by reference. By default all value types are passed by value where as all reference types are passed by reference. By default, when a value type is passed to a method, a copy is passed instead of the object itself. Therefore, changes to the argument have no effect on the original copy in the calling method.An example is shown below.


Output : 0

Output : 101


4) Can you pass value types by reference to a method?
Ans) Yes, we can pass value types by by reference to a method. An example is shown below.
using System;
namespace MethodDemo
{
 class Program
 {
  public static void Main()
  {
   int I = 10;
   Console.WriteLine("Value of I before passing to the method = " + I);
   Function(ref I);
   Console.WriteLine("Value of I after passing to the method by reference= " + I);
  }
  public static void Function(ref int Number)
  {
   Number = Number + 5;
  }
 }
}
5) If a method's return type is void, can you use a return keyword in the method?
Ans) Yes, Even though a method's return type is void, you can use the return keyword to stop the execution of the method as shown in the example below.
using System;
namespace MethodDemo
{
 class Program
 {
  public static void Main()
  {
   HelloMethod();
  }
  public static void HelloMethod()
  {
   Console.WriteLine("Hello method called");
   return;
   Console.WriteLine("This statement will never be executed");
  }
 }
}
6) What is the syntax of Method?
Ans) 
access-modifiers return-type method-name (parameters) 
{
Method Body
}
7) What are static methods?
Ans) When a method declaration includes a static modifier, that method is said to be a static method. Static method is invoked using the class name.

C# Interview Questions on Enumerations

1) Enums stands for ?
Ans) Enums stands for Enumerations 

2) What is underlying type for enum?
Ans) The default underlying type of an enum is int.
The default value for first element is ZERO and gets incremented by 1.

3) Is it posible to customize the underlying type and values?
Ans) Yes, It is possible to customize the underlying type and values.

4) Is Enums are value types?
Ans) Yes, Enums are value types.

5) Enum keyword (all small letters) is used to create enumerations, where as Enum class, contains static GetValues() and GetNames() methods which can be used to list Enum underlying type Values and Names.

6) What is the use of Enum?
Ans) If a program used set of integral numbers, better replacing them with enums, which makes the program more 
Readable
Maintainable

Example : 



























The above code is more readable

7) Write a code to get Enum values and names?
Ans) 


8) Can you write a code to customize enum type? 
Ans)
9) Can you write a code to customize Enum values?
Ans)