views:

82

answers:

1

I was thinking about how Regex.Match.Group wants to be dynamic:

Regex.Match (...).Groups["Foo"]

would like to be:

Regex.Match (...).Groups.Foo


I thought about writing an extension method that would allow:

Regex.Match (...).Groups().Foo

And tried writing it this way, but this isn't allowed (';' required by 'static dynamic')

public static dynamic DynamicGroups Groups(this Match match)
{
    return new DynamicGroups(match.Groups);
}

public class DynamicGroups : DynamicObject
{
    private readonly GroupCollection _groups;

    public DynamicGroups(GroupCollection groups)
    {
        this._groups = groups;
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        Group g = this._groups[binder.Name];

        if (g == null)
        {
            result = null;
            return false;
        }
        else
        {
            result = g;
            return true;
        }
    }
}

Any way to accomplish this?

There are plenty of other APIs that were written before dynamic that might be cleaner to use this way.

+5  A: 

There's just one little error in your code, change dynamic DynamicGroups to just dynamic

public static dynamic Groups(this Match match)
{
    return new DynamicGroups(match.Groups);
}
Sander Rijken
Silly me. Thanks!
Jay Bazuzi