none
How to find out what type an object is? - C# RRS feed

  • General discussion

  • 1. I have a function that has one formal parameter (an object) (e.g. ' void abcd (object ob) ' 

    2. When I call the function abcd, the object could be anything (e.g. a button, a pictureBox, a panel, etc.)

    3. Question: How can I find out what kind of object (the object form the actual parameters of my function) is?

    E.g.:

    void abcd(object ob)
    {
     /// code ///
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
       abcd(pictureBox1); // or 'abcd(panel1);' or 'abcd(button3);' or etc. 
    }

    Please help!!!

    Monday, February 24, 2014 4:37 PM

All replies

  • Has nothing to do with Windows Forms beside that you want to know it inside a method which is handled inside a click event. 

    Why not take the C# forum?

    http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=csharpgeneral

    In VB it is GetType


    Success
    Cor

    Monday, February 24, 2014 4:52 PM
  • Ok....sorry
    Monday, February 24, 2014 4:55 PM
  • void abcd(object ob) { /*if You want to get the name of the control and handle it differently based on the name Control theControl = ob as Control if ( theControl == null) return;//ob is not a control */ if (ob is Button) { //Handle code for button } elseif (ob is PictureBox) { //Handle code for PictureBox } } private void button1_Click(object sender, EventArgs e) { abcd(sender); }

    Try the above code
    Monday, February 24, 2014 4:57 PM
  • To answer your question - use the GetType() method to retrieve the complete Type definition for any object and compare that to known types or use the "Is" operator. 

    void abcd( object ob ) 
    {
       if ( ob.GetType() == typeof( System.String ) ) 
          // Exact Type match only 
    
       if ( ob Is System.String ) 
          // Matches named Type and any subclass thereof 
    }
    

    Alternatively (and, these days, preferably), clean your code up by "filtering" data types at the point of calling the method - overload your methods to only take specific Data Types are arguments: 

    void abcd( object arg ) 
    {
       // Called when arg is an object 
    }
    
    void abcd( string arg ) 
    {
       // Called when arg is a string 
    }
    



    Regards, Phill W.

    Tuesday, February 25, 2014 12:55 PM
  • I've answered this in the C# forums after about an half hour when OVlad has asked it there.


    Success
    Cor

    Tuesday, February 25, 2014 4:51 PM