My favorite Extension methods: String.Format shortcut

This is the first entry in a short series highlighting some of my favorite extension methods.

It’s a generally accepted best practice to use the String.Format() method to assemble string values that merge text and variables.

Using an Extension Method (.NET 3.5 or greater) makes accessing the String.Format function even easier.

Now, for any string value, you can simply use the following

"The quick brown fox {0}".Fmt("jumped over the lazy dog.")

Here’s the code for the extension method and various overloads:

<Extension()>_
Public Function Fmt(ByVal format As String, ByVal arg0 As Object) As String
  Return String.Format(format, arg0)
End Function

<Extension()>_
Public Function Fmt(ByVal format As String, ByVal arg0 As Object, ByVal arg1 As Object) As String
  Return String.Format(format, arg0, arg1)
End Function

<Extension()>_
Public Function Fmt(ByVal format As String, ByVal arg0 As Object, ByVal arg1 As Object, ByVal arg2 As Object) As String
  Return String.Format(format, arg0, arg1, arg2)
End Function

<Extension()>_
Public Function Fmt(ByVal format As String, ByVal ParamArray args() As Object) As String
  Return String.Format(format, args)
End Function

Leave a Reply