Important C# Interview Questions and Answers

In this blog, I have collected questions and answers of c# asked in the interview.

C# interview questions and answers

Q. What is Object Oriented Programming?

Please read here about Object Oriented Programming.

Q. What are OOPS Principals?

OOPS principal is the most asked questions in an interview for C#, Java, ASP.Net developer role.

Please read here about OOPS Principals in details. 

Q. Class Vs Struct

Class
Struct
A class is a reference type.
A struct is a value type.
When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. 
When a struct is created, the variable to which the struct is assigned holds the struct's actual data. 
Classes and structs can inherit multiple interfaces. 
Classes and structs can inherit multiple interfaces. 
Class Support inheritance
Struct do not support inheritance
Class have default constructor
Struct cannot have default constructor

Important ASP.Net Interview Questions and Answers for Experienced Developer

C# 6.0 new features

Q. What is Interface?

Interface is similar to class but Interface contains only Abstract methods i.e. we can only declared methods in interface and no method body can be defined in interface.

All methods declared in an interface should be implemented by child class of that interface.
By default all members of an interface are public and abstract.

Method declaration in Interface -

void Show(string name);
int Add(int a, int b);

We can't declare a field or a variable in an interface.
An interface can inherit from another interface.

Look at below sample code -

Interface1 contains a single method GetEmployeeList()

interface Interface1
    {
        void GetEmployeeList();
    }

    interface IDepartment :Interface1
    {
        void GetEmployeeByDepartment(int deptID);
    }

IDepartment interface contains one method GetEmployeeByDepartmentID(int deptID)

Class Test implement Interface1 so it has to define only one method i.e. GetComployeeList()

 Class Test1 implements IDepartment interface so it has to define GetEmployeeByDepartment(int deptID) and also GetComployeeList() because as shown above IDepartment inherits Interface1. So IDepartment contains 2 methods.

Note: If you are implementing a method of an interface in a class, then the method must be public in that class.

class Test : Interface1
    {
        public void GetEmployeeList()
        {
            throw new NotImplementedException();
        }
    }

    class Test1 : IDepartment
    {
        public void GetEmployeeByDepartment(int deptID)
        {
            throw new NotImplementedException();
        }

        public void GetEmployeeList()
        {
            throw new NotImplementedException();
        }
    }

Single inheritance is supported in C# but multiple inheritance is not supported using classes.i.e. 
A class can not have multiple base class.

class B
{
}

class C
{
}
  Below is incorrect, a class can not have multiple base class.
Class A: B,C
{
}

Q. Why Multiple Inheritance not supported using class?

In above sample code, class B and class C may contain a same method ABC()
So, if class A will inherit class B and class C then ABC() method can create ambiguity in class A. This is the reason multiple inheritance is not supported using class.

Multiple inheritance can be supported using interface. 

Look at below 2 interfaces.

interface Interface1
    {
        void GetEmployeeList();
    }

    interface IDepartment
    {
        void GetEmployeeList();
        void GetEmployeeByDepartment(int employeeID);
    }
 

class Program implement 2 interfaces Interface1 and IDepartment.
 You may notice GetEmployeeList() method is in both interface but in class Program there is only one implementation. So no ambiguity and no compile time error.

    class Program:Interface1,IDepartment
    {
        public static void Main(string[] args)
        {
            Program obj = new Program();
        }

        public void GetEmployeeByDepartment(int employeeID)
        {
            throw new NotImplementedException();
        }

        public void GetEmployeeList()
        {
            throw new NotImplementedException();
        }
    }
 

  

Q. How to implement interface explicitly?


using InterfaceName.MethodName
See sample code below.
  
class Program:Interface1
    {
        public static void Main(string[] args)
        {
            Program obj = new Program();
            Interface1 i = obj;
            i.GetEmployeeList();
        }

        void Interface1.GetEmployeeList()
        {
            throw new NotImplementedException();
        }
    }

Q. Differences between Interface and Abstract Class

Interface
Abstract Class
If we don’t know about implementation then go for Interface
If we know about implementation then go for Abstract class
Every method in an Interface is public by default.
In Abstract class every method need not to be public class. Abstract class may contain Abstract or non-abstract (concrete) methods.
We can't use method with access modifier like public, private, protected
Abstract class has no such restrictions.
An interface cannot contains constructor
Abstract class can contains constructor

Q. Abstract vs Sealed Class


Abstract Class
Sealed Class
An abstract class cannot be instantiated. 
A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. 
The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
Sealed classes prevent derivation. Because they can never be used as a base class.
Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods.

