Note that there are some explanatory texts on larger screens.

plurals
  1. POC# + WPF : how should I do proper checks/guards/casts when accessing control values?
    primarykey
    data
    text
    <p>This is probably pretty basic, but I'm just picking up C# after many years working with other languages, and I've unfortunately grown used to loose and dynamic typing. Now, in building a WPF form with a lot of checkboxes, I notice that my code to do simple things like determine whether a checkbox is checked is actually quite complicated due to the need to check for nulls and cast the results. I end up with helper functions like:</p> <pre><code> private bool isChecked(CheckBox control) { return control != null &amp;&amp; control.IsChecked != null &amp;&amp; control.IsChecked.HasValue &amp;&amp; (bool)control.IsChecked; } </code></pre> <p>so that in my logic code, I can just do</p> <pre><code> if (isChecked(opticsCheckBox)) { // whatever I need to do if opticsCheckBox is checked } </code></pre> <p>Is this the normal way of doing things in C# (with WPF), or am I missing something simple? Basically I'm finding the nested layers of conditionals to check every object for null all the time to be a warning sign of bad code (and the fact that I could forget a check). Not sure what I should be doing though.</p> <p>Should I be using try ... catch everywhere even though the control not being present or checked isn't really an exceptional condition? That seems to me like it would end up being just as cluttered.</p> <p>Another example to clarify: When I would like to write something like:</p> <pre><code> maxWeight = (int)maxWeightComboBox.SelectedItem; </code></pre> <p>I find myself instead writing:</p> <pre><code> if (maxWeightComboBox != null &amp;&amp; maxWeightComboBox.SelectedItem != null) { ComboBoxItem item = (ComboBoxItem)maxWeightComboBox.SelectedItem; maxWeight = Int32.Parse(item.Content.ToString()); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload