Pi

January 4, 2010

.net C#4 Dynamics, cool but slow

Filed under: C#, Programming — rqmedes @ 10:58 am

Recently I have been playing with DynamicObjects one of the new features in C# 4.0.
DynamicObjects once extended allows you to specifying dynamic behavior at run time.


By overriding the  TryGetMember and TrySetMember method you can dynamically add and remove properties.


dynamic person = new DynamicClass;

person.Name = “John Smith”;

person.Phone = “32345690”;

By overriding the TrySetIndex and TryGetIndex you can access properties you don’t know about at compile time.
dynamic person = new DynamicClass;
person[“Name”] = “John Smith”;

A basic implementation.

    
public class DynamicClass : DynamicObject
{
        public Dictionary _dictionary = new Dictionary();

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            return _dictionary.TryGetValue(binder.Name, out result);
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            _dictionary[binder.Name] = value;
            return true;
        }

        public override bool TrySetIndex(
            SetIndexBinder binder, object[] indexes, object value)
        {
            if (dictionary.ContainsKey((string)indexes[0]))
                _dictionary[(string)indexes[0]] = value;
            else
                _dictionary.Add((string)indexes[0], value);
            return true;
        }
        public override bool TryGetIndex(
            GetIndexBinder binder, object[] indexes, out object result)
        {
            return _dictionary.TryGetValue((string)indexes[0], out result);
        }
}

I found a nice implementation on David Ebbo’s blog.
He is using dynamic to simplify data access by writing a wrapper for SQL queries.

I particularly like the Yield return within the data connection. I was at first concerned about this leaving open connections but used correctly connections area automatically cleaned up for you, check this out.

It all works well however it runs really slow. I would be wary of using dynamic if performance is a consideration.
I will post benchmarks soon.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: