Question

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.

Was it helpful?

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.

OTHER TIPS

Here's my code to cast an object as label that i've discored while searching for the same solution:

    private void modeloUserControl_Click(object sender, EventArgs e)
    {

        Label label = (Label)sender;
        MessageBox.Show(label.Text);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top