Tuesday, November 22, 2011

Delegates and Events


What is a delegate?
Delegate is a reference type that safely encapsulates a method. Once the delegate is instantiated a method call made to the delegate would be passed to method by delegate.

How do you declare a delegate?
public delegate void SaveDelegate(Dataset Ds)

Which class are delegate type derived from?
They are derived from Delegate class.

Reason for Delegates existence or major Use of Delegate?
Delegates is a type or an object. Thus when you instantiate a delegate with method like
SaveDelegate delObj=new SaveDelegate(SomeMethod) or SaveDelegate delObj==SomeMethod
We can pass the delObj as object to other functions or use it as return type. Thus can further call the methods from the calling functions. This is also known for asynchronous callback

Difference between delegates for static method and instance method?
When wrapping instance method it references both instance and method. When used for static method it references only method.

What is multicasting in delegates?
Delegates can call more than one method when invoked, this is called as multicasting.
SaveDelegate d1=obj.SomeMethodA();
SaveDelegate d2=obj.SomeMethodB();

SaveDelegate allMethods=d1+d2

What are anonymous methods?
Methods by using which we can reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.

e.g
// Declare a delegate
delegate void Printer(string s);

class TestClass
{
    static void Main()
    {
        // Instatiate the delegate type using an anonymous method:
        Printer p = delegate(string j)
        {
            System.Console.WriteLine(j);
        };

        // Results from the anonymous delegate call:
        p("The delegate using the anonymous method is called.");
    }
}

Guidelines of when to use delegate instead of Interface from MSDN/
Use a delegate when:
·         An eventing design pattern is used.
·         It is desirable to encapsulate a static method.
·         The caller has no need access other properties, methods, or interfaces on the object implementing the method.
·         Easy composition is desired.
·         A class may need more than one implementation of the method.

Use an interface when:
·         There are a group of related methods that may be called.
·         A class only needs one implementation of the method.
·         The class using the interface will want to cast that interface to other interface or class types.
·         The method being implemented is linked to the type or identity of the class: for example, comparison methods.

Friday, November 18, 2011

Threading Concepts



Why do we use Threading?
Threading enables for multiple processing so that you can do more than one operation at the same point of time.

How to create a new Thread?
You create a new thread by declaring a variable of type Thread and calling the constructor, providing the name of the procedure or method that you want to execute on the new thread.
System.Threading.Thread newTh = new Thread(myMethod);

Does background thread keeps running even after last foreground thread has stopped.
No, background thread stops as soon as the last foreground thread has stopped.


If you want to call a method of a control from another thread than the thread it was created from, what must you use?
Ideally methods of controls should be called only on threads in which they were created, but use Invoke in cases where required otherwise.

Why should we not use lock to lock threads that manipulate forms or controls?
Forms and control methods call back to the calling procedure, thus it will create a deadlock.

How to start Async Operation of Background Worker?
Use the RunWorkerAsync() which calls in the DoWork() event of background worker.
Use CancelAsync() to cancel the Async operation.

How do you return values from Multithreaded procedures?
Initialize the BackgroundWorker. Inside DoWork get the argument of object from e.Argument and then call in the calculation method and assign the value to e.Result.Get the value back into use in RunWorkerCompleted event.

What does lock() statement do?
It can be used to ensure that a block of code runs to completion without interruptions from other threads. i.e. getting mutually exclusive lock for a given object for duration of the code block.

What does argument in lock() statement signify?
It gives the scope of the lock. Its sole purpose is to identify the resources being shared among multiple threads.
Thus don’t use lock(this) if the instance can be accessed publicly. Avoid locking on the public data types. Also avoid putting lock on string litterals as they are interned by CLR i.e. a single instance across application. Its recommended to put lock in protected or private members.

What are Monitors?
They also prevent from simultaneous execution of block of code.
Adv.
Enter method allows one and only one thread to enter, Exit releases the rights.
Object obj=new Object()
Threading.Monitor.Enter(obj);
DoSomething();
Threading.Monitor.Exit(obj);

Which is preferred lock or Monitor?
Lock is preffered as the lock is released implicitly in Monitor we use finally block to ensure release of the lock.

