Posts Tagged ‘snippet’

C# Tips – Type Conversion with “as” and “is”

Tuesday, July 21st, 2009

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.

jQuery outerHTML Snippet

Tuesday, June 16th, 2009

outerHTML is a property that is provided by Internet Explorer that returns the full HTML of an element (including start and end tags). In jQuery, the html() function returns the innerHTML of an element, which is just the HTML inside the element (not including the start and end tags).

There came a time that I wanted to get the outerHTML of an element, and I found that Brandon Aaron shared a jQuery code snippet that does this exactly. It does the trick for most cases, but there was one problem that I ran into. I wanted to get the outerHTML of an element inside of an iframe, and I got a ‘Permission Denied’ error in Internet Explorer.

The problem was that it was appending an element belonging to the iframes ‘contentDocument’ into an element belonging to the global ‘document’ element.
Using the jQuery(html, ownerDocument) overload of the jQuery core function, this error was fixed:

$.fn.outerHTML = function() {
    var doc = this[0] ? this[0].ownerDocument : document;
    return $('<div>', doc).append(this.eq(0).clone()).html();
};