views:

59

answers:

4

Take a look at the following. The question near the end of the code - in the "whoAmI" function...

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MY_TEST_PROJECT
{
    // a form class
    public partial class frmTestForm1 : Form
    {
        // zillion lines of code

        private void aFunction()
        {        
            ClassTest.whoAmI(this);
        }

        // zillion lines of code
    }

    // another form class...
    public partial class frmTestForm2 : Form
    {
        // zillion lines of code

        private void aFunction()
        {        
            ClassTest.whoAmI(this);
        }

        // zillion lines of code
    }

    // a home made test class
    public static class ClassTest
    {
        // zillion lines of code

        public static void whoAmI(Form theForm)
        {
            // IS THERE A WAY TO SEE WHAT KIND OF FORM theForm IS?

            // LIKE:
            // if (theForm IS A frmTestForm1)
            //   doThis();
            // else if (theForm IS A frmTestForm2)
            //   doThat();
        }

        // zillion lines of code
    }
}
+3  A: 

You can check with the keyword is.

Also, you might want to solve your problem using polymorphism instead of checking the type.

Sjoerd
"if (theForm is frmTestForm1)" is working fine! Thanks!!!
Jack Johnstone
A: 

Did you try this and it is not working? There is no problem trying to get a type from an object. Although you are sending it in as the base type the object still is a derived class type.

spinon
+2  A: 

There are few ways you can do this:

  • as you have guessed you can use "is" key word as Sjoerd has proposed
if (theForm is frmTestForm1)
   doThis();
//So on
  • Another approach is to use reflection to get the exact type of the form you have. Your code should look like somthing like this:

if (theForm.GetType().UnderlyingSystemType == typeof(frmTestForm1)) doThis();

The drawback of the first approach is that if, for example, your frmTestForm2 is derivative of frmTestForm1 and you use code like this if(yourform is frmTestForm1) and your form is pointing to a frmTestForm2 instance "is" keyword will return true.

Koynov
OK, good-to-know things!
Jack Johnstone
A: 
if (theForm.GetType().ToString() == typeof(frmTestForm1).ToString())
{
    // Do your stuff
}
Miel
I didn't know about `UnderlyingSystemType`, which Koynov uses. I now prefer his answer.
Miel