When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method.




Q. Constructor vs Destructor

A method with same name as class name is called constructor.
Constructor by default public.
Constructor will not return anything.
Constructor name is same as class name.
Constructor with no arguments and no body is called default constructor.
We can create private constructors.

Constructor is a special method of a class which is automatically called as soon as object of class is created.


3 types of of constructor Default Constructor, Parametrized Constructor, Copy Constructor



Default constructor:

Public class Employee()

{

Public Employee()

{

}



Parameterized Constructor:

Public Employee(int id, string name, decimal sal)
{
//Assign property
}

}



Copy Constructor:

Employee emp = new Employee();

Emploee emp1 = new Employee(1,"Emp1",10000)

emp1 = emp;

emp1.Name = "KK";
emp1.Sal = 20000;
emp1.ID = "Emp2";
emp = new Employee(emp1); //Copy Constructor

Destructor
It is called automatically when an object is no longer in use. This activity is automatically controlled by Garbage Collector.

Q. What is Collection in C#?

Collection classes are responsible for data storage. The 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 a 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.
  • An 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 a parent class.
  • An abstract class can not be instantiated. 
  • You can not declare abstract class out side an abstract class.
  • An abstract class can not be declared sealed.  
  • An abstract method must declare in Abstract class only.

An 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?

An 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 an 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 the 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 a handset.

Important ASP.Net Interview Questions and Answers for Experienced Developer

C# 6.0 new features

Q. Data Abstraction in C#?

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

An 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 a 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 Post back property?


Post back is used to send back the web form on the web server with the data in its control for further processing. After processing on the server the page will be again loading into the memory. This whole process is known as the round tripping of the page.

Q. What is a value type and reference type?

In Value, type 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 a 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. Boxing and Unboxing

When we are not sure about what data type we are going to receive, then we use object as data type.
object can hold value for any data type.

Boxing: Value type to reference type.
Unboxing: Reference type to value type.


     static void Main(string[] args)
        {
            int count = 10;
            object obj = count;  //Boxing
            int newcount = (int)obj; //Unboxing
        }

Q. What is a partial class in C#?

A 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. Dispose vs finalize vs using block

Dispose method belongs to IDisposable interface.
IDisposable interface. has only one method called "Dispose()"
Dispose() method can be controlled i.e. we can call whenever we want to dispose an object.

public void Dispose()
{
GC.SupressFinalize(this);//This method will remove the object from Finalize queue and will overtake this to dispose method.
}


When we call Destructor , at run time it is going to convert into Finalize or we can say that it will override Finalize method. And that object for which destructor is being called is going to add in Finalize queue.

It will be like
protected override void Finalize()

So we can say that using destructor, Finalize method can be implemented.

GC.collect() - Deallocate all the inactive object memory. It is expensive operation.

Program objP = new Program();
objP = null; //It means now object is inactive and it can be free from memory by GC.


Using block will automatically take care of Dispose() method.

using(Program objP = new Program())
{
//Write code here
}

We can use Database connection with using block.

Good Practice:


  1. Follow using statement to make sure Dispose is called.
  2. Do not implement Finalize or Call Destrcutor unless require.

Q. String vs StringBuilder


String is immutable.
String Builder is mutable.
String Builder is better when manipulating heavy string.

static void Main(string[] args)
        {
            string message = "Hello !";
            message += " How ";
            message += " are ";
            message += " you? ";
            Console.WriteLine(message);


        }

//String builder
       static void Main(string[] args)
        {
            StringBuilder strMessage = new StringBuilder("Hello");
            strMessage.Append(" How");
            strMessage.Append(" are");
            strMessage.Append(" you?");
            Console.WriteLine(strMessage);
        }

Q. What is Delegate in C# ?

A delegate holds the reference of a method.


public delegate void AddPtr(int a, int b);

        static void Main(string[] args)
        {
             
            AddPtr objPtr = new AddPtr(Add);
            //Either we can call via this
            objPtr.Invoke(10, 5);
            //Or we can call via this
            objPtr(20, 7);        }

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

        }

Q. Sealed vs Virtual Class

Sealed class prevent itself to being inherited by other class.

sealed class ProgramNew
    {

    }

    class ExtendProgram : ProgramNew
    {

    }

If you compile above code, it will throw error. 
Error: cannot derive from sealed type

 Q. What is Partial Class?

Partial class allow developers to split the class into 2 or more source files.

