Saturday 22 February 2014

covariance and contra variance in C#.

Covariance:-
Suppose  S is subclasses of class A, type X is covariant if X<S> allows a reference conversion to
X<A>.
In other words, type MyClass<T> is covariant if the following is legal:
MyClass<int> a = someValue;
MyClass<object> o = a;


Tuesday 18 February 2014

Why we used two interface IEnumerator and IEnumerable in Collection?

public interface IEnumerator            // provide structure for traversal in collection.
{
bool MoveNext();
object Current { get; }
void Reset();
}

public interface IEnumerable     // access the IEnumerator instant  for travelsal operation.
{
IEnumerator GetEnumerator();
}
question is that why we used two different interface for traversal in collection.

IEnumerable provides flexibility  in the iteration logic can be farmed off to another class. Moreover, it means that several consumers can enumerate the collection at once without interfering with each other.

Take example: IEnumerator is like a book. IEnumerable is like a reader. You can have many readers reading the same book, and each of them on a different page.

Two main Difference :

1. IEnumerable is Sugar-coated internally to IEnumerator . But IEnumerable has easy syntax compare to
    IEnumerator for iteration of list.

     IEnumerable<int> ie = (IEnumerable<int>)ls;  
            foreach (var item in ie)      //IEnumerable used the foreach syntax and it is easy to write.
            {
                Console.WriteLine(item);
            }
    if you use IEnumerator then

     IEnumerator<int> iet = ls.GetEnumerator();
            while (iet.MoveNext())                 // manually do the iteration
            {
                Console.WriteLine(iet.Current);
           }
2. IEnurator preserve state of Object which are using for iteration. But IEnumerable is not preserve state of       Object(means if you are inside of foreach statement and you called other function then the state of object       which are currently display are not presrve in calling function).

For More  Click Here