What is WaitOne(), WaitAll(), WaitAny()?
WaitHandle.WaitOne() causes the thread to wait until a single event becomes signaled, WaitHandle.WaitAny() blocks a thread until one or more indicated events become signaled, and WaitHandle.WaitAll() blocks the thread until all of the indicated events become signaled.
 
What is Mutex?
Mutex are similar to Monitor but can also be used to synchronize threads across the processes.

What is Deadlock?
When two threads are trying to lock a resource where each other has already locked. Thus both go into waiting and cannot make any further progress

 What is race conditions?
Race conditions occurs when the outcome of the program depends on which of the two or more thread reaches the code block first. Thus running a program may return different results most of the times and outcome cannot be predicted

In case of Multiple Threads to enable synchronization what should be used?
Don’t use Thread.Suspend() and Thread.Resume() to synchronize. Use Mutex, Monitor in these cases.

Should we control the execution of the worker thread from main program.
No.

Should we have lock on Type objects.
Never take lock on the Types. i.e. lock(typeof(x)) as for the given type there can be only one instance per application domain.

Where should Exit() of monitor be used?
Call the Exit() always in the finally block which ensures that the lock is released. If you cannot ensure that finally will be called use Mutex instead.

Where would multiple threads be used?
Use multiple threads when threads would be performing tasks on different resources. For e.g, a background thread can be used to do I/O operations where other thread to do the network connection operation.

How can performance from lock be increased?
Use Increment method in place of lock for increased performance.

What are foreground threads and background threads?
All the threads which does not keep the managed execution environment running are called as background thread.
Threads that belong to the managed thread pool  i.e with IsThreadPoolThread property as true are background threads. All that enter managed execution environment from unmanaged code are background threads.
All threads generated by new Thread object are foreground threads.

What is a thread pool?
Thread pool is a collection of threads that can be used to perform number of tasks in background

Tuesday, November 8, 2011

Collections & Generic Collections

Why to use Generics? Why did .NET introduce generic collections?
The immediate benefit of using Generics is Type Safety. They are also improved in performance as compared to collections without generics.

Give the mapping of similar classes from Collections to Generic Collections?
·         List<T> -> Arraylist
·         Dictionary<TKey, TValue> and ConcurrentDictionary<TKey, TValue> are the generic classes that correspond to Hashtable.
·         Collection<T> is the generic class that corresponds to CollectionBase. Collection<T> can be used as a base class, but unlike CollectionBase, it is not abstract. This makes it much easier to use.
·         ReadOnlyCollection<T> is the generic class that corresponds to ReadOnlyCollectionBase. ReadOnlyCollection<T> is not abstract, and has a constructor that makes it easy to expose an existing List<T> as a read-only collection.
·         The Queue<T>, ConcurrentQueue<T>, Stack<T>, ConcurrentStack<T>, and SortedList<TKey, TValue> generic classes correspond to the respective nongeneric classes with the same names.
Collections are derived from which Classes?
To manage a collection, use the System.Array class and the classes in the System.Collections, System.Collections.Generic, and System.Collections.Concurrent namespaces to add, remove, and modify either individual elements or a range of elements in the collection.
Collections are based on the ICollection interface, the IList interface, the IDictionary interface, or their generic counterparts.

How to have efficient Thread Safe add, removing of items in Collections from Multiple Threads?
This can be achieved by using System.Collections.Concurrent namespace

What is Collection?
Collection is similar type of objects grouped together.

What are three types of Collection categorization?
·         Commonly used collections: These are the common variations of data collections, such as hash tables, queues, stacks, dictionaries, and lists. Many commonly used collections have non-generic versions, generic versions, and thread-safe generic versions.
·         Bit collections: These are collections whose elements are bit flags. They behave slightly differently from other collections.
·         Specialized collections: These are collections with highly specific purposes, usually to handle a specific type of element, such as StringDictionary.

What collection to use when you need a sequential list where the element is typically discarded after its value is retrieved?
Queue or Stack

If need random access to Items?
Use LinkedList

If Need access to elements by Index?
ArrayList, StringCollection

If Need access to elements by Key?
Use Dictionary.

If you have a requirement to have following:
One Value only: List
One Key and One Value: Dictionary
One Key and Multiple Values: NameValueCollection class

If required to sort elements?
HashTable sorted by hash values
SortedList
ArrayList and List<T> provide for sort method.

