Quantcast
Channel: Towards Next » C#
Viewing all articles
Browse latest Browse all 10

Dynamic Lookup & dynamic Type, C# 4.0 Part 1

$
0
0

C# 4.0 is out once again with new set of features. Now we will see one of the new feature of it, which is know as Dynamic Lookup. It is new approach for invoking thing more dynamically than before. It gives big freedom and working with various different kind of objects like COM etc will be too easy.

Big question how. I have written one sample below where i am grabbing the object of excel instance which is already running and filling data in it. In the previous version of C# we used to do it with the help of InvokeMember funtions of the object. But in C# 4.0 story is differentM

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DynamicObjects
{
class Program    
{
static void Main(string[] args)
{
dynamic excel = System.Runtime.
InteropServices.Marshal.GetActiveObject("Excel.Application");

//Display the name of the work book            
Console.WriteLine(excel.ActiveWorkbook.Name);

//Select the range and place some data here
excel.Range("B2").Select();
excel.ActiveCell.FormulaR1C1 = "Sample Data";

//Wait for the input            
Console.ReadLine();
}
}
}


It was so simple to use the dynamic object, That i have to just type out the properties and method in the front of dynamic object. At the time of getting that object it will be handled automatically and will map the functions and methods. Its really a great feature, which can save time and give more freedom to the developer.

Difference between VAR & DYNAMIC

VAR It is also know as local type inference feature of C#. This feature will allow you to remove the data type from the left hand side and create the type on the fly. But still you have to specify the type in the right hand side and var will be replaced by the new type which will be built at compile time.

DYNAMIC it is step ahead of the VAR. It will get the information of the object not at the compile time rather at the time of creation of that object. It is done at runtime only.



Viewing all articles
Browse latest Browse all 10

Trending Articles