Removing the Ceremony from C#
Ceremony. More and more I see comments about there being too much ceremony in C#. That is, it isn't terse enough and that we should be spending less time worrying about typing brackets and parenthesis and more time worrying about the customer's problem. Yanno, like them dynamic, skivvy wearin, popular-with-the-girls Ruby folk are doing, with Merb on Rack or whatever its called now.
I'm inclined to agree; it's why code templating plugins exist for C#, yet there is not really a Ruby equivalent (though TextMate comes close). Some people are asking what can we add to the language, some wonder if we need it, and some are asking 'maybe we should take stuff out'?
Allow me to join in, get all misty and say...
So at the moment we can easily write in a functional style like this:
var foo = SomeList.Select(c => c.ToString());
[/sourcecode]
In this case, foo is inferred as being an IEnumerable. I was thrilled when var became available, it was a massive code cleanup.
Well, what if the inferencing engine could go deeper? You might write code like this:
var result =
if (someBoolean)
return "Jim";
else
return "Jam";
[/sourcecode]
Assuming we could put an if statement on the RHS like this, the typed variable result can be inferred as returning string, since both outcomes return this type.
So what if we might want to return different types? Perhaps we could return a common base class instead...
var conn =
if (isFooDb)
return new FooDbConnection();
else
return new SqlDbConnection();
[/sourcecode]
Our var conn is typed as IDbConnection, a common base type between the two potential return types. But why stop there? We could have our functions infer their return types and parameter types as well:
public SomeFunction(someInt)
{
return "Hello world".ElementAt(someInt);
}
[/sourcecode]
Here, someInt is inferred as Int32, since that is what the extension method ElementAt takes as a parameter. Since ElementAt returns char in this case, that would be the return type of the function.
public IsGreater(first, second)
{
return first > second;
}
[/sourcecode]
The parameters first and second become inferred as being generic types, that have the generic constraint of implementing IComparable etc. Obviously, the return type is boolean.
Of course, this is all pie in the sky for C# right now, and I would be astounded if it made the next version. To be honest, I think we would need to give up certain other freedoms in order for this to be a reality. However, if you can't wait for C# X and want to use this kind of type inference now, with full IDE, compiler, debugger and intellisense support, start coding in F# today!
PS. Kind of looks JavaScripty in retrospect.