0

Can anyone tell me what is happening in below code. What is the reason behind declaring a member as the class type ??

    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();
}

I saw it in the route registration method:

routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "AboutView1", id = UrlParameter.Optional } );

  • Your question is unclear. What is it that you want to know? There are millions of reason for having a field of the same type as the declaring class. – Stefano d'Antonio Jul 10 '16 at 13:06
  • Edited my question! – Bhupinder Singh Jul 10 '16 at 13:51
  • You already have an answer which is correct. Does that not enough? Consider going through documentation. – Rahul Jul 10 '16 at 13:52
  • The MapRoute method is analysing the anonymous object behind the scenes and if the `id` is in the URL and it's of the type UrlParameter (instead of an expected value), it will check if it is the same as the Optional instance (which is a singleton) and if so, it won't get it's value, but it will consider it an optional parameter. – Stefano d'Antonio Jul 10 '16 at 13:59
  • You can look at the implementation from here: https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Mvc/RouteCollectionExtensions.cs – Stefano d'Antonio Jul 10 '16 at 14:00

1 Answers1

2

Although this may look strange to you, the Optional field is nothing but an implementation of the singleton design pattern (see Static Initialization here). A very special one in this case.

Because the field is marked as static, you'll only have one instance of the UrlParameter class in your application. The readonly modifier means that assignments to this field can only occur as part of the declaration or in a constructor in the same class (have a look here). In this concrete example, Optional is always set to null (see here). So it is a singleton, but merely a constant because it's defined as null.

Microsoft has probably done this so that the value of the Optional field may change in the future without breaking existing code (see the difference between const and static readonly) - const forces you to recompile all your existing code, in case of change, to make it work again, while static readonly doesn't.

Community
  • 1
  • 1
Jan Kalfus
  • 5,422
  • 2
  • 30
  • 38