COM Interop and Parsing JSON Data – Dynamic C# (PART5)

Dynamic type can help us write COM interop code without using interop assemblies and parse json data without much plumbing code or concrete classes corresponding to json. This will result in less and cleaner code.

Let’s understand this with an example. Suppose we have one json file with student information. We’ll read json data and populate that to an excel file. Usually, dealing with excel files requires interop assemblies and json parsing involves creation of concrete classes corresponding to json data. Here we will use NewtonsoftJson to read json data from file and will populate the data in an excel file without using interop assemblies. You can add NewtonsoftJson to your project using nuget package manager.

Our json data looks like below

{
"students": [
{
"firstName": "Luv",
"lastName": "Mishra"
},
{
"firstName": "Kush",
"lastName": "Mishra"
},
{
"firstName": "Ankit",
"lastName": "Mishra"
},
{
"firstName": "Anurag",
"lastName": "Mishra"
}
]
}

Step1: Let’s first read the json data

dynamic jsonData = JsonConvert.DeserializeObject(File.ReadAllText("Students.json"));

Step2:Create excel object set the workbook

dynamic excel = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application", true));
            excel.Visible = true;
            excel.Workbooks.Add();
            dynamic defaultWorkSheet = excel.ActiveSheet;

Step3:Iterate through json data and populate the worksheet

int currentRow = 1;
 foreach(dynamic student in jsonData.students)
 {
   defaultWorkSheet.Cells[currentRow, "A"] = student.firstName;
   defaultWorkSheet.Cells[currentRow, "B"] = student.lastName;
   currentRow++;
 }

Here is the complete program

dynamic jsonData = JsonConvert.DeserializeObject(File.ReadAllText("Students.json"));
dynamic excel = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application", true));
excel.Visible = true;
excel.Workbooks.Add();
dynamic defaultWorkSheet = excel.ActiveSheet;

int currentRow = 1;
foreach(dynamic student in jsonData.students)
{
  defaultWorkSheet.Cells[currentRow, "A"] = student.firstName;
  defaultWorkSheet.Cells[currentRow, "B"] = student.lastName;
  currentRow++;
}

And output looks like below
excel
You can see, we did’t use interop assemblies to deal with excel and we didn’t create any concrete classes to hold student information. We had to write very little code and the code looks cleaner.

Shortening Reflection Code Using Dynamic – Dynamic C# (PART4)

Using dynamics can simplify our reflection based code. It can be very helpful in simplifying complex reflection code to make it more readable. We need to be aware of the APIs that objects in context supports.
Let’s understand this by an example. Suppose we have following string

string sampleString = "This is simple string";

Suppose, we want to get substring starting at index 8. So, the output will be – “simple string”

Though we can get the substring using string class’ Substring() method but to understand how we can reduce reflection code using dynamic, let’s do it using reflection. We’ll first invoke the Substing method using reflection and then using dynamic.
Here is how reflection based code looks like to get the substring

 string sampleString = "This is simple string";
 string substring = (string)sampleString.GetType().InvokeMember("Substring",
                BindingFlags.InvokeMethod,
                null,
                sampleString,
                new object[] { 8 });
Console.WriteLine(substring);

And the output is – “simple string”
Now, let’s invoke the Substring method using dynamic. We’ll cast the underlying string variable to dynamic and then try invoke Substring() method.

string sampleString = "This is simple string";
string substring = ((dynamic)sampleString).Substring(8);
Console.WriteLine(substring);

And the output is  – “simple string”

As you can see, the code using dynamic is much simpler and short. This is a simple example. Dynamic can be very helpful in shortening complex reflection based code.

Limitations – Dynamic C# (PART3)

We can’t call extension methods on variables of type dynamic
For example, suppose we have one string extension that repeats the same string

    public static class StringExtensions
    {
        public static string RepeatIt(this string str)
        {
            return string.Format("{0} {1}", str, str);
        }
    }

If we try invoke this extension method on a variable of type dynamic, we’ll get RuntimeBinderException. This is because extension methods are compile time construct. Runtime has no way of knowing that there is some extension method that can be invoked on dynamic type.

dynamic str = "Hello";
Console.WriteLine(str.RepeatIt()); (Throws RuntimeBinderException)

Workaround is to use the extension method as regular static method

dynamic str = "Hello";
Console.WriteLine(StringExtensions.RepeatIt(str));

Dynamic type variables can’t invoke explicitly implemented interface members. For example
Here is my Student class that implements IStudent interface’s CalculateFinalGrade() method explicitly.

    public class Student:IStudent
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public dynamic DateOfBirth { get; set; }

        double IStudent.CalculateFinalGrade()
        {
            //For now lets just return anything
            return 78.5;
        }
    }

If we try to invoke CalculateFinalGrade() method on variable of type dynamic it will throw RuntimeBinderException

dynamic st = new Student();
Console.WriteLine(st.CalculateFinalGrade());

