A somewhat type-safe String.Format

written by Ryan Olshan on Monday, January 23 2006

Using String.Format you can format any string. However, the last parameter that String.Format accepts is of type object. So, to add some type-safety to the mix, the following function works perfectly.

VB.NET
Public Function FormatString(Of T)(ByVal originalString As String, ByVal replacement As T) As String
   Return String.Format(originalString, replacement)
End Function

C#
public string FormatString<T>(string originalString, T replacement)
{
   return String.Format(originalString, replacement);
}

Kick this post on .NET Kicks

Similar Posts

  1. What's wrong with this generic class?
  2. Generic Type Inference
  3. Generic Sub Classes

Comments

  • Marc Brooks on on 1.23.2006 at 3:49 PM

    Marc Brooks avatar

    What does this buy you?



    It does insure that you pass an integer when you doe FormatString<int>("d", 2), but you still have no linkage between the formatting tokens and the replacement object, which is really where the type-safety would be useful (like I should have given a DateTime here). It's not that useful in the other major use of String.Format, for parameter rearrangement either.

  • Ryan Olshan on on 1.23.2006 at 6:02 PM

    Ryan Olshan avatar

    That's why I named this blog entry "A somewhat type-safe String.Format."



    It does add some type-safety on what you are passing to it. However, there isn't any type-safety on what happens when the string is formatted. The function does limit it to only one of the overloads of String.Format, but you could add other overloads. While it's not the best example as a use for generics, it should hopefully get people not familiar with or confused about generics thinking as to how they can apply generics.

Post a comment