2009-03-03

C# Params

In C#, you'll want to familiarize yourself with the params keyword. Simply, params is a way of identifying a method with a variable number of arguments. At first, this seems to have limited uses, but in practice it has a lot of very pertinent uses. And, unfortunately, a lot of developers I've met do not know this little secret.

Let's say you're formatting Xml (without using the .NET Xml classes). You know what your Xml structure, and it's already been defined for you as such:

<book>
  <author>{0}</author>
  <title>{1}</title>
</book>

This Xml structure is already defined and available to you. To most effectively propagate your data into this structure, you could use string.Format as such:

public string FormattedXml(string Author, string Title)
{
  string xmlstructure = "<book><author>{0}</author><title>{1}</title></book>";
  return string.Format(xmlStructure, Author, Title);
}

This method will return a fully formatted xml stucture, replacing the tokens ({0}, {1}) to the caller. string.Format implements the params keyword to allow you to pass in any number of parameters that will be formatted--this Xml structure could easily have dozens of tokens--each of which would be replaced by whatever you gave to string.Format. Read more here: http://msdn.microsoft.com/en-us/library/aa331875.aspx

Unfortunately, the problem with processing Xml this way... is the rules of Xml formatting. This code, for example, will cause an Xml structure error:

string result = FormattedXml("Jamal Khan", "Ubercode & .NET");

The ampersand is a special character in XML. If you're validating your Xml against any validation tool, this will give you errors. The easiest way to address this is to use the HtmlEncode Method for each of your strings.

public string FormattedXml(string Author, string Title)
{
  string xmlstructure = "<book><author>{0}</author><title>{1}</title></book>";
  return string.Format(xmlStructure, HttpUtility.HtmlEncode(Author), HttpUtility.HtmlEncode(Title));
}

If you're ambitious, you could wrap this functionality into a Xml helper class or method, and in that case, read up on your params...

More Reading on Params: http://msdn.microsoft.com/en-us/library/w5zay9db(VS.71).aspx#

No comments: