Wednesday, April 18, 2007

Symbols Part 3

Here's another alternative, which would unify lambda expressions and "symbols" nicely.

Also note that the solution in my previous post would be good for "mock" stype unit testings, since it works just fine in .NET 2.0 an later. It would allow you to specify method call expectations by writing the methods names directly into your code (rather than using string representations of their names).

Wednesday, April 11, 2007

Symbols, Part 2

I've previously written about how useful it would be to have compiler-checked symbols in C#. It allows you to identify methods, properties etc without having to use uncheckable (and un-refactorable) string literals. Insteads, you can use the method or property name and have it checked by the compiler (and refactored by your refactoring tool.)

I have some good news and some bad news:
  • The good news: you can simulate named symbols for methods right now.
  • The bad news: the technique doesn't work for properties (which is probably where you want it most).

Anyway, here's now to get a "named symbol" effect for methods. It relies on delegate inference to let you to use a method name and have the system automatically create a delegate. (Inspecting the delegate then gives the method info, when you need it.)
// Declare a delegate for a parameterless method 
// which returns void
public delegate void SimpleDelegate();

// This is the method to which you want to pass other
// methods. Its param is typed as SimpleDelegate
// Return type can be void or whatever you want.  
// I've used bool just for the sake of the example 
// below 
protected bool DoStuffWithMethod(SimpleDelegate d)
// here d.Method identifies the method
// Example of use:

// This is the method we want to refer to
public void Foo()
{ ... }

// here o.Foo is the compiler-checked "symbol"
MyObject o = new MyObject();

It would be great to have something similar for properties. Perhaps delegate inference could be extended so that if you use a property name instead of a method name, then the inferred delegate will point to the property's "getter" method.

P.S. as others have already pointed out, another solution for properties is to use LINQ-based syntax. Personally, I'd like something cleaner. I don't like the idea of writing "o => o.Foo" every time I want to say o.Foo (although I can't argue with the fact that it does work :-)

Finally, as noted here, a solution which worked in atttributes would be great (which is admitedly not the case for any of the solutions mentioned in this post).

Also see followup here.

Monday, April 09, 2007

Quoted Strings

I posted this suggestion about an alternative form of @-quoted strings. It would be useful in cases where the string itself contains lots of double quotes.