Constructor Interview Questions in C#

1.what is a Constructor?
   Constructor is a method that is called when an instance of an object is created.
   They have the same name as a class.
    eg-
        class Test
       {
             public Test ()
            {

            }
        }


2.Can a constructor have access modifier?
    Yes. The fall are access modifiers allowed -
     1. Public --This is called whenever a class is initialized.
     2. Private- This will prevent the class from being instantiated (creating objects)
     3. Protected-
     4. Internal--cannot be instantiated outside the assembly.
 
3.If a class has parametrized constructor do we need to have default constructor?
   C# provides a default constructor with no parameters if there are no explicit ones. But if we
   have a parameterized constructor we need to specify a default one with no parameters.
 4.what is static constructor?
static constructor loaded during loading of class in CLR loader, before instantiation of class object. For example, when you go to college the college name is visible before becoming part of (instance of or before entry) college
   

5.Can constructors be inherited?
    No.

6.How can you call a base class constructor from a child class?
   Child class can call base class constructor by using the keyword base.

  
7.In which order constructor is called in inheritance?
    If Class B inherits Class A, when you create object of Class B then Class B constructor is called first then Class A constructor is called.
  eg-
      class ClassA
{
    public ClassA()
    {
        Console.WriteLine("I am class A");
    }
}

class ClassB:ClassA
{
    public ClassB()
    {
        Console.WriteLine("I am class B");
    }
}

output- I am class A
              I am class B


8.What is Copy constructor. Do you have this in C#?
 C# does not provide copy constructor.


9.Can constructors be overloaded?
      Yes.


10.How do you overload a constructor?    
      Overload a constructor by specifying diff parameters.
eg- 
            class numbers
           {
                public numbers() {
                 }

               public numbers(int a){
              }
          }

11.How do you call one constructor from another in the same class?
      By using this keyword. eg-
      class numbers
      {
                public numbers() {
                 }

               public numbers(int a):this(){
              }
       }

12.When you create an object of the above class which constructor is called 
      first?
      When you instantiate the above class first overloaded constructor is called and then the
       default one is called.


13.Can a constructor call itself by using this keyword?
      N0 it will through a compile time error.

     
12.Does memory gets allocated when constructor is called?
       Yes using new operator.


13. what happens when you instantiate an object?
      When you create instance of a class using new operator fall happens-
       New memory is allocated
       instance is created on heap
       reference is created on stack and passed on the instantiated object.


14.What happens if "new" keyword fails while instantiating?
       it throws OutOfMemoryException.



14.What is default access modifier of constructor?
       Private


15.Is it Ok to throw an exception from a constructor?
      No its not preferred. Constructors are used mainly for initialization purpose. But there are
      certain .Net Framework classes like DateTime, FileStream et which throw exception from
      constructor.


Read More »

Lambda Expressions in C#

To work with lambda expressions, we need to know at least some basic functionality on List and collections. Like Sql server we can Query the list from the front end and filter or remove or add some sort of data. Below are the some of the examples of the list operations.


Exists in Lambda Expression
bool result = feedDataList.Exists(x =>                           x.CC_ID.Equals(assortedData.resource.id, StringComparison.OrdinalIgnoreCase))


First in Lambda expression
var result = feedDataList.First(x => x. CC_ID.Equals(assortedData.resource.id, StringComparison.OrdinalIgnoreCase));


Where in lambda Expression
var result = feedDataList.Where(w => w.CC_ID == assortedData.resource.id).ToList().ForEach(i => i.EVENT_TYPE = eventType);


Remove All in Lambda Expression
feedDataList.RemoveAll(x => x.CC_ID == assortedData.resource.id);


Read More »

Polymorphism in .Net Interview Questions

Polymorphism


1.What is Polymorphism. Explain different types.

Ability to take more than one form is called polymorphism. Diff types are-

Compile time/Design time polymorphismthis is also called method overloading. The method will have same name but diff parameters.

Run time polymorphismthis is also called overriding. Its achieved by virtual and override keywords


2.What is method overloading?

Having different methods with same name but different parameters inn a single class is called method overloading. Methods can be overloaded based on following-

a) diff no of parameters.
              public void method (int a)
              public void method (int a,int b)
b) diff types of parameters.
              public void method (int a)
              public void method (float a)
c)diff order of parameters.
             public void method (int a,float b)
             public void method (float b,int a)


3.When should we use method overloading?

When you need couple of methods to take different parameters but do the same thing.
eg-Draw (circle c), Draw (triangle t) ... the basic function is drawing but they draw diff structures. in CLR console.writeline() does the same thing.


4.What is method overriding?

It is a feature which is used in inheritance chain and it provides its own implementation to an already existing method in base class. its achieved by using virtual and override keyword.
class A
{
     public virtual void method()
     {
     }
}
class B:A
{
    public override void method()
     {
     }
}
The appropriate methods are invoked at runtime when proper references are allocated.


5.Advantages of polymorphism.

a) invoking child class functions dynamically
b) maintenance of code becomes easy.


6.Whats the diff between new and override keyword in inheritance chain?

new keyword completely hides the base class implementation and creates a
new method. It can be concluded that the method defined is independent of
base class method.
override keyword overrides the base class implementation. it helps in existence of different diff versions of method and appropriate version is called dynamically. Objects of derived class will call this method instead of base class method.


7.Will the full code compile? why?
a)
class A
{
     public void method()
     {
     }
}
class B:A
{
     public override void method()
     {
     }
}
No, because you can override the base class method only if its marked as virtual

b)
class A
{
     public void method()
     {
     }
}
class B:A
{
     public new void method()
     {
     }
}
Yes, because new keyword defines its own implementation and it is not related to base class method in any way.