Also, don’t assign result of a void method call on dynamic to any variable; it will throw RuntimeBinderException at run time.

Conversions, dynamic vs var vs object and Overloads – Dynamic C# (PART2)

Conversions
Dynamic type is implicitly convertible to and from every other type. E.g.

int i = 10;
dynamic d = i;
int j = d;

But we cannot do following

string s=”Hello”;
Dynamic ds = s;
int i = ds (Throws cast exception as obvious)

var vs Dynamic
Let’s understand difference between var and dynamic types by an example.

dynamic dynamicVar = “Hello World”;

At compile time type of dynamicVar is dynamic. At runtime, type of dynamicVar is string

string stringVar = “Hello World”;

At compile time, type of stringVar is string. At runtime, type of stringVar is string

var helloVar = “Hellow World”

At compile time, type of helloVar is string. At runtime, type of helloVar is string

In case of var, type is decided at compile time whereas in case of dynamic, type is decided at runtime.
We can assign multiple types to same dynamic variable but we can’t do the same with var type variables.
e.g.

dynamic dynamicVar = “Hello World”;
Console.WriteLine(dynamicVar);
Console.WriteLine(dynamicVar.GetType());

dynamicVar = 10;
Console.WriteLine(dynamicVar);
Console.WriteLine(dynamicVar.GetType());

Output:
“Hello World”
System.String
10
System.Int32

You can see first we assigned string type to our dynamic variable dynamicVar and then we assigned integer type to same variable.

Overloads
If we have method overloads with both dynamic and specific type as an argument, most specific one is called and the one with dynamic argument works as fallback. If we have two overloaded methods, one with dynamic type and the other with object type, compiler throws error.

Object vs Dynamic
Dynamic and object types are same except the fact that in case of dynamic types, we can invoke any method or access properties without any error at compile time. After the compilation even dynamic type gets converted to object type.
E.g. Following is my Student class

public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public dynamic DateOfBirth { get; set; }
    }

And here is decompiled version of the same class. You can notice that type of DateOfBirth becomes object.

