Archive for the ‘Framework 4.0 New Features’ Category

what is the use of Yield keyword?

Yield keyword helps to do custom and stateful iteration over a collection

Custom Iteration
namespace ConsoleApplication1
{
    class Program
    {
        static List<int> myList = new List<int>();

        static void Main(string[] args)
        {
            FillValues();
            foreach (int i in myList)
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();
        }

        static void FillValues()
        {
            myList.Add(1);
            myList.Add(2);
            myList.Add(3);
            myList.Add(4);
            myList.Add(5);

        }
    }
}

If we run the above program the output would be displayed as below

Untitled

2

Let us suppose that the user want to display only numbers which are greater than a specific number ( say 3), then many developers would end up writing a piece of code as shown below:

namespace ConsoleApplication1
{
    class Program
    {
        static List<int> myList = new List<int>();

        static void Main(string[] args)
        {
            FillValues();
            foreach (int i in Filter())
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();
        }

        static void FillValues()
        {
            myList.Add(1);
            myList.Add(2);
            myList.Add(3);
            myList.Add(4);
            myList.Add(5);
        }

        static IEnumerable<int> Filter()
        {
            List<int> temp = new List<int>();

            foreach(int i in myList)
            {
                if(i >3)
                {
                    temp.Add(i);
                }
            }
            return temp;
        }
    }
}

3

Notice that in the above piece of code we are using a temporary list. It would be good if we can write the same piece of code without using the temporary list. That is where exactly yield will help us.

        static IEnumerable<int> Filter()
        {
            foreach(int i in myList)
            {
                if(i >3)
                {
                    yield return i;
                }
            }

        }

4

Stateful Iteration

Let us suppose that we would like to find the running total of the list defined in the above code

5

We use a yield return statement to return each element one at a time.

namespace ConsoleApplication1
{
    class Program
    {
        static List<int> myList = new List<int>();

        static void Main(string[] args)
        {
            FillValues();
            foreach (int i in RunningTotal())
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();
        }

        static void FillValues()
        {
            myList.Add(1);
            myList.Add(2);
            myList.Add(3);
            myList.Add(4);
            myList.Add(5);
        }

 static IEnumerable<int> RunningTotal()
 {
    int runningTotal = 0;
    foreach(int i in myList)
    {
      runningTotal  += i;
      yield return runningTotal;
    }
  }
}
}
Advertisements

Programming languages are sometimes divided into statically typed and dynamically typed languages. C# and Java are often considered examples of statically typed languages, while Python, Ruby and JavaScript are examples of dynamically typed languages.

Generally speaking, dynamic languages don’t perform compile-time type checks and identify the type of objects at run time only. This approach has its pros and cons: Often the code is much faster and easier to write, but at the same time you don’t get compiler errors and have to use unit testing and other techniques to ensure the correct behavior of your application.

Originally, C# was created as a purely static language, but with C# 4, dynamic elements have been added to improve interoperability with dynamic languages and frameworks. The C# team considered several design options, but finally settled on adding a new keyword to support these features: dynamic.

The dynamic keyword influences compilation. A dynamic variable, parameter or field can have any type.  Its type can change during run-time. The downside is that performance suffers and you lose compile-time checking.

dynamic d = "test";
Console.WriteLine(d.GetType());
// Prints "System.String".

d = 100;
Console.WriteLine(d.GetType());
// Prints "System.Int32".

As you can see, it’s possible to assign objects of different types to a variable declared as dynamic. The code compiles and the type of object is identified at run time. However, this code compiles as well, but throws an exception at run time:

dynamic d = "test"; // The following line throws an exception at run time. d++;

Absence of compile-time type checking leads to the absence of IntelliSense as well. Because the C# compiler doesn’t know the type of the object, it can’t enumerate its properties and methods.

object d = "test";
Console.WriteLine(d.Length);
dynamic d = "test";
// The following call to exampleMethod1 causes a compiler error
Console.WriteLine(d.Length);

 

static void Main(string[] args)
{
    ExampleClass ec = new ExampleClass();
    // The following call to exampleMethod1 causes a compiler error
    // if exampleMethod1 has only one parameter. Uncomment the line
    // to see the error.
    //ec.exampleMethod1(10, 4);

    dynamic dynamic_ec = new ExampleClass();
    // The following line is not identified as an error by the
    // compiler, but it causes a run-time exception.
    dynamic_ec.exampleMethod1(10, 4);

    // The following calls also do not cause compiler errors, whether
    // appropriate methods exist or not.
    dynamic_ec.someMethod("some argument", 7, null);
    dynamic_ec.nonexistentMethod();
}

 

class ExampleClass
{
    public ExampleClass() { }
    public ExampleClass(int v) { }

    public void exampleMethod1(int i) { }

    public void exampleMethod2(string str) { }
}