Saturday 26 March 2011

Delegates and events Interview Questions

What’s a delegate?

A delegate object encapsulates a reference to a method.

What are the different types of delegates?

Two types:

1. Unicast delegate: Delegate which is used to call a single method is called unicast delegate.
2. Multicast delegate: Delegate which is used to call a more than one method is called multicast delegate.


Do events have return type ?

No events do not have return type.

Can event’s have access modifiers ?

Event’s are always public as they are meant to serve every one registering to it.But we can use access modifiers in events. we can have events with protected keyword which will be accessible only to inherited classes. We can have private events only for object in that class.

Can we have shared events ?

Yes we can have shared event’s note only shared methods can raise shared events.

What’s difference between delegate and events?

1. Actually events use delegates in bottom. But they add an extra layer on the delegates, thus forming the publisher and subscriber model.
2. As delegates are function to pointers they can move across any clients. So any of  the clients can add or remove events ,  which can be pretty confusing. But events give the extra protection by adding the layer and making it a publisher and subscriber model.

What is an Asynchronous delegate?

Delegates used to invoke method that takes long time to execute.

How to create events for a control? What are custom events?


Declare a public delegate and set of events to listen from.
public delegate void CarEventHandler(string msg);
public event CarEventHandler AboutToBlow;
public event CarEventHandler BlewUp

Steps to use delegate?

1. Create delegate: delegate returntype nameofdelegate(parameter passed to method);
2. Create instance of delegate: delname objname = new delname(classobj.nameofmethod);
3. Invoke delegate: datatype parameter of method = objname("value to pass ");

What is invocationlist?

Multicast delegate contains internal lis tof delegate. This list is called invocationlist.

** += and -= operators are use dto add and remove delegates from invocationlist.

Reflection Interview Questions

What is reflection?

All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection.

Which namespace is used in Reflection?
System.Reflection

Which namespace is used to built new types at runtime?


System.Reflection.Emit

Advantages of Reflection?

1. Used to access attribute sin programs metadata.
2. Examine and instantiate types in an assembly.
3. To perform late binding, accessing methods on the types created at runtime.

What is attributes? Types of attributes?

Attributes are the declarative tags that convey information at runtime.
Some predefind attributes are Serializable, Deserializable

Types:

1. Standard: Predefined attributes in .Net framework

eg.

 class attributeparamsdemo
    {
        [DllImport("user32.DLL", EntryPoint = "MessageBox")]
        static extern int MessageDialog(int hwnd, string msg, string caption, int msgtype);
        static void Main(string[] args)
        {
            MessageDialog(0, "MessageDialog called !", "DllImport demo", 0);

        }
    }
This will display the messagebox as output with the message "MessageDialog called ! " , caption  "DllImport demo" and
Ok button as msgtype 0 contains ok button.

2. Custom: Attributes defined by user

eg.

namespace demo_customattribute
{
    [AttributeUsage(AttributeTargets.All,Inherited = false,AllowMultiple = true)]
    public class bookattribute : System.Attribute
    {
        private string name;

        public string version;

        public bookattribute(string str)
        {
            name = str;
            version = "1.5";
        }
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }

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

           book b = new book();
           Type t = b.GetType();
           Attribute[] ats = Attribute.GetCustomAttributes(t);
           foreach (Attribute a in ats)
           {
               if (a is bookattribute)
               {
                   bookattribute author = (bookattribute)a;
                   Console.WriteLine("AuthorName = " + author.Name);
                   Console.WriteLine("Version = " + author.version.ToString());
               }
           }
           Console.ReadLine();
        }
    }
        [bookattribute("balaguruswamy", version = "1.1")]
        [bookattribute("ABC", version = "1.2"), bookattribute("yashwant")]
        public class book
        {
            private string bkname;

            public string Bkname
            {
                get { return bkname; }
                set { bkname = value; }
            }
        }
               
    }
[AttributeUsage(AttributeTargets.All,Inherited = false,AllowMultiple = true)]
<b> AttributeTargets </b>indicates that this attribute can be applied to all program elements.
<b>Inherited</b> indicates whether the attribute can be inherited by classes that are derived from the classes to which attribute is applied.
<b>AllowMultiple</b>indicates whether multiple instances of attribute can exists on an element.




