Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the UrlParameter.Optional really is?

Tags:

asp.net-mvc

At first, I thought it is defined as some kind of an enum. But it is not.

The UrlParameter is defined as below:

// Summary:
//     Represents an optional parameter that is used by the System.Web.Mvc.MvcHandler
//     class during routing.
public sealed class UrlParameter
{
    // Summary:
    //     Contains the read-only value for the optional parameter.
    public static readonly UrlParameter Optional;

    // Summary:
    //     Returns an empty string. This method supports the ASP.NET MVC infrastructure
    //     and is not intended to be used directly from your code.
    //
    // Returns:
    //     An empty string.
    public override string ToString();
}

And ILSpy shows the implementation as:

// System.Web.Mvc.UrlParameter
/// <summary>Contains the read-only value for the optional parameter.</summary>
public static readonly UrlParameter Optional = new UrlParameter();

So how does MVC know not to put the optional parameter into the dictionary when it sees the following code? After all, the code below just assign a new instance of UrlParameter to the id.

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
like image 627
smwikipedia Avatar asked Sep 17 '13 14:09

smwikipedia


1 Answers

Look at the broader context.

The complete source code for UrlParameter is

public sealed class UrlParameter {

    [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "This type is immutable.")]
    public static readonly UrlParameter Optional = new UrlParameter();

    // singleton constructor
    private UrlParameter() { }

    public override string ToString() {
        return String.Empty;
    }
}

UrlParameter.Optional is the only possible instance of UrlParameter.
In other words, the entire UrlParameter class exists only as a placeholder for optional parameters.

like image 64
SLaks Avatar answered Sep 27 '22 18:09

SLaks