RSS

Explicit Conversion X as Operator

13 Jan

What’s the difference between explicit conversion, as operator and calling a method to a conversion?

public void Test2()
{
    var obj = "stack247";

    var str1 = (string)obj;
    var str2 = obj as string;
    var str3 = obj.ToString();
}

Conclusion (as seen from the result below):

  • Explicit conversion throws InvalidCastException if obj is not a string type.
  • Explicit conversion assigns anything to obj, even if it’s null.
  • as operator returns null if obj is not a string type.
  • as operator can’t be use in value type because it’s not null-able, unless the value type is null-able (for example, int? will work)
  • ToString(), or whatever the method that return certain type, will throw NullReferenceException if obj is null.
  • ToString(), or whatever the method that return certain type, will return string representation of an object if the object can’t be converted.
public void Test1()
{
    var obj = "stack247";

    var str1 = (string)obj;
    // Return stack247

    var str2 = obj as string;
    // Return stack247

    var str3 = obj.ToString();
    // Return stack247
}
public void Test2()
{
    var obj = new object();

    var str1 = (string)obj;
    // Return InvalidCastException (Unable to cast object of type 'System.Object' to type 'System.String'

    var str2 = obj as string;
    // Return null

    var str3 = obj.ToString();
    // Return System.Object
}
public void Test3()
{
    var obj = 247;

    var str1 = (int)obj;
    // Return 247

    var str2 = obj as int;
    // Return The 'as' operator must be used with a reference type or nullable type ('int' is non-nullable value type).

    var str3 = obj as int?;
    // Return 247

    var str4 = obj.ToString();
    // Return 247
}
public void Test4()
{
    object obj = null;

    var str1 = (string)obj;
    // Return null

    var str2 = obj as string;
    // Return null

    var str3 = obj.ToString();
    // Return NullReferenceException (Object reference not set to an instance of an object).
}
Advertisements
 
1 Comment

Posted by on January 13, 2015 in General

 

Tags: , , ,

One response to “Explicit Conversion X as Operator

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: