‘case like classes’ in C# 4.0

 

“case classes” are a notion in scala. It provides an easier syntax to quickly create POJO objects (Its POCO – Plain Old CLR Objects, in .NET). When I first looked at this couple of days back, I was sure this could done with C# too. Here is what I checked,

  • Use dynamic keyword from C# 4.0
  • Create a simple key/value pair to define the property bag values.
  • Construct a dynamic object based on these values.

This looks pretty straight forward. The code is very simple, the CaseClass <- (dervies from) DynamicObject, and keeps a simple key/value pair mapping.

public class CaseClass : DynamicObject
    {
        private Dictionary<string, object> members;
        public CaseClass(IDictionary<string, object> propertyValues)
        {
            this.members = new Dictionary<string, object>();
            foreach (var kvp in propertyValues)
            {
                if (!this.members.ContainsKey(kvp.Key))
                {
                    this.members.Add(kvp.Key, kvp.Value);
                }
            }
        }

        public CaseClass Extends(CaseClass parent)
        {
            var instance = new CaseClass(this.members);
            foreach (var kvp in parent.members)
            {
                if (!instance.members.ContainsKey(kvp.Key))
                {
                    instance.members.Add(kvp.Key, kvp.Value);
                }
                else
                {
                    throw new InvalidOperationException("child object contains the same property key " + kvp.Key);
                }
            }

            return instance;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (this.members.ContainsKey(binder.Name))
            {
                result = this.members[binder.Name];
                return true;
            }
            else
            {
                return base.TryGetMember(binder, out result);
            }
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (!this.members.ContainsKey(binder.Name))
            {
                this.members.Add(binder.Name, value);
            }
            else
            {
                this.members[binder.Name] = value;
            }
            return true;
        }

        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return this.members.Keys;
        }
    }

Couple of interesting things,
  • It uses the fluent API interface.
  • If you want to extend a class object, simply call the Extends method and pass the parent class to it.

Usage of it is pretty simple too,

class Program
   {
       static void Main(string[] args)
       {
           var dict = new Dictionary<string, object>() { { "Name", "Fahad" }, { "Age", 25 } };
           var personalInfo = new CaseClass(dict);
           dynamic d1 = personalInfo;
           Console.WriteLine(d1.Name);
           Console.WriteLine(d1.Age);

           var work = new CaseClass(new Dictionary<string, object>() { { "Profession", "Software Engineer" } });           
           dynamic d2 = work.Extends(personalInfo);
           Console.WriteLine(d2.Profession);

           Console.ReadKey(true);
       }
   }

This shows the power of C#, (of course you don’t get intelli-sense / static typed values), but then its only for specific use cases, not everyone has to deal being dynamic. There are couple of more features that the Scala case classes provide, the ToString() / GetHashCode() / Equals() overrides that the scala compiler does for you. Anybody interested can simply add some more functionality in the above code.

Disclaimer: This post is just to show the usage of C# in one way as in Scala, It doesn’t completely replicate the functionality that is provided as-is in Scala.

-Fahad

Advertisements

One thought on “‘case like classes’ in C# 4.0

  1. […] This post was mentioned on Twitter by Balaji, Fahad. Fahad said: http://bit.ly/dzBmuM, blog post on case classes (#Scala) in C# 4.0 with the #dynamic keyword. […]

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

%d bloggers like this: