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

Help Support This Website:

Buying something through these Amazon affiliate links within 24 hours of clicking could help me out at no additional cost to you:
USA, UK, Canada, Germany, Spain, France, and Italy

Direct Donation Links:
Paypal, Buy Me A Coffee, or Ko-Fi

This entry was posted in General and tagged , , , . Bookmark the permalink.