What If you need fastsearch and retrival of information?
ListDictionary is faster than Hashtable for small collections (10 items or fewer). The Dictionary<TKey, TValue> generic class provides faster lookup than the SortedDictionary<TKey, TValue> generic class. The multi-threaded implementation is ConcurrentDictionary<TKey, TValue>. ConcurrentBag<T> provides fast multi-threaded insertion for unordered data.

What If collection only string?
Use StringCollection.

Explain Enumeration in Collection?
Every enumerator is based on the IEnumerator interface or the IEnumerator<T> generic interface, which requires the following members:
·         The Current property points to the current member in the collection.
·         The MoveNext property moves the enumerator to the next member in the collection.
·         The Reset property moves the enumerator back to the beginning of the collection. Current is positioned before the first element. Reset is not available in the generic IEnumerator<T> interface.

In List<T> how is the equality compared decided?
If T implements the IEquatable<T> Interface than it uses the Equals(T) method else its uses the Object.Equals(Object) method.

Is performance of ArrayList and List identical for reference type and why?
Yes the performance of using an ArrayList and List is identical for both as there is boxing or unboxing involved in Arraylist.

For value types why is List better than ArrayList?
First, its type safe. Every value type which is entered in the ArrayList is boxed to the parent type of Object. While retrieving the same element the Object has to be unboxed. This causes an unwanted overhead. This can be removed by using the List<T>.
Is a concurrent list type provided by System.Collections.Concurrent?
The System.Collections.Concurrent namespace does not provide a concurrent list type, but it does provide a ConcurrentQueue<T> and ConcurrentStack<T> type.

What are advantadges of using Arrays over ArrayList and List<T>?
·         You can set the lower bound of Array, the lower bound of ArrayList and List is always zero
·         Multiple dimension are supported by Arrays.
·         It provides better performance than the others as Arraylist is trapped in the boxing, unboxing fundas. List can compete with performance if the Capacity attribute is good approximation of the upper bound of the List

What is a HashTable?
A Hashtable object consists of buckets that contain the elements of the collection. A bucket is a virtual subgroup of elements within the Hashtable, which makes searching and retrieving easier and faster than in most collections. Each bucket is associated with a hash code, which is generated using a hash function and is based on the key of the element.

Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be null, but a value can be.
// Create a new hash table.
        //
        Hashtable openWith = new Hashtable();

        // Add some elements to the hash table. There are no
        // duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

// The default Item property can be used to change the value
        // associated with a key.
        openWith["rtf"] = "winword.exe";
        Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

foreach( DictionaryEntry de in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
        }

openWith.Remove("doc");

What is HashSet<T>?
The HashSet<T> class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary<TKey, TValue> or Hashtable collections. In simple terms, the HashSet<T> class can be thought of as a Dictionary<TKey, TValue> collection without values.

Is Array part of System.Collections?
No.  But it’s a collection as it’s based on IList interface.

What is Rank of an Array?
Rank is the dimensions of Array.

Monday, November 7, 2011

What is Singleton and how is it implemented?

I was getting a walk through of the basics of C# when came across this good article on Singleton design pattern. Sharing few concepts which can be used during interviews or for implementations.


Singleton can be implemented in various ways, here are some of the options with their tradeoff from MSDN.
using System;

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}

This implementation has two main advantages:
·  Because the instance is created inside the Instance property method, the class can exercise additional functionality (for example, instantiating a subclass), even though it may introduce unwelcome dependencies.
·  The instantiation is not performed until an object asks for an instance; this approach is referred to as lazy instantiation. Lazy instantiation avoids instantiating unnecessary singletons when the application starts.
The main disadvantage of this implementation, however, is that it is not safe for multithreaded environments. If separate threads of execution enter the Instance property method at the same time, more that one instance of the Singleton object may be created. Each thread could execute the following statement and decide that a new instance has to be created:
 
if (instance == null)

To overcome the above error here is one more solution:
public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();
   
   private Singleton(){}
 
   public static Singleton Instance
   {
      get 
      {
         return instance; 
      }
   }
}

The only potential downside of this approach is that you have less control over the mechanics of the instantiation.
MultiThreaded Instantiation:
Static initialization is suitable for most situations. When your application must delay the instantiation, use a non-default constructor or perform other tasks before the instantiation, and work in a multithreaded environment, you need a different solution.
using System;
 
