C# Tips - Type Conversion with "as" and "is"

I had used C# for at least a year before I found out a couple of nice shorthand ways to convert types. These are the is and as expressions, and using them can help make your code more readable.

The is Expression

The is expression will return true if the provided expression is non-null and can be cast to the specific type.

private string GetDisplayField(object val)
{
  if (val is string)
  {
    string text = (string)val;
    return "Value was text: " + text;
  }
  else if (val is DateTime)
  {
    DateTime time = (DateTime)val;
    return "Value was date: " + time.ToShortDateString();
  }

  return "Could not match type";
}

The as Expression

The as expression will try to cast the object into the given type, and returns an object of that type if the cast was successful, or return null if unsuccessful.

This buys a little bit more functionality for you, as it assigns the variable with an already casted value if successful. It is functionally equivalent to: expression is type ? (type)expression : (type)null

private string GetDisplayField(object val)
{
  string text = val as string;
  DateTime? time = val as DateTime?;

  if (text != null)
  {
    return "Value was text: " + text;
  }
  if (time.HasValue)
  {
    return "Value was date: " + time.Value.ToShortDateString();
  }

  return "Could not match type";
}

Testing out the functions

Console.WriteLine(GetDisplayField(1));              // Output: "Could not match type"
Console.WriteLine(GetDisplayField("Hello"));        // Output: "Value was text: Hello"
Console.WriteLine(GetDisplayField(DateTime.Now));   // Output: "Value was date: 7/21/2009"

They are both readable ways to perform a type conversion - but pick one or the other! Using both of them is redundant.

Comments

  1. przewody elektryczne Says:

    There is certainly noticeably a bundle to understand relating to this. I suppose an individual made certain great things within capabilities also.

Comments are closed. Please contact me instead.