Saturday, January 12, 2013

Collections in .Net

NameSpace: System.Collections
The .NET Framework provides specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces, and these interfaces may be inherited to create new collection classes that fit more specialized data storage needs.
Closely related data can be handled more efficiently when grouped together into a collection. Instead of writing separate code to handle each individual object, you can use the same code to process all the elements of a collection. To manage a collection, use the Array class and the System.Collections classes to add, remove, and modify either individual elements of the collection or a range of elements. An entire collection can even be copied to another collection.
Some Collections classes have sorting capabilities, and most are indexed. Memory management is handled automatically, and the capacity of a collection is expanded as required. Synchronization provides thread safety when accessing members of the collection. Some Collections classes can generate wrappers that make the collection read-only or fixed-size. Any Collections class can generate its own enumerator that makes it easy to iterate through the elements.
Collection types are the common variations of data collections, such as hash tables, queues, stacks, dictionaries, and lists.
Collection Classes have the following properties:-
• Collection classes are defined as part of the System.Collections or System.Collections.Generic namespace.
• Most collection classes derive from the interfaces ICollection, IComparer, IEnumerable, IList, IDictionary, and IDictionaryEnumerator and their generic equivalents.
• Generic collection classes provide increased type-safety and in some cases can provide better performance, especially when they store value types. For more information, see Benefits of Generics (C# Programming Guide). 
The .NET Framework 2.0 introduced the notion of generics. In the .NET Framework 1.x, most of the collection classes stored System.Object references. This meant that every time you extracted an item out of a collection you would have to cast it back to its original type (and if you developed a library, the consumer of that library was required to know what those types were). This cast had a performance impact, especially when storing value types, as adding one to a collection required it first to be boxed into a System.Object and later unboxed when pulled out of the collection and cast back to its original type.
Some Collection Types: Array, ArrayList, Hastable, SortedList, Queue & Stack
Array: 
• The Array class is not part of the System.Collections namespaces. However, it is still a collection because it is based on the IList interface.
• The rank of an Array object is the number of dimensions in the Array. An Array can have one or more ranks.
• Unlike the classes in the System.Collections namespaces, Array has a fixed capacity. To increase the capacity, you must create a new Array object with the required capacity, copy the elements from the old Array object to the new one, and delete the old Array.
• An Array can have multiple dimensions.
• An Array of a specific type (other than Object) has better performance.
ArrayList:
• An ArrayList is a sophisticated version of an array.
• The capacity of an ArrayList is automatically expanded as required.
• ArrayList provide methods that add, insert, or remove a range of elements. In Array, you can get or set the value of only one element at a time.
HashTable:
• The Hashtable class implement the IDictionary interface. Each element in these collection is a key-and-value pair. A key cannot be null, but a value can be.
• 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, generated using a hash function and based on the key of the element.
• A hash function is an algorithm that returns a numeric hash code based on a key. The key is the value of some property of the object being stored. A hash function must always return the same hash code for the same key. It is possible for a hash function to generate the same hash code for two different keys, but a hash function that generates a unique hash code for each unique key results in better performance when retrieving elements from the hash table.
• Each object that is used as an element in a Hashtable must be able to generate a hash code for itself using an implementation of the GetHashCode method. However, you can also specify a hash function for all elements in a Hashtable by using a Hashtable constructor that accepts an IHashCodeProvider implementation as one of its parameters.
• When an object is added to a Hashtable, it is stored in the bucket that is associated with the hash code that matches the object's hash code. When a value is being searched for in the Hashtable, the hash code is generated for that value, and the bucket associated with that hash code is searched.
SortedList:
• The System.Collections.SortedList class is similar to the Hashtable class implements from the interface IDictionary, but they maintain their elements in sort order by key, and they do not have the O(1) insertion and retrieval characteristic of hash tables.
• Elements are sorted according to an System.Collections.IComparer implementation (for nongeneric SortedList)
• Each class provides properties that return collections containing only the keys or only the values.
Queue:
• Queues are useful for storing messages in the order they were received for sequential processing. This class implements a queue as a circular array. Objects stored in a Queue are inserted at one end and removed from the other. The capacity of a Queue is the number of elements the Queue can hold. As elements are added to a Queue, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize.
• The growth factor is the number by which the current capacity is multiplied when a greater capacity is required. The growth factor is determined when the Queue is constructed. The default growth factor is 2.0. The capacity of the Queue will always increase by at least a minimum of four, regardless of the growth factor. For example, a Queue with a growth factor of 1.0 will always increase in capacity by four when a greater capacity is required.
• Thread Safety: Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe. To guarantee the thread safety of the Queue, all operations must be done through the wrapper returned by the Synchronized method.
• Queue accepts null as a valid value and allows duplicate elements.
Stack: 
• Represents a simple last-in-first-out (LIFO) non-generic collection of objects. tack is implemented as a circular buffer. The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation. If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation.
• Stack accepts null as a valid value and allows duplicate elements.
• Thread Safety: Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe. To guarantee the thread safety of the Stack, all operations must be done through the wrapper returned by the Synchronized method.
• Three main operations can be performed on a Stack and its elements:
-Push inserts an element at the top of the Stack.
-Pop removes an element at the top of the Stack.
-Peek returns an element at the top of the Stack but does not remove it from the Stack.


Collections Interfaces:


System.Collections.IEnumerable:
It exposes the enumerator, which provides a collection like behavior to user defined classes. 
Methods:
GetEnumerator() - It returns the enumerator object that can be used to iterate through the collection. It allows using the foreach statement. Enumerators only allow reading the data in the collection.


System.Collections.ICollection:
ICollection interface specifies a method for getting the size of collection, creating enumerators on a collection and managing synchronized access to all non-generic collections. It is a base interface for classes in the System.Collections namespace. 
Properties:
• Count - It returns the number of elements contain by ICollection.
• IsSynchronized - It returns true if access to the ICollection is synchronized.
• SyncRoot - It returns an object that can be used to synchronize access to the ICollection.
Methods:
• CopyTo() - The method copies the elements of the ICollection object to any array, starting at a particular Array index. If .NET is unable to cast source type to destination, then it throws ArrayTypeMismatchException exception.

System.Collections.IList:
IList interface represents the collection of objects that can be individually accessed by index. The implementation of IList falls into three categories: read-only, fixed-size, and variable-size. A read only IList cannot be modified. A fixed size IList does not allow the addition or removal of elements, but it allows the modification of the existing elements. A variables size IList allows the addition, removal, and modification of elements. 
Properties:
• IsFixedSize - It returns true if IList has fixed size.
• IsReadOnly - It returns true if IList is read only.
Methods:
• Add(object value) - It adds the item into the IList.
• Clear() - It removes the all items from the IList.
• Contains(object value) - It returns true if IList contain a specific value. This method uses the Equals and CompareTo methods to determine whether an item exists.
• IndexOf(object value) - It returns the index of a specific item in the IList. This method also uses the Equals and CompareTo methods to determine whether an item exists.
• Insert(int index, object value) - It inserts an item to the IList at specific index. If index equals the number of items in the IList, then value is appended to the end, but if index greater then the number of items in the IList or less then zero, then it throws ArgumentOutOfRangeException exception. If you try to insert item in the read-only or fixed size IList then it throws NotSupportedException exception.
• Remove(object value) - It removes the first occurrence of a specific object from the IList. If you try to remove value from read only or fixed size IList, then it throws NotSupportedException.
• RemoveAt(int index) - It removes an item at the specified index. It throws ArgumentOutOfRangeException exception for invalid index in list and throws NotSupportedException exception for read only and fixed size IList.

System.Collections.IDictionary:
It represents a collection of key/value pairs. IDictionary interface is implemented by classes that supports collections of associated keys and values. Each element in a key/value pair is stored in a DictionaryEntry object. It allows the contained keys and values to be enumerated, but it does not imply any particular sort order.
Properties:
• IsFixedSize - It returns true if IDictionary object has a fixed size.
• IsReadOnly - It returns true if IDictionary object is read only.
• Keys - It returns ICollection object containing keys of the IDictionary object.
• Values - It returns ICollection object containing values of the IDictionary object.
Methods:
• Add(object key, object value) - Adds an element with the specified key and value into the IDictionary object.
• Clear() - It removes all elements from the IDictionary object.
• Contains(object key) - It returns true if IDictionary object contains an element with the specified key.
• GetEnumerator() - It returns an IDictionaryEnumerator object for the IDictionary object.
• Remove(object key) - It removes the element with the specified key from the IDictionary object.

Friday, January 11, 2013

Modifiers in C#


Access Modifiers: Access modifiers are keywords used to specify the declared accessibility of a member or a type. This section introduces the four access modifiers: public, protected, internal & private
The following five accessibility levels can be specified using the access modifiers:
  • public: Access is not restricted.
  • 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.
  • private: Access is limited to the containing type.

Other Modifiers: 


  • abstract - Indicates that a class is intended only to be a base class of other classes.
  • const - Specifies that the value of the field or the local variable cannot be modified.
  • event - Declares an event.
  • extern - Indicates that the method is implemented externally.
  • new - Hides an inherited member from a base class member.
  • override - Provides a new implementation of a virtual member inherited from a base class.
  • partial - Defines partial classes, structs and methods throughout the same assembly.
  • readonly - Declares a field that can only be assigned values as part of the declaration or in a constructor in the same class.
  • sealed - Specifies that a class cannot be inherited.
  • static - Declares a member that belongs to the type itself instead of to a specific object.
  • unsafe - Declares an unsafe context.
  • virtual - Declares a method or an accessor whose implementation can be changed by an overriding member in a derived class.
  • volatile - Indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.

Thursday, January 10, 2013

What is an Interface, Abstract Class? What are the differences between them?



Interface - Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. An interface represents a contract, in that a class that implements an interface must implement every aspect of that interface exactly as it is defined.

Abstract Class - Abstract classes are closely related to interfaces. They are classes that cannot be instantiated, and are frequently either partially implemented, or not at all implemented. Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.

The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

Differences between Interface and Abstract Class:
Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast
Adding functionality (Versioning)
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants
No fields can be defined in interfaces
An abstract class can have fields and constants defined

Tuesday, January 8, 2013

OOP - Object Oriented Programming Basics


Object-oriented programming (OOP) is a programming paradigm that represents concepts as "objects" that have data fields (attributes that describe the object) and associated procedures known as methods. Objects, which are instances of classes, are used to interact with one another to design applications and computer programs.

Encapsulation - Encapsulation refers to the creation of self-contained modules that bind processing functions to the data. These user-defined data types are called "classes," and one instance of a class is an "object."

Abstraction - Abstraction is an emphasis on the idea, qualities and properties rather than the particulars (a suppression of detail). The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects.

Inheritance - Classes are created in hierarchies, and inheritance allows the structure and methods in one class to be passed down the hierarchy. That means less programming is required when adding functions to complex systems. If a step is added at the bottom of a hierarchy, then only the processing and data associated with that unique step needs to be added. Everything else about that step is inherited. The ability to reuse existing objects is considered a major advantage of object technology.

Polymorphism - Polymorphisms is a generic term that means 'many shapes'. More precisely Polymorphisms means the ability to request that the same operations be performed by a wide range of different types of things.

Overloading - Overloading is the ability to give different means or different definitions in the form of Method Overloading(differentiate them by defining different type of input parameters) and Operator Overloading.

Overriding or Method Overriding - Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.