Search code examples
c#strong-typing

Type safety in string arguments


My specific question is about ASP.NET MVC but I am sure that the answers can be applied outside ASP.NET.

How do you deal with functions that accept string arguments but still you want type safety?

In ASP.NET, the extension method Html.ActionLink has two arguments of type string: string linkText, string actionName. The first argument is a text that can be loaded from a resource but the second argument is the name of a method that exists in code.

One option would be to create a class with constant strings so instead of writing

 Html.ActionLink("Blah blah", "MyAction");

one could write:

Html.ActionLine("Blah blah", StrongType.MyAction);

Where MyAction is a const string in a class called StrongType. However, this becomes a pain to manage when the number of methods and other objects that can be passed as arguments increases.

A second option would be to load somehow the name of the function using Reflection but this seems too expensive.

Is there a better way of doing it? How do you make sure that you don't have typos in string arguments like the ones mentioned before?


Solution

  • You can use the ActionLink extension method that allows you to avoid the use of these magic string.

    <%= Html.ActionLink<BlahController>(c => c.MyAction(), "Blah blah");
    

    You'll need to reference Microsoft.Web.Mvc which is part of ASP.NET MVC 3 Futures and available at http://aspnet.codeplex.com/releases/view/58781.