c)
class A
{
     public void method(ref int a)
     {
     }
     public void method(out int a)
     {
     }
}
No, methods cannot be overloaded based on the ref and out parameter.

d)
class A
{
     public virtual void method()
     {
     }
}
class B:A
{
     public void method()
     {
     }
}
class C:B
{
     public override void method()
     {
     }
}
No, class C is overriding method in its base class B. it can do so only if method in base class is marked as virtual.

e)
class A
{
     public virtual void method()
     {
     }
}
class B:A
{
     public new void method()
     {
     }
}
class C:B
{
     public override void method()
     {
     }
}
No, class C is overriding method in its base class B. it can do so only if method in base class is marked as virtual.


8.Whats the disadvantage of using virtual keyword?

a) Appropriate function calls are determined only at runtime.
b) since virtual keyword is used derived classes may ignore that base class implementations.


9.Whats the output of full code
a)
class A
{
     public virtual void method()
     {
      //print A
     }
}
class B:A
{
     public override void method()
     {
      //print B
     }
}
class C:B
{
     public new void method()
     {
       //Print C
     }
}
A objA = new A();
objA .method()                              //Output: A

objB= new B()
objB.method()                               //Output: B
                          
objC= new C()
objC.method()                               //Output: C


10.Why static methods cannot have virtual keyword?

The idea of using virtual keyword is to achieve polymorphism i.e., calling appropriated functions dynamically at runtime, but static methods are attached to the class names and to invoke them you have to go through the classes. And they are decided at compile time hence there is no point in having virtual keyword to static methods.


11.Can properties be marked as virtual?
Yes



Read More »

Inheritance in .Net Interview Questions

Inheritance


1. What is inheritance?
The method of constructing one class from another is called Inheritance. The derived class inherits all the properties and methods from the base class and it can add its own methods also.


2. Are constructors and destructors inherited?
No


3. Advantages of Inheritance.
a) Code re usability-Public and protected methods can be used in derived classes
b) Extensibility- base class can be extended as per business logic in derived classes.
c) Polymorphism


4. What are diff types of inheritance?
a) Single inheritance --Class B is derived from base class A. A->B
b) Multiple inheritance ---Class C derives from both A and B.  A,B->C
c) Multilevel inheritance--Class B derives from Class base class A. class C derives from B.  A->B->C
d) Hybrid inheritance --class B and C derives from same base class A.  A->B, C


5. Is multiple inheritances possible in C#. Why?
No. because
a) It is not supported by CLR since its support many diff language and not all languages can have multiple inheritance concept.
b) Because of the complexities involved where method name can clash when two diff classes have same method name. This is resolved by pointers in C++ but it’s not possible in c#.
·        Instead interfaces can be used to achieve the same.


6. Is circular inheritance possible. Like A: B, B: A?
No


7. How do you prevent a class from being inherited?
a) Make the class as sealed.
b) Add private constructors to the class.


8. Can derive class have public modifier when there are no modifiers specified on the base class?
No. base class derived class cannot be more accessible that base class.


9. Why c# does not support inheritance by structure?
Because, structures are mainly used for light weight process. And if they are allowed to be inherited then they have to act as base class which is not possible as they are value types.


10. Does structs inherit from interfaces?
Yes structs can inherit only from interface.


11. What do you mean by sealed keyword?
If you mark a class as sealed it means that you cannot inherit from it but you can create objects of that class.


12. Can you mark method as sealed?
Yes. But for a method to be marked as sealed you need to have override keyword also.


13. What do you mean by up casting and down casting?
class DerivedClass :BaseClass

 Upcasting :  assigning a derived class object to a base class. This is implicit.
BaseClass b= new DerivedClass.

Downcasting : assigning base class object to derived class. This is explicit and it throws runtime error.

a)     BaseClass b = new BaseClass()
   DerivedClass d= b  //will give compile time error.
 
b) d=(DerivedClass)b  //will give runtime error.


c) b=d;
   d=(DerivedClass)b;
   d.method()             //will always call derivedclass method

   //there is no point in taking so much of pain and using this kind of code.


Read More »

Linked list operations in C#

Linked list is a linear collection data set where One node pointing to other node.
While adding new value to Linked List we can directly add First, add Last, adding after Specific Node and Adding before Specific node.

linkedlstobj.AddFirst(Value);
linkedlstobj.AddLast(value);
linkedlstobj.AddBefore(node, value);
linkedlstobj.AddAfter(node, value);

To get the Node from Linked List we need to pass the value and output datatype LinkedListNode<T>

LinkedListNode<string> node = linkedlstobj.Find(value);

While removing values from Linked List we can remove the node by giving value of the node, removing first element and removing last element.

linkedlstobj.Remove(value);
linkedlstobj.RemoveFirst();
linkedlstobj.RemoveLast();



Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LLEXAMPLE
{
    class Program
    {
        static void Main(string[] args)
        {
            LinkedList<string> linkedlstobj = new LinkedList<string>();
           
            //Adding values into LinkedList in C#          
            linkedlstobj.AddFirst("Ant"); //Add node from begining
            linkedlstobj.AddLast("Fox"); //Add node at last of linked list

            // get linkedListNode by passing value
            LinkedListNode<string> node = linkedlstobj.Find("Fox");
           
            //Adding new value after specific node
            linkedlstobj.AddBefore(node, "Elephant");
            //Adding new value after specific Node
            linkedlstobj.AddAfter(node, "Goat");

            //Removing values into LinkedList in C#
            linkedlstobj.Remove("Fox");//remove by passing value
            linkedlstobj.RemoveFirst();//remove first value in linkedList
            linkedlstobj.RemoveLast();//remove last value in Linkedlist

        }
    }
}


Read More »