ARULJOTHI PARTHIBAN
ARULJOTHI PARTHIBAN

Reputation: 105

How to write methods with named parameters?

I have a method defined below.

public static MvcHtmlString DisplayReadOnlyGrid(
    this HtmlHelper htmlHelper,
    string containerId, 
    MvcHtmlString innerHtml)
{
    try
    {
        var outerDiv = new TagBuilder("DIV");
        outerDiv.AddCssClass("ML5 MT5 MR5");
        outerDiv.MergeAttribute("id", containerId);
        if (innerHtml != null && !innerHtml.Equals(string.Empty))
        {
            outerDiv.InnerHtml = innerHtml.ToString();
        }
        return MvcHtmlString.Create(outerDiv.ToString());
    }
    catch 
    {                
        throw;
    }
}

When I'm calling this method I need the format like below:

DisplayReadOnlyGrid(containerId="mycontainerid", innerHtml="innerhtml")

How can I do that?

Upvotes: 0

Views: 162

Answers (4)

Habib
Habib

Reputation: 223332

Explanation for the method:

First its an extension method. Which is notable with the key word this in the parameters. To be precise its an extension method on HtmlHelper

Second the parameters: They are Named parameters(feature of C# 4.0) and you can call that method:

helper.DisplayReadOnlyGrid(containerId:"mycontainerid", innerHtml:"innerhtml")

Named parameters allow you to specify parameters in any order and are helpful with default parameters as well, which is also a new feature in C# 4.0

Upvotes: 0

Lukazoid
Lukazoid

Reputation: 19426

Take a look at the MSDN here.

The format for using named arguments is as follows:

helper.DisplayReadOnlyGrid(containerId: "mycontainerid", innerHtml: "innerhtml");

Upvotes: 0

James Gaunt
James Gaunt

Reputation: 14783

Try this:

html.DisplayReadOnlyGrid(containerId: "mycontainerid", innerHtml: "innerhtml");

You can pass the parameters in any order, and you can pass both positional and named parameters, however the named parameters must follow the positional parameters for obvious reasons.

MSDN: http://msdn.microsoft.com/en-us/library/dd264739.aspx

Upvotes: 3

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174427

Since C# 4.0 this works out of the box, see here. There is nothing you have to do to enable it.
However, please note that the correct syntax uses a colon, not the equals sign:

helper.DisplayReadOnlyGrid(containerId: "mycontainerid", innerHtml: "innerhtml");

If you are using an older version, you are not able to do that at all.

Upvotes: 1

Related Questions