Monday, 21 December 2015

IEnumerable and IEnumerator in C# with real time example

We will discuss here what is IEnumerable, IEnumerator, what are differences between them, where should we use IEnumerable and where to IEnumerator, once we will finish our discussion it will be clear, which one would be best for which situation and why, so let’s see it with example
To better understand we will create a list of age
  1. List<int> ages = new List<int>();
  2. ages.Add(10);
  3. ages.Add(20);
  4. ages.Add(30);
  5. ages.Add(40);
  6. ages.Add(50);
Now convert this list to IEnumerable
  1. IEnumerable<int> age_IEnumerable = (IEnumerable<int>)ages;
  2. foreach (int age in age_IEnumerable)
  3. {
  4.     Console.WriteLine(age);
  5. }
There is nothing new, we used foreach here very straight forward, now let’s convert the ages into IEnumerator, there is a method GetEnumerator to convert a list into IEnumerator
  1. IEnumerator<int> age_IEnumerator = ages.GetEnumerator();
  2. while (age_IEnumerator.MoveNext())
  3. {
  4.     Console.WriteLine(age_IEnumerator.Current);
  5. }
As you can see here we used while rather than foreach because foreach cannot be used with IEnumerator, but still there is nothing which can suggest us when should we use IEnumerable and where to IEnumerator.
Before we go further, we should know, IEnumerable uses IEnumerator internally also have a functionGetEnumerator to convert into IEnumerator, we should use IEnumerable because it make coding easier and clearer as we can see in above example.
Now let’s discuss the main difference, IEnumerable doesn’t remember the state, which row or record it is iterating while IEnumerator remember it and we are going to see this with example by creating method PrintUpto30 and PrintGreaterThan30
Let’s first check with IEnumerator
  1. public void PrintAgeUpto30(IEnumerator<int> age_IEnumerator)
  2. {
  3.    while (age_IEnumerator.MoveNext()){
  4.       Console.WriteLine(age_IEnumerator.Current);
  5.       if (age_IEnumerator.Current > 20) {
  6.          Console.WriteLine("PrintGreaterThan30 is called");
  7.          PrintGreaterThan30(age_IEnumerator);
  8.       }
  9.    }
  10. }
  11. public void PrintGreaterThan30(IEnumerator<int> age_IEnumerator)
  12. {
  13.     while (age_IEnumerator.MoveNext())
  14.         Console.WriteLine(age_IEnumerator.Current);
  15. }
  16. // Now Call PrintUpto30 which will call PrintGreaterThan30
  17. // by using our previous age IEnumerator
  18. PrintUpto30(IEnumerator);
As we know IEnumerator persists state so once we will call PrintGreaterThan30 by passing age_IEnumerator it will print the remaining list, here is the output:
  1. 10
  2. 20
  3. 30
  4. PrintGreaterThan30 is called
  5. 40
  6. 50
Now let’s check same code with IEnumerable
  1. public void PrintUpto30(IEnumerable<int> age_IEnumerable)
  2. {
  3.     foreach (int age in age_IEnumerable){
  4.        Console.WriteLine(age);
  5.        if (age > 20){
  6.          Console.WriteLine("PrintGreaterThan30 is called");
  7.         PrintGreaterThan30(age_IEnumerable);
  8.       }
  9.    }
  10. }
  11. public void PrintGreaterThan30(IEnumerable<int> age_IEnumerable)
  12. {
  13.   foreach (int age in age_IEnumerable)
  14.     Console.WriteLine(age);
  15. }
// Now Call PrintUpto30 by using our variable age_IEnumerable
PrintAgeUpto30(age_IEnumerable);
Now check the output you will see “PrintGreaterThan30 is called” many times something like this
  1. 10
  2. 20
  3. 30
  4. PrintGreaterThan30 is called
  5. 10
  6. ....
  7. 50
  8. 40
  9. PrintGreaterThan30 is called
  10. 10
  11. ...
  12. 50
  13. 50
  14. PrintGreaterThan30 is called
  15. 10
  16. 50
Conclusion:
  1. Both are interface
  2. IEnumerable code are clear and can be used in foreach loop
  3. IEnumerator use While, MoveNext, current to get current record
  4. IEnumerable doesn’t remember state
  5. IEnumerator persists state means which row it is reading
  6. IEnumerator cannot be used in foreach loop
  7. IEnumerable defines one method GetEnumerator which returns an IEnumerator
  8. IEnumerator allows readonly access to a collection

