roymcclure
roymcclure

Reputation: 404

Retrieve an object's class

Right now, this is what I am doing to obtain the class of elements in my WPF canvas:

    // for instance
    private void R_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
    {
        if (sender.ToString() == "System.Windows.Shapes.Rectangle")
        {
            // ok i am a rect
            System.Windows.Shapes.Rectangle r = (System.Windows.Shapes.Rectangle)sender;
            //etc...
        }
    }

Somehow I feel there is a more elegant way of doing this. Something in the lines of:

    if (class(sender) == System.Windows.Shapes.Rectangle) ...

In other words, is there reflection in C# and if not, how to emulate it?

Upvotes: 0

Views: 51

Answers (1)

René Vogt
René Vogt

Reputation: 43896

You are probably looking for the is operator:

if (sender is System.Windows.Shapes.Rectangle)
    // it's a rectangle

Or maybe better use the as operator:

System.Windows.Shapes.Rectangle rect = sender as System.Windows.Shapes.Rectangle;
if (rect != null)
{
   // do something with rect
}

but this will only work for classes, not for structs or other value types. If sender is not of that type, rect will be null (a direct cast like (Rectangle)sender would throw an InvalidCastException instead).


Note that both operators also work for base types. So if sender really is a Rectangle, sender is Shape will also return true.

Upvotes: 7

Related Questions