Search code examples
c#objectcasting

cast from object to label


what is difference between these codes?

public class MyClass
{
    object myObject;

    public MyClass()
    {
        myObject = new Label();
        (myObject as Label).Width = 100;
    }
} 

And:

 public class MyClass
    {
        object myObject;

        public MyClass()
        {
            myObject = new object();
            (myObject as Label).Width = 100;
        }
    }

in both of them cast is needed and no error happens.


Solution

  • No compile time error happens. At runtime in the second code block, you'll get the exception that an object really isn't a Label and can't be cast as such.

    Because every .NET type inherits from object, you can assign any type to your object myObject; field. In your first code block, a Label instance is assigned to it. You can cast it back to a label as happens at (myObject as Label), because you actually stored a Label in it.

    Your second code example stores an object, which isn't a Label, so it can't be cast.