Static Class in C# why and when with examples

Static Class in C# why and when with examples

Static class, static method and static constructor are some common questions which are asked in most interviews. A static class is basically the same as a non-static class, but there in one difference, a static class cannot be instantiated, means we cannot use new keyword to create an object of the class. Even we cannot create any parameterized constructor because to pass the constructor value we need to create object, we will check all these points in more detail in this article.

When we can use static class?
We have a class Math in C#, let’s check it’s methods and operation. Say Math.Min, it takes two values of different data types and return minimum one, similarly Max, Round, Floor, Ceiling. If you notice all these methods take some values and operate only those provided values. So a static class should be container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields.
What is a static class?
A static class is similar to normal class with these differences
  1. Contains only static members means all the methods and members must be static
  2. Cannot be instantiated by using new keyword
  3. By default it is sealed class and therefore cannot be inherited.
  4. It can have default constructor or
  5. Can have only one constructor without any parameter
  6. Access modifiers are not allowed on static constructors
  7. Cannot have instantiate constructors
  8. Methods can be called by using class name dot (.) method name.
What is a static Method?
Static method are similar to regular (instantiate) method, but they can be accessed directly by using the class name rather than the instance of the class, it will give error if we will try to access them with class instance, see it with this example:
  1. public class Sample
  2. {
  3.     public void DisplayInst()
  4.     {
  5.         Console.WriteLine("I am a instance method");
  6.     }
  7.     public void DisplayStatic()
  8.     {
  9.         Console.WriteLine("I am a static method");
  10.     }
  11. }
Call these two methods with instance and directly, see this
  1. var obj = new Sample();
  2. obj.DisplayInst();  // I am a instance method
  3. obj.DisplayStatic(); // Wrong, it cannot be called
  4. // Let’s try to call them directly
  5. Sample.DisplayInst();  // Wrong, it cannot be called
  6. Sample.DisplayStatic(); // I am a static method
Can we have static as well as instantiate constructor in a class?
  1. Yes, it can be in a normal instantiate class
  2. Any number of instantiate constructors
  3. With zero to any number of parameters
  4. Can have only one static constructors
  5. Static constructor cannot have any parameter
  6. Static constructor are mostly used to initialize some values
We will create a simple Car class with different constructors and a static constructor to understand the feature, let’s create a class with two instantiate constructor, one static constructor and two Detail methods
  1. public class Car
  2. {        
  3.     String _color = "White";
  4.     static decimal _price = 25000;
  5.     static Decimal _discount = 100;
  6.     public Car()
  7.     {
  8.     }
  9.     public Car(String color)
  10.     {
  11.         this._color = color;
  12.         _discount = 500;
  13.     }
  14.     static Car()
  15.     {
  16.         _discount = 1000;
  17.     }
  18.     public String Detail()
  19.     {
  20.         return String.Format("Price: {0:C} and Color: {1} "
  21.                                 , _price - _discount, _color);
  22.     }
  23.     public static String Detail(String color)
  24.     {
  25.         return String.Format("Price: {0:C} and Color: {1} "
  26.                                 , _price - _discount, color);
  27.     }
  28. }
It is valid and working class which has both types of constructors and methods, if you can see there is a normal constructor without any parameter and one static constructor without any parameter, because static constructor cannot have any parameter. Let's try to execute them one by one
  1. var car = new Car(); car.Detail();
    • Output: Price: $25,000 and Color: White
  2. var car = new Car(“Black”); car.Detail();
    • Output: Price: $24,500 and Color: Black
    • One parameter constructor is called and assign the discount $500
  3. Car.Detail(“Red”);
    • Output: Price: $24,000 and Color: Red
    • When we will call Detail method, constructor will be called before executing the method.
Try to add a new constructor like this and you will get following error
public static Car(Int32 color) { } 
  1. a static constructor must be parameterless
  2. access modifiers are not allowed on static constructors
Conclusion:
  1. Easy to use
  2. No need to create instance before calling the methods
  3. Cannot have more than one constructor
  4. Constructor cannot have any parameter
  5. Access modifier cannot be use with constructor
  6. Constructor is called before calling any method internally
  7. Cannot be instantiated
  8. Cannot be inherited because by default it is sealed