Ziv Weissman
Ziv Weissman

Reputation: 4556

Sending property name to a method

I have a question, similar to what was asked in the past, but I wonder if there is a way to achieve this:

Sending to a method the name of the property itself, without using the property directly. (IE. Not GetName(()=> ParamSearch1parameter - like seen on another solution)

Example code:

#region Props

    public string ParamSearch1
    {
        get
        {
            return GetValueFromQueryString(/*Here should come a string called ParamSearch1*/); 

        }
    }

    #endregion

    #region Helper Methods

    private string GetValueFromQueryString(string keyName)
    {
        return string.IsNullOrEmpty(Request.QueryString[keyName]) ? "" : Request.QueryString[keyName];
    }

    #endregion

Upvotes: 1

Views: 163

Answers (1)

keyboardP
keyboardP

Reputation: 69392

If you're targetting .NET 4.5, you can use the CallerMemberName attribute.

public string ParamSearch1
{
    get
    {
       return GetValueFromQueryString();     
    }
}

private string GetValueFromQueryString([CallerMemberName] string keyName = "")
{
    return string.IsNullOrEmpty(Request.QueryString[keyName]) ? "" : Request.QueryString[keyName];       
}

Otherwise there's no built in solution other than the solutions you've already come across. If you're happy to add an extra dependency, you can use the MS BCL Portability Pack to provide the CallerMemberNameAttribute to previous versions of .NET or follow Thomas's post on recreating the attribute in the comments.

Upvotes: 4

Related Questions