Jay Bazuzi
Jay Bazuzi

Reputation: 46496

How to write an extension method that returns a dynamic object?

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.

Upvotes: 1

Views: 405

Answers (1)

Sander Rijken
Sander Rijken

Reputation: 21615

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);
}

Upvotes: 8

Related Questions