Serialization Interview Questions

What is serialization and Deserialization?
Serialization is the process of converting an object into a stream of bytes.
Deserialization is the opposite process i.e. it creats an object from a stream of bytes.

Serialization /Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).

What are the types of Serialization?

There are 4 types of srailization.

1. Binary Serialization: It writes the contents of an object into binary form to a file.
2. SOAP Serialization: It writes the contents of an object into platform-agnostic format.
3. XML Serialization: It writes the contents of an object into a XML file.
4. Custom Serialization: In some cases, the default serialization techniques provided by .NET may not be sufficient in real life.  This is when we require implementing  custom serialization.   It is possible to implement custom serialization in .NET by implementing the ISerializable interface.  This interface allows an object to take control of its own serialization and de-serialization process.

Does the .NET Framework have in-built support for serialization?

There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

Why is XmlSerializer so slow?
There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application.

Why do we get errors when we try to serialize a Hashtable?

XmlSerializer will refuse to serialize instances of any class that implements IDictionary,
e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.

what are the namespaces we use to implement serialization?

using System.Xml.Serialization; -> for xml
using System.Runtime.Serialization.Formatters.Binary; -> for binary
using System.Runtime.Serialization.Formatters.Soap; -> for soap



Wednesday 23 March 2011

Static Keyword related Questions

What is a Static class? What are its features?

Static class is a class which can be accessed without creating an instance of the class.
Important Features:
a. Static class only contains static members.
b. Static class need not to be instantiated.
c. Static classes are sealed by default and therefore cannot be inherited.

What is sealed class? What are its features?

Sealed classes are those classes which can not be inherited and thus any sealed class member can not be derived in any other class.
A sealed class cannot also be an abstract class.
In C# structs are implicitly sealed; therefore, they cannot be inherited.

What is a life span of a static variable?

A static variable’s life span is till the class is in memory.

Why main function is static?
To ensure there is only one entry point to the application.

What is static member?

static members are the members that can be called directly from the class name, it doesnt require the object of the class.

What is static constructor?

When constructors are used to set the value of a type’s data at the time of construction, if we want the value of such static
data is to be preserved regardless of how many objects of the type are created, we have to define the constructor with static keyword.


Can you declare the override method static while the original method is non-static?

No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

Polymorphism Interview questions

What is Polymorphism?

Ability to provide different implementation based on different number/type of parameters that
are called by the same name.


public class DrawingShape
{
public virtual void Draw()
{
Console.WriteLine("Drawing shapes.");
}
}
public class Square : DrawingShape
{
public override void Draw()
{
Console.WriteLine("Drawing square.");
}
}
public class rectangle : DrawingShape
{
public override void Draw()
{
Console.WriteLine("Drawing rectangle.");
}
}

public class baseclass
{
public static void Main()
{
DrawingShape[] ds = new Drawingshape[2];

ds[0] = new Square();
ds[1] = new rectangle();


foreach (DrawingShape s in ds)
{
ds.Draw();
}
}
}

In this we have drawingshape class having virtual method Draw() whic his overriden in the Square and rectangle class.


In which cases you use override?

If the base class member is declared as virtual or abstract then to override these members in derived class
we use override leyword in derived class.

Can you override private virtual methods?

No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access

What does the keyword virtual mean in the method definition?

It means the method can be over-ridden in derived class.

Can you declare the override method static while the original method is non-static?

No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

How a base class method is hidden?

We can Hide a base class method by declaring a method in derived class with keyword new.

What is the difference between virtual and abstract method?

Abstract methods doesnot provide implementation of method whereas virtual method provides the implementation.

Interface Interview Questions

What is an Interface?

An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body.

Important point:

a. By default it is public. We cannot specify any access specifier in interface.
b. It doesnot contain implementation of method.
[code]
using System;
namespace Interfaces
{
interface Icustdetails
{
void GetName();
void GetID();
}
public class Demo : Icustdetails
{
public void GetName()
{
Console.WriteLine("Gives the name");
}

public void GetID()
{
Console.WriteLine("gives the ID");
}

public static void Main()
{
Demo obj_demo = new Demo();
demo_obj.GetName();
demo_obj.GetID();
}
}
}

