Simple equivalent of “With” statement in C#

Consider the following class in C#

	public class Person
	{
		private string name;
		private int age;
		
		public string Name{
			get {return name;}
			set { name = value; }
		}
		
		public int Age{
			get {return age;}
			set { age = value; }
		}
	}

If I want to set the value of Name and Age property on the instance of Person class, I’ll need to refer to that instance for every property I need to set in the code. For example:

var person = new Person();
person.Name = "Super Man";
person.Age = 30;

It would have been great if C# had an equivalent of VB’s “With..End” statement, where we could refer to the instance of Person class only once and then refer to properties only.

Today, I came across this post “mucking about with hashes…“, which shows how C# lambdas could be used as hashes. Using this concept, I implemented a simple extension method that simulates the behavior of VB’s “With..End” statement to some extent.

Here is the code for extension method:

	public static class MetaExtensions
	{	
		public static void Set(this object obj,params Func<string,object>[] hash){
				foreach(Func<string,object> member in hash){
					var propertyName = member.Method.GetParameters()[0].Name;
					var propertyValue = member(string.Empty);
					obj.GetType()
						.GetProperty(propertyName)
							.SetValue(obj,propertyValue,null);
				};
		}
	}

Using this extension method, we can set the value of properties on instance of Person class as follows:

var person = new Person();
person.Set(
	Name => "Super Man",
	Age => 30
);

Isn’t that cool?

C# 3.5 in Ubuntu

Today, I managed to install Mono 2.4 in Ubuntu 9.04 without affecting Ubuntu’s default mono installation. Thanks to the instructions here (Building Mono 2.4 from source on Ubuntu 8.10), I was able to install latest mono/monodevelop in a parallel environment. Now I can work on C# 3.5 code in Linux as well.

Here is the screen shot of MonoDevelop instance with the code given in this post.

MonoDevelop running C# 3.5 code

Y-Combinator in C#

For last few days, I was trying to use lambda feature of C# to implement Y-Combinator. After few trial and errors, I was able to implement it in C# 3.5. I’m currently posting the code here and in my next blog, I’ll explain how I derived it.

In this code, Y-Combinator function, is used to implement anonymous recursive-factorial function called ‘factorial’.

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

namespace YCombinator
{
    class Program
    {
        delegate Func RecursiveFunction(RecursiveFunction f);

        static void Main(string[] args)
        {

            Func, Func>, Func> Y = (f) =>
            {
                RecursiveFunction function = (h) =>
                {
                    return (x) =>
                    {
                        return f(h(h))(x);
                    };
                };
                return function(function);
            };

            Func factorial = Y(function=>
            {
                return x =>
                {
                    return x == 0 ? 1 : x * function(x - 1);
                };
            });
            Console.WriteLine(factorial(5));
            Console.ReadLine();
        }
    }
}

Binding HTML Form Fields To Javascript Objects

Consider that I have a object called ‘person’ with a property called ‘Name’ which returns me the name of a particular person. I want to assign this object property to a form element such that:

  1. The form element will display the value of object property (In our case, the value of person.Name)
  2. If I change the value in form, then it should automatically get assigned to the object property

In C#, it could be done by using the following piece of code:

nameTextBox.DataBindings.Add("Text", person, "Name");

I really like the way DataBinding works and would really like have something like this when I’m working on web applications to bind a object property to input elements in HTML forms. So I decided to write a small javascript that would allow me to bind object properties to form elements. For example, I wanted to write something like this:

<input type="text" object="person" property="firstName" />

Thanks to the power of Javascript and prototype library, I was able to use data binding in html forms using code:

function initializeFormBinding()
{
	var formElements = document.getElementsByTagName('input');
	$A(formElements).each(function(formElement)
				{
					Element.extend(formElement);
					initializeFormElement(formElement);
				});
}
 
function initializeFormElement(formElement)
{
	if (!(formElementHasObjectAttribute(formElement) &amp;&amp; formElementHasPropertyAttribute(formElement)))
		return;
	var objectName = getAttributeValue(formElement,'object');
	var propertyName = getAttributeValue(formElement,'property');
	window.eval('formElement.value = '+objectName+'.'+propertyName);
	window.eval('formElement.onchange=function(){ '+objectName+'.'+propertyName+' = formElement.value; }');
}
 
function formElementHasObjectAttribute(formElement)
{
	return getAttributeValue(formElement,'object')!=null;
}
 
function formElementHasPropertyAttribute(formElement)
{
	return getAttributeValue(formElement,'property')!=null;
}
 
function getAttributeValue(element, attributeName)
{
	return element.readAttribute(attributeName);
}

Lets see how to use this: First, create a javascript object. For example:

var person = {};
person.firstName = '';
person.lastName = '';
person.age = '';
person.country = '';

After that call initializeFormBinding() function using onLoad attribute of body tag. For example:

<body onLoad="javascript:initializeFormBinding();">

Now, in each of your input elements, put the name of the object in ‘object’ attribute and name of property in ‘property’ attribute as follows:

<form>
First Name:
<input type="text" object="person" property="firstName" /><br>
Last Name:
<input type="text" object="person" property="lastName" /><br>
Age:
<input type="text" object="person" property="age" /><br>
Country:
<input type="text" object="person" property="country" /><br>
</form>

Thats it…. If you initialize properties of person object, you would see those values in respective form elements. On the other hand, if you modify the value in a particular input element then it would get reflected in the corresponding object property. Anybody is free to use this code in their applications.

Download a small example application..