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.


Blogger Chris said...

Wow thanks for this :-) neat solution

Thu May 24, 07:35:00 AM PDT  
Anonymous dgon said...

SureI am late but I bumped into this while researching about symbols in C#.
I wanted to do the same sweet thing that is mentioned in Symbols in C# 3.0 to get the name of a method but if I got it right with your solution, do I need a new delegate for each and every of my methods signatures?

Sorry if it's a dumb question.

Thu Dec 06, 02:49:00 AM PST  

Links to this post:

Create a Link

<< Home