C# .NET Programming Tip: Types

Figuring out a variable’s type has become more important since now variables can be boxed by their parent class(s) (Where all can be “Object”). It’s nice because it allows for one generalized function to work with many types that perform an action on a common attribute, or first figure out what the object is and then perform the action.

That is one of the instances where figuring out a variables type is important.

.NET has a built-in function called GetType() which figures out what type a variable is.

//loop through the controls in the panel anf figure out which of the checkboxes are checked
foreach (Control panelControl in newCheckListQuestionPanel.Controls)
{
   //only continue if this control is a checkbox
   if (panelControl.GetType().ToString().Equals("System.Windows.Forms.CheckBox") == true)
   {
       if (((CheckBox)panelControl).Checked == true)
       {
           //do something here if the control is checked
       }
   }
}
This entry was posted in General and tagged , , , . Bookmark the permalink.