Wednesday, 19 August 2015

Important C# Interview Questions and Answers

Hi all, I am sharing few important questions and answers of c# asked in interview.

Q. What is Collection in C#?
Collection classes are responsible for data storage. Collection supports queue, stack, list, hash table etc. Classes that comes under System.Collection namespace: ArrayList, HashTable, Queue

For more details see this link What is Collection

Q. What is reflection in C#?
Reflection in C# is used to get metadata of an assembly. Classes in Reflection uses System.Reflection namespace.

Below C# code is used to get assembly info , qualified name, base type etc.

use below namespace in your code:

using System.Reflection;

            Type tp = typeof(Program);
            Console.WriteLine("assembly- " + tp.Assembly + "qualified name- " + tp.AssemblyQualifiedName + "attributes- " + tp.Attributes + "base type- " +  tp.BaseType + "declaring type- " + tp.DeclaringType + "full name- " + tp.FullName+ "is abstract- " + tp.IsAbstract+ "is class- " + tp.IsClass+ "is enum- " + tp.IsEnum);

Q. What is get and set in C#?

Get and Set in C# is an auto property or auto implemented property which is a shorthand to write property.

 private string _Login; //Backing Field
 public string Login //Property
        {
            get
            {
                return _Login;
            }
            set
            {
                _Login = value;
            }
        }


Q. What is Abstract Class?
  • Abstract classes are incomplete that must be implemented in derived class.
  • Abstract class can contain Abstract or non-abstract methods.  
  • Abstract methods do not have any implementation in Abstract class and must be implemented in derived class.
  • In child class it is optional to implement the abstract method of parent class.
  • Abstract class can not be instantiated. 
  • You can not declare abstract class out side an abstract class.
  • Abstract class can not be declared sealed.  
  • Abstract method must declare in Abstract class only.

Abstract method is used for Dynamic Polymorphism.

A static member can not be marked as virtual, override or abstract (See below code)

 abstract class abs1
    {
        public static abstract int AddNum1(int a, int b); // Error in this line

        int AddNum2(int x, int y)
        {
            return x + y;
        }

    }


Abstract Class Example:

namespace MorePractice
{
    class Program:abs1 // Program inheriting abstract class abs1
    {
        static void Main(string[] args)
        {
            Program objp = new Program();
            Console.WriteLine(objp.AddNum1(5, 10));
            
        }

   public override int AddNum1(int a, int b) //overriding abstract method declare in abstract class abs1
        {
            return a + b;
        }
    }

    abstract class abs1 // abstract class abs1
    {
      public abstract int AddNum1(int a, int b); //abstract method with declaration only

      public static int AddNum2(int x, int y) //non-abstract method
        {
            return x + y;
        }

    }
}

For more see this link :

http://www.sharepointcafe.net/2015/06/difference-between-interface-and-abstract-class.html

Q. What is sealed class?
Abstract class can not be declared sealed.  Sealed class can not be inherited, but sealed class can inherit other class. It means a sealed class can not be a base class. Sealed keyword in a method must be used with override keyword.

Q. What is interface?

http://www.sharepointcafe.net/2015/06/difference-between-interface-and-abstract-class.html

Q. Data Hiding in C#?
Data Hiding or Data Encapsulation is used to hide data from outer world.
For eg: If you are buying a new handset you don't bother about its internal engineering or how signal converts and received by handset.

Q. Data Abstraction in C#?
Data Abstraction is hiding complexity and showing what is necessary.
For eg: If a user buy a new mobile phone he/she looks for color, mp3, camera, sound quality etc. He/she doesn't care about internal circuits.

Example of Abstraction:

 public class Pigeon:Bird
    {
        public override void fly()
        {
            Console.WriteLine("Pigeon Can Fly");
        }
    }

    public class Crow : Bird
    {
        public override void fly()
        {
            Console.WriteLine("Crow Can Fly High");
        }
    }


    abstract class Bird
    {
        public abstract void fly();
    }


Q. What is generic class in C#?
Generic allow you to work with class and method of any data type. In generic data type determines at run time only.

Consider below example:

class Test<T>
    {
        T val;
        public Test(T t)
        {
            this.val = t;
        }
        public void Print()
        {
            Console.WriteLine(this.val);
        }
    }


class Program
    {
        static void Main(string[] args)
        {

            Program objP = new Program();

            Test<int> objT = new Test<int>(10);
            objT.Print();


            Test<string> objT1 = new Test<string>("test");

            objT1.Print();
       }
  }

In above example there is a single method in Generic class Test of type T and gives out put based on provided data type i.e int or string.

Q. What is value type and reference type?
In Value type a space is allocated in memory to store variable.
In reference type address of the object is stored in stead of data itself.

Value Type:

int i= 20; //value of i i.e. 20 is stored in memory

Reference Type:

int[] arr = new int[20];  //

Q. What is boxing and unboxing?
Boxing- When a value type is converted in reference type.
int i = 67; // i is value type 
object ob = i; // variable i is boxed


Unboxing- When a reference type is converted into a value type.

Performance Impact:
when using value type in a method parameter, a copy of each parameter is created into stack. If it is a large data type , then its going to impact on performance.
So to avoid this issue better to use reference type by using ref keyword.

Example:

class A
        {
            public static void PrintDataValueType(int i)
            {
                Console.WriteLine(i);

            }

            public static void PrintDataRefType(ref int i)
            {
                Console.WriteLine(i);

            }

        }

class Program
    {
        static void Main(string[] args)
        {

            Program objP = new Program();

            int i = 100;
            A.PrintDataValueType(i); //Call with Value Type parameter

            A.PrintDataRefType(ref i); // Call with Reference Type parameter
         }
     }


Q. What is partial class in C#?
Partial class is used to split a class in 2 or more source file, see below code.


 public partial class Hotel
    {
        public void DoOrder()
        {
            Console.WriteLine("Order Placed");
        }
    }

    partial class Hotel
    {
        public void BillPayment()
        {
            Console.WriteLine("Bill Paid");
        }
    }

It is not mandatory to have more than one partial class, i.e. a single 

Q. What is Enum in C#?
Enum is a type with a set of related named constants. Enum type can be int, float, double.
By default first enumerator has value 0.
Lets see Enum by example.

 public enum days
   {
       Monday,
       Tuesday,
       Wednesday,
       Thursday,
       Friday,
       Saturday,
       Sunday
   }


   public class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(days.Monday);
            Console.WriteLine((int)days.Monday);          
         }
    }

Enum is used to make the code much readable and understandable.

Q. Explain Custom Logging in C#.

 http://www.sharepointcafe.net/2015/06/exception-handling-in-c-sharp-dot-net.html

Q. Access modifier in C#.

Default access modifier in C# is internal

Below are access modifier available in C#.

Public- No restriction, can be access from any where in the project.

Internal- Access limit to assembly.

Protected- Access limit to class and derived class. Protected variable is accessible in same partial class.

Private- Access limit to current scope where it is define. Private variable is accessible in same partial class. See below code

public partial class Test
    {
       protected int a=10;
        private void Print()
        {
            Console.WriteLine(a);
        }
    }

   partial class Test
    {
        public void Print1()
        {
            Console.WriteLine(a);
        }
    }


Q. What is Static and Dynamic Polymorphism?

Static Polymorphism is also called as Compile time Polymorphism or Early binding or Method Overloading.
In Static Polymorphism two methods will have same name but different parameter. See below example

public class New
    {
        public int Add(int a, int b)  //Method with two int parameter
        {
            return a + b;
        }

        public string Add(string x, string y) //Same method name but with two string parameter
        {
            return x + y;
        }
    }

Dynamic Polymorphism or Method Overriding or Late Binding means same method name with same parameters.

We can override a method in base class using override keyword in derived class method.

Example:

 public class New
    {
        public virtual int Add(int a, int b)
        {
            return 10;
        }

       
    }

    public class New2:New
    {
        public override int Add(int a, int b)
        {
            return 20;
        }
    }

Q. What is preprocessor directives in C#?
Preprocessor Directives gives instruction to compiler about what to do before actual compilation.

For eg:
Using below code you can tell compiler to execute below code only if the mode is in Debug else do not execute.

#if DEBUG
            Console.WriteLine("This is in Debug Mode");
#endif



Q. What is delegate and events in C#?

Delegate is a reference type and refers method.
Declaration of Delegate

  public delegate void MyDelegate();

C# code without delegate:

public class Program
    {
        static void Main(string[] args)
        {

            Program.Add(20, 10);
        }

        public static void Add(int a, int b)
        {
            Console.WriteLine(a + b);
        }
    }

C# code with delegate:

    public delegate void MyDelegate(int a, int b);
    public class Program
    {
        static void Main(string[] args)
        {

            MyDelegate del = new MyDelegate(Add); //Holding the reference of Add method
            del(10,20);
        }

        public static void Add(int a, int b)
        {
            Console.WriteLine(a + b);
        }
    }

Q. Virtual keyword in C#

Virtual or abstract members can not be private.

Error in below code:

public class Class1
    {
private virtual void Method() //method can not be private as virtual method must be accessible in other class to override
        {
            Console.Write("Hello");
        }
    }


Below code will give error:

Can not change access modifiers when overriding inherited member

See below code:

 public class Program:Class1
    {
      static void Main(string[] args)
        {
            
        }
        public override void Method()//Access modifier is changed from protected to public
        {
            base.Method();
        }
    }

    public class Class1
    {
       protected virtual void Method() //Here virtual method is protected
        {
            Console.Write("Hello");
        }

    }

Q. Class vs Struct
Class is a reference type, Struct is a value type.
Object of class holds the reference to the memory.
Struct do not support inheritance but class support.
Struct can not have default constructor but a class have.


Q. Primitive data type vs non-primitive data type
Primitive data type is predefined by system for eg- byte, short, int, float, double long etc.
Non-primitive data type is user defined for eg - class, struct, interface etc.

Q.Convert and Parse and TryParse
-Convert vs Parse
Compile Time Error
            int a = 10;
            int b = Convert.ToInt32(a);
            int c = int.Parse(a); //Error-The best overloaded method match for 'int.Parse(string)

Run Time Error
            int a = 10;
            string ss = null;
            int b = Convert.ToInt32(ss);//b = 0
            int c = int.Parse(ss);//Error - ArgumentNULLException was handled

        Try Parse
It converts string to integer and returns true if success else return false.

Q. What is Garbage Collection in C#?
Garbage collection is a part of CLR (Common Language Runtime) and it is used for automatic memory management. GC reclaims unused object, clears memory and make them available for future uses.

Generations of Garbage collection:
Generation 0: It contains newly created object. Generally hold temporary object.
Generation 1: It contains object of long live duration and transfer to Generation 2.
Generation 2: It contains longest lived object, generally object at application level.

Garbage Collector Phases:
Marking Phase: In this phase GC find and create list of active objects.
Relocation Phase: In this phase GC updates the reference to the objects that will be compacted.
Compacting Phase: In this phase GC reclaims the memory occupied by dead object.

No comments:

Post a Comment