Below is the example.
public partial class Employee
   {
       public void SalaryProcess()
       {
           //Do coding for salary calculation like basic+hra+medical
       }
   }

   public partial class Employee
   {
       public void TaxCalculation()
       {
           //Do coding for Tax calculation
       }

   }

Q. What is Static Constructor?

Static constructor will be invoked only once for any number of instance of a class. Static constructor must be parameterless.

   class Program
    {
        /// <summary>
        /// Static Constructor
        /// </summary>
        static Program()
        {
            Console.WriteLine("Static Constructor");
        }

        /// <summary>
        /// Default Constructor
        /// </summary>
        Program()
        {
            Console.WriteLine("Default Constructor");
        }

        /// <summary>
        /// Parameterize Constructor
        /// </summary>
        /// <param name="msg"></param>
        Program(string msg)
        {
            Console.WriteLine("Hello ! " + msg);
        }

        static void Main(string[] args)
        {
            Program obj = new Program();
            Program obj1 = new Program();
            Program obj2 = new Program("C#");
           
        }
       
    }

O/P-   Static Constructor 
         Default Constructor
         Default Constructor
         Hello ! C# 
         

Note: Default constructor executed twice, but static constructor invoked only once even non-parametrized constructor called 2 times. 

Note: We can not create an object of the class which has private constructor.

Q. ref vs out keyword

Ref and out keyword in C# is use to pass variables by reference.

Ref is 2 way from caller to callee and back.
//Passing by val
static void Main(string[] args)
        {
            int valinit = 20;
            Add(valinit);
            Console.WriteLine(valinit); // Output = 20
           
        }

        public static void Add(int val)
        {
            val = val + 10;
        }

//Passing by ref keyword
static void Main(string[] args)
        {
            int valinit = 20;
            Add(ref valinit);
            Console.WriteLine(valinit); // Output = 30, because reference is updated in Add() method.
           
        }

        public static void Add(ref int val)
        {
            val = val + 10;

        }

Out is one way , from callee to caller.
Out parameter must be assign before using it.
//Passing by out keyword
static void Main(string[] args)
        {
            int valinit = 20;
            Add(out valinit);
            Console.WriteLine(valinit); //Output = 15, as out variable is defined in Add() method 
           
        }

        public static void Add(out int val)
        {
            val = 5; // You must assign value to out parameter
            val = val + 10;

        }

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.
Let's 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.

Important ASP.Net Interview Questions and Answers for Experienced Developer

C# 6.0 new features

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 anywhere 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 the current scope where it is defined. A 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 the 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 the 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 the compiler about what to do before actual compilation.

For Eg:
Using below code you can tell the compiler to execute 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#?


A 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 an 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.
An object of the class holds the reference to the memory.
A struct does not support inheritance but class support.
A struct can not have default constructor but a class has.


Q. Primitive data type vs non-primitive data type

A primitive data type is predefined by the system for eg- byte, short, int, float, double long etc.
A 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 a string to integer and returns true if success else returns 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 a newly created object. Generally, hold a temporary object.

Generation 1: It contains an object of long live duration and transfers to Generation 2.

Generation 2: It contains longest-lived object, generally object at the application level.


Garbage Collector Phases:
Marking Phase: In this phase, GC finds and create a 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 a dead object.

Q. Constant vs Readonly


Const Keyword

  • Const is purely constant and can not be changed through out the application life cycle.
  • Const requires a value when declared.
Readonly Keyword
  • Readonly may or may not require a value when declared.
  • Readonly value can be changed in static constructor only.



class Program
    {
        public const int meter=10; //Comple time constant
        public static readonly string TableName; //Runtime constant

       static Program()
        {
            TableName = "Employee_Tbl"; //We can assign readonly value in constructor or any other intial point.
        }
        static void Main(string[] args)
        {
            
            //Code
        }

    }

Read only is better than const in context of performance.

Q. ref vs out Keyword


Ref and out keyword in C# is use to pass variables by reference.

Ref is 2 way from caller to callee and back.
//Passing by val
static void Main(string[] args)
        {
            int valinit = 20;
            Add(valinit);
            Console.WriteLine(valinit); // Output = 20
           
        }

        public static void Add(int val)
        {
            val = val + 10;
        }

//Passing by ref keyword
static void Main(string[] args)
        {
            int valinit = 20;
            Add(ref valinit);
            Console.WriteLine(valinit); // Output = 30, because reference is updated in Add() method.
           
        }

        public static void Add(ref int val)
        {
            val = val + 10;

        }

