Tuesday, October 05, 2010

On my wish list: Static extension methods

Ideally, I want to remove as much lambda expressions as possible out of my repository classes. Using Subsonic, I want to implement my own fluent methods which do not require any lambda in the implemented repository class at all.

Now, please correct me if I'm wrong, but while you can make a generic extension class you can't really make static extension methods in c#? Code would be something like this:


public static class GeneralExtension{
public static T ById(this T entity, int id) where T: IActiveRecord
{
return T.SingleOrDefaul(x=>x.Id == id);
}
}


And implementation would be something like this:


public class TaskRepository : IScrumblrRepository
{
public Task Get(int id)
{
return Task.ById(id);
}
}


If I find a smooth way of doing this without the use of static extension methods, I'll let you know.

5 comments:

Q and A site for developers said...

How many people do read this post? Just curios.

Anders said...

That reminds me, my analytics script is not recording at the moment. Last year, this blog had about 300 visitors per day.

Yngve B. Nilsen said...

Why not hook the extension-method to the Interface? No need for generics here...


public static IMyInterface ById(this IList i, int id)
{
return i.Single(m => m.Id == id);
}

Now all Lists containing classes that implement IMyInterface will get the new Extensionmethod ById

/Y

Yngve B. Nilsen said...

apparently the comment stripped away something.. It's supposed to be this IList<IMyInterface> in the parameterlist

Anders said...

I have no control of the list classes. But I suppose I could do your implementation if I alter the T4 code generation scripts that comes with Subsonic.