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;
                _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.


August 14, 2009

Protecting your MVC Model with anonymous types

Filed under: C# — Tags: , , — rqmedes @ 12:01 pm

Anonymous classes can be a great way to protect your models from being polluted by any view specific requirements.
Lets say you have a Product model that you want to present as a list in a table.


You now want to add some extra information to present any pre selected items.
By creating an anonymous type you can easily extend your product to add the additional information, Selected.

var test = new { Product = product, Selected = true};

Combining this with Linq makes it easy to return a list that contains the products and any other information required by the view engine

var selectedId = 3;
var products = (from p in _productRepository.GetAll()
select new { Product = p, Selected = p.Id == selectedId });

This will set selected as true for the product with the Id of 3.


Blog at WordPress.com.