Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Auto-gen a URI string based on a method call

4.18/5 (4 votes)
22 Nov 2013CPOL1 min read 7.4K  
Auto-gen a URI string based on a method call.

There are some navigational paradigms out there that use navigation strings to hit, in turn, methods within your own codebase. It’s a sound idea, but generating those URIs as strings which you in turn use in a Navigate() call can be problematic. What happens when you add a parameter to the method? Rearrange the parameters? And what if you could get intellisense when you wanted to generate those URIs?

Look no further than that awesomeness Microsoft provides us .Net developers than the beautiful acronym we all love: LINQ. More specifically, the Expression Tree objects that we got with LINQ.

I’ve used a pretty handy class for a while now that allow me to use hard references to properties when I am implementing/calling INotifyPropertyChanged objects. Basically, it turns

C#
OnNotifyPropertyChanged("MyProperty");

in to

C#
OnNotifyPropertyChanged(()=>this.MyProperty);

which, as you can guess, makes sure that I never misspell the property and also never use one that’s not available in my code.

So, I took this idea another step and dissected the handy reusable file I’d had in so many of my Windows Phone projects to accomplish this to see if I could make it fit the bill of a NavigationURI generator.

Here’s what I came up with:

C#
class MethodProcessor
{
    public static string CreateStringForCall<T>(Expression<Action<T>> methodCall)
    {
        var exp = methodCall.Body as MethodCallExpression;
        var retVal = string.Concat(exp.Method.Name, "/",
            string.Join("/", exp.Arguments.Cast<ConstantExpression>().Select(a => a.Value.ToString())));
        return retVal;
    }
}

which gets used like this:

C#
public class SubClass
{
    public void MyMethod(string name, int value)
    {

    }
}

static void Main(string[] args)
{
    Console.WriteLine(
        MethodProcessor.CreateStringForCall<SubClass>(
        (o)=>o.MyMethod("theName",4)));
}

and gives me this:

image

Pretty slick! Feel free to dissect the expression tree magic going on here and augment it to your liking!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)