What is UrlParameter.Optional?

At first, I thought it was defined as an enumeration . But this is not so.

The UrlParameter parameter is defined 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 not know to put an optional parameter in the dictionary when it sees the following code? In the end, the code below simply assigns a new instance of UrlParameter to the identifier.

 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
+7
asp.net-mvc
source share
1 answer

Look at the wider 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.

+5
source share

All Articles