[/code]
In this example we have declared an interface ICustdetails with the abstract methods GetName and GetID. Now their is a class demo
which is inherited from Icustdetails so,it has to provide the implementation of these methods. If it doesn't provide the implementation
then compile time error is thrown.

What do you mean by "Explicitly Implemeting an Interface"?

If a class is implementing the inherited interface member by prefixing the name of the interface, then the class is "Explicitly Implemeting an Interface member". 

Can we declare private methods inside an Interface?

No, they all must be public, you are not allowed to specify any accessibility, its public by default.

Can you create an instance of an interface?
No, you cannot create an instance of an interface.

A class inherits from 2 interfaces and both the interfaces have the same method name as shown below.
How should the class implement the GetName method for both IOrderdetails and ICustdetails interface?

[code]
  interface ICustdetails
    {
         void GetName(int n);
    }
    interface IOrderdetails
    {
        void GetName(int n);
    }
    class Orders : ICustdetails, IOrderdetails
    {
       //how we implement method of both interface
    }
[/code]

To implement the GetName() method we use the fully qualified name as shown below.
To call the respective interface GetMethod method type cast the Orders object to the respective interface and then call the  method.
[code]
 interface ICustdetails
    {
         void GetName(int n);
    }
    interface IOrderdetails
    {
        void GetName(int n);
    }
    class Orders : ICustdetails, IOrderdetails
    {
        void ICustdetails.GetName(int n)
        {
           
        Console.WriteLine("These are customer details");
          
        }
        void IOrderdetails.GetName(int n)
        {           
            Console.WriteLine("These are order details");
          
        }
    }
 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter customer number");
            int n = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter order number");
            int o = int.Parse(Console.ReadLine());
            Orders obj = new Orders();
            ICustdetails cd = obj;
            IOrderdetails od = obj;
            cd.GetName(n);
            od.GetName(o);
            Console.ReadLine();

        }
    }

[/code]

If a class inherits an interface, what are the options available for that class?
Their are 2 options available in this case:

a. A class has to implement all the members of that interface.

namespace demo_interface
{
interface Bank
{
void savingaccount();
Void currentaccount();
}

class bankdetail : Bank
{
public void savingaccount()
{
Console.WriteLine("savingaccount Method");
}
public void currentaccount()
{
Console.WriteLine("currentaccount Method");
}
}
}

Option 2: class must use the abstract keyword

namespace demo_interface
{
interface Bank
{
void savingaccount();
Void currentaccount();
}


abstract class bankdetail : Bank
{
abstract public void savingaccount();
abstract public void savingaccount();
public void bankdetailmethod()
{
Console.WriteLine("Bankdetail Method");
}
}
}



Inheritance Interview Questions

What is Inheritance?

Inheritanc eprovides reusability and extensibility features.
Reusability:  Allow us to use a a component,class and even methods in different applications.
Extensability: Means to extend a module as a new need arises.

Does C# support multiple class inheritance?
No, C# supports doesn't support multiple class inheritance.We can use interface in place of that.

Do structs support inheritance?
No, structs do not support inheritance, but they can implement interface.

Is the following code legal?
class Employee
{
//code for Employee class
}
class Department
{
//code for Department claSS
}
class Clerk : Employee, Department
{
}


NO, Because c# doesnot support multiple inheritance so one class cannot inherit more then one class. Though if Employee and Department are interfaces rather than class then it is possible.

What will be the output of the following code? (very important question asked in almost every interviews)
public class Bank
{
public Bank()
{
Console.WriteLine("I am a bank class");
}
}
public class account : Bank
{
public account()
{
Console.WriteLine("I am a account class");
}
static void Main()
{
account a = new account();
}

}
Output:
I am a bank class
I am a account class

Base class constructor is always called before the child class.


Array Interview questions

What is an Array?
An array is a type of data structure that is used to store variables of same data type.

What are the different types of arrays?
1. Single-Dimensional

int[] arrayname = new int[size of array];

2. Multidimensional: int[ , ] arrayname = new int[2,3];

3. Jagged : It is array of array.
int[][] arrayname = new int[2][];


Arrays are value types?yes or no

no,Arrays are reference types.

What is the base class for Array types?
System.Array



Tuesday 22 March 2011