public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();
 
   private Singleton() {}
 
   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }
 
         return instance;
      }
   }
}
the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed.L
Lastly, this approach uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks. 

Types in .NET - Value Types and Reference Types

1.       The compiler embeds the type information into the executable file as metadata. The common language runtime (CLR) uses that metadata at run time to further guarantee type safety when it allocates and reclaims memory.

2.       If you want compiler to infer type which declaring keyword in used
a.        Var

3.       Two fundamental points about the type system in the .NET Framework
a.       It supports the principle of inheritance. Types can derive from other types, called base types. The derived type inherits (with some restrictions) the methods, properties, and other members of the base type. The base type can in turn derive from some other type, in which case the derived type inherits the members of both base types in its inheritance hierarchy. This unified type hierarchy is called the Common Type System (CTS).
b.      Each type in the CTS is defined as either a value type or a reference type. This includes all custom types in the .NET Framework class library and also your own user-defined types.
4.       What are structs and classes – value type or reference type
a.       Types that you define by using the struct keyword are value types; all the built-in numeric types are structs. Types that you define by using the class keyword are reference types.

5.       What are Value Types:
a.       Value types derive from System.ValueType, which derives from System.Object.
b.      Types that derive from System.ValueType have special behavior in the CLR. Value type variables directly contain their values in stack, which means that the memory is allocated inline in whatever context the variable is declared.
c.       There is no separate heap allocation or garbage collection overhead for value-type variables.

6.       What are the two main categories for Value Type
a.       Structs and Enums

7.       What’s the base type of built in Numeric Type?
a.       The built-in numeric types are structs, and they have properties and methods that you can access

8.       Can you derive from System.Int32
a.       Value types are sealed, which means, for example, that you cannot derive a type from System.Int32, and you cannot define a struct to inherit from any user-defined class or struct because a struct can only inherit from System.ValueType. However, a struct can implement one or more interfaces. You can cast a struct type to an interface type; this causes a boxing operation to wrap the struct inside a reference type object on the managed heap.

9.       What are reference Types?
a.       A type that is defined as a class, delegate, array, or interface is a reference type.
b.      At run time, when you declare a variable of a reference type, the variable contains the value null until you explicitly create an instance of the object by using the new operator, or assign it an object that has been created elsewhere by using new.

10.   What happens internal to memory when an object is created?
a.       First the reference for the object is created in the stack.
b.      When object is created with the new keyword memory is allocated in the managed heap.
c.       Types on the managed heap require overhead both when they are allocated and when they are reclaimed by the automatic memory management functionality of the CLR, which is known as garbage collection. However, garbage collection is also highly optimized, and in most scenarios it does not create a performance issue.

11.   Are array int[] i={1,2,3}, value type or reference type?
a.       All Arrays are by default reference type, derived from System.Array.

12.   How to specify a type to a literal
a.       All Literals receive type from compiler. You can explicitly specify the type by suffixing it by “f” or “F”. e.g 4.56f

13.   How to start an Enum from 1
a.  enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

14.   What can be underlying type of Enum.
a.       Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of enumeration elements is int. To declare an enum of another integral type, such as byte, use a colon after the identifier followed by the type
b.       enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
c.        The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

15.   Struts fall into which categories:
a.       Numeric Types
b.      Bool
c.       User Defined Struts.

16.   What are nullable Types in C#?
a.       Nullable types are instances of the System.Nullable<T> struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value.
b.       The syntax T? is shorthand for Nullable<T>, where T is a value type. The two forms are interchangeable. E.g int? x = null
c.        Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;

17.    What is Boxing and Unboxing?
a.       Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system, in which a value of any type can be treated as an object.

18.   Explain Boxing Conversion?
a.      
b.      Boxing a value type allocates an object instance on the heap and copies the value into the new object.
19.   What in Unboxing?
a.       Checking the object instance to make sure that it is a boxed value of the given value type.
b.      Copying the value from the instance into the value-type variable.
c.      

20.   What is the new type introduced in VS 2010.
a.       dynamic. The type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object.

21.   Comments about Var:
a.       var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
b.      var cannot be used on fields at class scope.
c.       Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);
d.      Multiple implicitly-typed variables cannot be initialized in the same statement.
e.      If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.