Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"is"-reference or gettype()

I'm searching inside some controls in my WinForms Form, with the help of foreach statements. I'm comparing the object i find through a "is"-reference (a is DataGridView). With "a" being an object in a control collecion. That works fine so far, because the compared objects on my form are all sufficiantly different from one another.

In a new form i created i'm using a derived version of a DataGridView called my_datagridview. So when a my_datagridview is compared to a DataGridView through a "is"-reference no exception is thrown, which is "wrong" cause i want to handle the two seperately.

Is there a way to compare my_datagridview and DataGridView properly?

like image 964
Rufus Avatar asked Feb 03 '26 12:02

Rufus


2 Answers

Is there a way to compare my_datagridview and DataGridView properly?

One option would be to use something like:

if (a is MyDataGridView) // Type name changed to protect reader sanity
{
}
else if (a is DataGridView)
{
    // This will include any subclass of DataGridView *other than*
    // MyDataGridView
} 

Or you could use GetType() to match exactly, of course. The important question is what you would want to happen with any other classes derived from DataGridView or even from MyDataGridView.

like image 73
Jon Skeet Avatar answered Feb 05 '26 02:02

Jon Skeet


Yes. Start with the most specific class first. So:

if (a is my_datagridview)
{
    //....
}
else if (a is DataGridView)
{
    // ....
}

See MDSN here.

like image 30
Matt Burland Avatar answered Feb 05 '26 02:02

Matt Burland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!