Collection Interview questions

what is Collection?

It is the set of of similar typed objects grouped together.

 Give examples of Generic and non-generic collections?

Non-Generic collection comes under System.Collections namespace.
eg: Arraylist, queue, stack, Sorted list, Hashtable etc

Generic collection comes under System.Collections.Generic namespace.
eg:generic list, generic queue, generic stack etc

What is an ArrayList?

The ArrayList object is a collection of items containing a single data type values.

What is a HashTable?

The Hashtable object contains items in key/value pairs. The keys are used as indexes, and very quick
searches can be made for values by searching through their keys.

What is SortedList?

The SortedList object contains items in key/value pairs. A SortedList object automatically sorts items in alphabetic or numeric order.

What’s the .NET collection class that allows an element to be accessed using a unique key?

HashTable.

What class is underneath the SortedList class?

A sorted HashTable.

Where are all .NET  Collection classes located ?

System.Collection namespace has all the collection classes available in .NET.

What’s difference between HashTable and ArrayList ?

You can access array using  INDEX value of  array , but  how many times you know the
real value of index.Hashtable provides way of accessing the index using a user identified KEY value , thus removing the INDEX problem.

What are queues and stacks ?
Queue is for  first-in, first-out (FIFO) structures. Stack  is for last-in, first-out (LIFO) structures.

What is the difference between array and arraylist?

1. Size of array is always fixed and should be defined at the time of instantiation of array whereas arraylist size grows dynamically.
2. In array we can store elements of single type of data type whereas in arraylist we can store elements of data types.

Boxing and unboxing interview questions

What do you mean by boxing and un-boxing?
C# provides us with Value types and Reference Types. Value Types are stored on the stack and Reference types
are stored on the heap. The conversion of value type to reference type is known as boxing and converting
reference type back to the value type is known as un-boxing.
e.g.
int x = 100;

object o = x ;  //  Implicit boxing
object o = (object) x; // Explicit Boxing

x = o; // Implicit Un-Boxing
x = (int)o; // Explicit Un-Boxing


What happens during the process of boxing?
Boxing is used to store value types data types in the garbage-collected heap.
Boxing is an implicit conversion of a value type to the type object or to any interface
type implemented by this value type.During this an object is created on the heap and
value is copied over their.



Access specifiers interview questions

What are the access-specifiers available in c#?
There are 5 access specifiers.
Private, Protected, Public, Internal, Protected Internal.


Are private class-level variables inherited?
Yes, but they are not accessible.

Explain about Protected and protected internal, “internal” access-specifier?
protected - Access is limited to the containing class or types derived from the containing class.

internal - Access is limited to the current assembly.

protected internal - Access is limited to the current assembly or types derived from the containing class.

When you inherit a protected class-level variable, who is it available to?
Classes in the same namespace.

Explain public and private access specifier?
public: can be accessed anywhere

private: can be accessed in the class in which it is declared.

Abstract and sealed keyword interview questions

What is an Abstract class?

An abstract class is a special kind of class that cannot be instantiated. It normally contains one or more abstract methods
or abstract properties. It provides body to a class.


What is an Sealed class?

Sealed class is a class which cannot be inherited.

<b>Can a sealed class be used as a base class?</b>
No, sealed class cannot be used as a base class. A compile time error will be generated.


When do you absolutely have to declare a class as abstract?

a. If a class contains one or more abstract method.
b. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

 Can we declare a class as sealed as well as abstract?

No, as it is against definition.A sealed class cannot be inherited but to use abstract class its necessary to inherit that class.

Can we declare a method as sealed?

In C# a method can't be declared as sealed. However when we override a method in a derived class,
we can declare the overridden method as sealed. By declaring it as sealed, we can avoid further overriding of this method.
E.g.

using System;
class MyClass1
{
   public int x;
   public int y;
   public virtual void Method()
   {
    Console.WriteLine("virtual method"); 
   }
}
class MyClass : MyClass1
{
   public override sealed void Method() 
  {
    Console.WriteLine("sealed method");  
  }   
}
class MainClass
{   public static void Main() 
    {
      MyClass1 mC = new MyClass();
      mC.x = 110;
      mC.y = 150;
      Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
      mC.Method();  
    }
}