Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi code project...
i want to get the type of class
example: i have class name A
ClassA : System.Windows.Forms.Form

and then i have classB which ClassB : ClassA -- Inherits
and then i have class C which ClassC : ClassB
and class D which ClassD : ClassB too.

i use this class C for show data
frmViewData : ClassC

when i show this frmViewData on mdiForm.. i want to check if frmViewData is ClassC.

example.

C#
void toolStripView_click (object sender, EventArgs e)
{
  frmViewData f = new frmViewData;
  f.MdiParent = this;

  //i try this but not work
  if ( f.GetType() == typeof(classC)
  {
    f.SomeCustomProperties = //Some custom value;
  }
  f.Show();
}

this code is not work. when i check using messagebox
C#
void toolStripView_click (object sender, EventArgs e)
{
  frmViewData f = new frmViewData;
  f.MdiParent = this;
  MessageBox.Show(f.GetType().ToString());

}

the result is " WinnSystem.frmViewData " at messagebox.
is that any other way to check the class ??

thx a lot.
Posted

something.GetType() == typeof(someOther) checks whether the type of something is equal to the type of someOther. If you want to check whether something inherits from someOther then use the keyword is:
C#
if (f is classC)
{
  // ...
}


Edit: In case the types are equal, is will also return true (so not only for actually derived types).

Edit 2: As PIEBALDConsult has pointed out in his solution, there are alternatives: Type.IsAssignableFrom(..) and Type.IsInstanceOfType(..) that do (mostly) the same thing as the keyword is. Which one is most convenient to use depends on what you have to compare to what (an instance of an object / a type object / a static type). See here:
http://stackoverflow.com/questions/15853159/isassignablefrom-isinstanceoftype-and-the-is-keyword-what-is-the-difference[^]
 
Share this answer
 
v3
Comments
Afzaal Ahmad Zeeshan 3-Apr-15 13:34pm    
+5
Sascha Lefèvre 3-Apr-15 13:46pm    
Thank you, Afzaal!
I use Type.IsAssignableFrom : https://msdn.microsoft.com/en-us/library/system.type.isassignablefrom(v=vs.110).aspx[^]

typeof(classC).IsAssignableFrom(f.GetType())
 
Share this answer
 
Comments
Sascha Lefèvre 3-Apr-15 13:54pm    
My 5
Use reflection - Type superClass = frmViewData.GetType().BaseType;
 
Share this answer
 
all solution is good..thx by the way
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900