Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

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);
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top