Out is one way , from callee to caller.
Out parameter must be assign before using it.
//Passing by out keyword
static void Main(string[] args)
        {
            int valinit = 20;
            Add(out valinit);
            Console.WriteLine(valinit); //Output = 15, as out variable is defined in Add() method 
           
        }

        public static void Add(out int val)
        {
            val = 5; // You must assign value to out parameter
            val = val + 10;

        }

Q. dispose vs finalize vs using block



Dispose method belongs to IDisposable interface.
IDisposable interface. has only one method called "Dispose()"
Dispose() method can be controlled i.e. we can call whenever we want to dispose an object.

public void Dispose()
{
GC.SupressFinalize(this);//This method will remove the object from Finalize queue and will overtake this to dispose method.
}


When we call Destructor , at run time it is going to convert into Finalize or we can say that it will override Finalize method. And that object for which destructor is being called is going to add in Finalize queue.

It will be like
protected override void Finalize()

So we can say that using destructor, Finalize method can be implemented.

GC.collect() - Deallocate all the inactive object memory. It is expensive operation.

Program objP = new Program();
objP = null; //It means now object is inactive and it can be free from memory by GC.


Using block will automatically take care of Dispose() method.

using(Program objP = new Program())
{
//Write code here
}

We can use Database connection with using block.

Good Practice:


  1. Follow using statement to make sure Dispose is called.
  2. Do not implement Finalize or Call Destrcutor unless require.


Q. String vs StringBuilder



String
String Builder
String is immutable.
String Builder is mutable.

String Builder is better when manipulating heavy string.

static void Main(string[] args)
        {
            string message = "Hello !";
            message += " How ";
            message += " are ";
            message += " you? ";
            Console.WriteLine(message);

        }

//String builder
       static void Main(string[] args)
        {
            StringBuilder strMessage = new StringBuilder("Hello");
            strMessage.Append(" How");
            strMessage.Append(" are");
            strMessage.Append(" you?");
            Console.WriteLine(strMessage);
        }



Q. Delegate and Events in C#



A delegate holds the reference of a method.

public delegate void AddPtr(int a, int b);

        static void Main(string[] args)
        {
             
            AddPtr objPtr = new AddPtr(Add);
            //Either we can call via this
            objPtr.Invoke(10, 5);
            //Or we can call via this
            objPtr(20, 7);        }

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

        }

Q. IEnumerable vs IEnumerator


These are the interfaces which help to loop through the collection. Also IEnumerable uses IEnumerator internally.

Lets see below example of C# code.

     List<string> productList = new List<string>();
            productList.Add("TV");
            productList.Add("Mobile");
            productList.Add("Laptop");
            productList.Add("Audio system");
            productList.Add("Tablet");

            IEnumerable<string> enumlist = (IEnumerable<string>)productList;
            foreach (string p in enumlist)
            {
                Console.WriteLine(p);
            }

            IEnumerator<string> enumaratorlist = productList.GetEnumerator();
            while (enumaratorlist.MoveNext())
            {
                Console.WriteLine(enumaratorlist.Current);

            }

Q. Generic, Collection and Indexer in C#


Generic introduces in C# 2.0, Generic is not bound with any data type.

Code to check 2 values without generic
static void Main(string[] args)
        {
            
            bool result = Check.IsEqual("20""10");
            if (result)
            {
                Console.WriteLine("Equal");
            }
            else
            {
                Console.WriteLine("Not Equal");
            }
            
        }
    }

   public class Check
   {
public static bool IsEqual(object a, object b) //Here boxing/unboxing rule will apply, which is not recommended for such a small comparison
       {
           return a == b;
       }
        
   }




Code to check 2 values with generic
static void Main(string[] args)
        {
            
            bool result = Check.IsEqual("20""10");
            if (result)
            {
                Console.WriteLine("Equal");
            }
            else
            {
                Console.WriteLine("Not Equal");
            }
            
        }
    }

   public class Check
   {
        
       public static bool IsEqual<T>(T a, T b)
       {
           return a.Equals(b);
       }
   }




Output for given C# code

1. What is the output for below sample code:


            string a = new string(new char[] { 'O', 'k' });
            string b = new string(new char[] { 'O', 'k' });

            Console.WriteLine(a == b);
            Console.WriteLine(a.Equals(b));
            object c = a;
            object d = b;
            Console.WriteLine(c == d);
            Console.WriteLine(d.Equals(d));


True, True, False, True

Important ASP.Net Interview Questions and Answers for Experienced Developer

C# 6.0 new features

Keep following SharePointCafe.Net for upcoming blogs.


Comments

Popular