public class Student
  {
    // Field <Id>k__BackingField with token 04000001
    [/*Attribute with token 0C000001*/CompilerGenerated]
    [/*Attribute with token 0C000002*/DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private int \u003CId\u003Ek__BackingField;
    // Field <Name>k__BackingField with token 04000002
    [/*Attribute with token 0C000011*/CompilerGenerated]
    [/*Attribute with token 0C000012*/DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private string \u003CName\u003Ek__BackingField;
    // Field <DateOfBirth>k__BackingField with token 04000003
    [/*Attribute with token 0C000014*/CompilerGenerated]
    [/*Attribute with token 0C000016*/DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private object \u003CDateOfBirth\u003Ek__BackingField;

    // Property Id with token 17000001
    public int Id
    {
      // Method get_Id with token 06000003
      get
      {
        return this.\u003CId\u003Ek__BackingField;
      }
      // Method set_Id with token 06000004
      set
      {
        this.\u003CId\u003Ek__BackingField = value;
      }
    }

    // Property Name with token 17000002
    public string Name
    {
      // Method get_Name with token 06000005
      get
      {
        return this.\u003CName\u003Ek__BackingField;
      }
      // Method set_Name with token 06000006
      set
      {
        this.\u003CName\u003Ek__BackingField = value;
      }
    }

    // Property DateOfBirth with token 17000003
    public object DateOfBirth
    {
      // Method get_DateOfBirth with token 06000007
      get
      {
        return this.\u003CDateOfBirth\u003Ek__BackingField;
      }
      // Method set_DateOfBirth with token 06000008
      set
      {
        this.\u003CDateOfBirth\u003Ek__BackingField = value;
      }
    }

    // Method .ctor with token 06000009
    public Student()
    {
      base.\u002Ector();
    }
  }

Introduction to Dynamic C# – Dynamic C# (PART1)

C# 4.0 introduced a new type called dynamic. Dynamic types can help us write code that is more readable, simple and quick to write. There are scenarios when we are not sure about features of underlying data structure/object at compile time but we know what features the object will have at run time. Dynamic types are best suited for such scenarios.
Dynamic types can reduce the amount of code we have to write to implement some logic leading to better productivity.

Syntax of declaring a dynamic type is as follows:

dynamic st = new Student() { Id = 1, Name = "Rajeev" };

Dynamic types are also helpful while dealing with weakly typed data like JSON, XML or plain text. You can replace the reflection code in your app with less complex code using dynamic types. They also help us write simple interop COM components.
Dynamic Language Runtime (DLR)
Fundamental bedrock of .net is Common Language Runtime (CLR). It is runtime environment in which our .net code executes. In C# 4, DLR was added. It enables dynamic features in static languages like C#

DLR

Static Binding, Dynamic Binding and RuntimeBinderException

Binding is association of class members with object. Static binding happens at compile time. Compiler is aware of all the members that the class has and it binds them with the object. Here is the example

public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

 

Student st = new Student() { Id = 1, Name = "Rajeev" };
string name = st.Name;
Console.WriteLine(name);

In above example, at compile time Name property gets bound to st object. We get proper intellisence for the members.
Dynamic binding happens at runtime. Compiler is not aware of the member that we want to associate with object. Dynamic binding happens if we declare our object of dynamic type. In following example, st is declared as dynamic type. Binding of Name property happens at runtime. We even don’t get intellisence for dynamic types. If we declare certain object as dynamic type, compiler trusts that everything will be fine at runtime and doesn’t throw any error.

dynamic st = new Student() { Id = 1, Name = "Rajeev" };
string name = st.Name;
Console.WriteLine(name);

If we try to access some property or execute some method of a dynamic type object, We’ll get RuntimeBinderException. For example, we try to access ThisPropertyDoesNotExist property of dynamic object st, we’ll get RuntimeBinderException as follows

dynamic st = new Student() { Id = 1, Name = "Rajeev" };
            string name = st.ThisPropertyDoesNotExist;
            Console.WriteLine(name);

RuntimeBinderEx

Conditional Exception Catching – C# 6 Language Features (PART6)

In C#6, we can catch exceptions based on some condition by using ‘when’ construct. Here is the format

            try
            {
                //Do something
            }
            catch (Exception ex) when (conditon)
            {
                // Do something
            }

Lets understand this by an example. I have Maths class with a method Divide(int a, int b). It returns division of a and b.

    public class Maths
    {
        public double Divide(int a, int b)
        {
            return a / b;
        }
    }

Now, let’s create an object of Maths class and pass argument 10 and 0. As we know, it’s going to through DivideByZero exception. We want to catch this exception only if certain condition is true. For now, let’s have a Boolean flag catchException. If flag catchException is true, we’ll catch the exception else we’ll allow it to blow.
We can do this as follows:

            bool catchException = true;
            var math = new Maths();

            try
            {
                var result = math.Divide(10, 0);
            }
            catch (Exception ex) when (catchException)
            {
                Console.WriteLine("Exception occurred" + ex.Message);
            }

We have a simple scenario here but ‘when’ construct can have any condition, expression or method call but its output should be of Boolean type.

Collection Add method as Extension – C# 6 Language Features (PART5)

C# compiler generates a series of calls to Add method or indexer whenever we initialize collections with items. This works for built-in types as well as custom collections created by implementing IEnumerable interface and having public Add method in it. Let’s understand this by an example.

We have a Student class and a StudentCollection class which implements IEnumerable<Student> interface. Here is the code

    public class Student
    {
        public Guid Id { get; } = Guid.NewGuid();
        public string Name { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public string Address { get; set; }
        public event EventHandler<EventArgs> Reading;

        public void Read()
        {
            Reading?.Invoke(this, new EventArgs());
        }
    }

public class StudentCollection : IEnumerable<Student>
    {
        List<Student> students;
        public int Capacity { get; }

        public StudentCollection(int capacity)
        {
            students = new List<Student>(capacity)
            {
                new Student() {Name="Arjun", Address="Allahabad", DateOfBirth=new DateTime(1986,02,03) },
                new Student() {Name="Sanjay", Address="Pratapgarh", DateOfBirth=new DateTime(1976,12,8) }
            };
            this.Capacity = capacity;
        }

        public Student Add(Student newStudent)
        {
            this.students.Add(newStudent);

            return newStudent;
        }

        public IEnumerator<Student> GetEnumerator()
        {
            var allUsers = students;
            return allUsers.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

You can see, we have implementation for IEnumerable interface methods and we have one Add method that adds new student in the collection. Now we can initialize our StudentCollection class as follows

var students = new StudentCollection(10)
            {
                new Student { Name = "John", Address = "Seattle", DateOfBirth = new DateTime(1992, 5, 6) },
                new Student { Name = "Raj", Address = "Redmond", DateOfBirth = new DateTime(1982, 5, 6) },
                new Student { Name = "Kyle", Address = "Seattle", DateOfBirth = new DateTime(1972, 5, 6) }
            };

Compiler generates series of Add method calls internally to add these items.

This is required that the method to add new item to the collection should be named ‘Add’. If we don’t name it Add, compiler will prompt error as follows

‘StudentCollection’ does not contain a definition for ‘Add’ and no extension method ‘Add’ accepting a first argument of type ‘StudentCollection’ could be found

The above approach is how we have been implementing collections traditionally.
In C#6, if the creator of the collection class didn’t name the method to add the new item as ‘Add’, we can still initialize the collection in same traditional way by creating an extension method named ‘Add’ on the collection class.
Suppose, in our StudentCollection, the method name for adding the new item is ‘AddStudent’ in place of Add, we can create an extension method named ‘Add’ on StudentCollection class as follows and initialize our collection the same way.

public static class StudentCollectionExtension
    {
        public static Student Add(this StudentCollection students, Student newStudent)
        {
            return students.AddStudent(newStudent);
        }
    }