Im trying to assign a decimal value of 1 to a variable if a check box is checked but I having trouble getting it to work. Here is my code:
decimal nitrodsgn;
decimal lnitro;
decimal unitro;
if (nitrogenLowerCheckBox.Checked)
lnitro = 1;
if (nitrogenUpperCheckBox.Checked)
unitro = 1;
nitrodsgn = (lnitro + unitro)

Dani AI

Generated

Two things are worth clarifying from the snippets above. The immediate, common compile-time problem is definite assignment: lnitro and unitro are declared but only set inside if blocks, so the compiler can see a path where they are never assigned. That causes a "Use of unassigned local variable" error when you try to add them. 's point about decimal literals is also relevant for non-integer literals, but an integer literal like 1 is implicitly convertible to decimal — using m (for example 1m) makes the intent explicit.

A safe, clear fix is to initialize the temporaries to zero or compute the sum inline. Example patterns:

decimal lnitro = 0m;
decimal unitro = 0m;

if (nitrogenLowerCheckBox.Checked)
{
    lnitro = 1m;
}
if (nitrogenUpperCheckBox.Checked)
{
    unitro = 1m;
}

decimal nitrodsgn = lnitro + unitro;

Or compute directly without temporary variables:

decimal nitrodsgn =
    (nitrogenLowerCheckBox.Checked ? 1m : 0m) +
    (nitrogenUpperCheckBox.Checked ? 1m : 0m);

Notes: if only counting checked boxes, int is simpler (no m suffix needed), e.g. int count = (chk1 ? 1 : 0) + (chk2 ? 1 : 0);. Also remember the ASP.NET page lifecycle when reading Checked — read it after view state has been restored (for example in event handlers or Page_Load after postback) so the control state reflects the user selection.

To assign a decimal like that at compile time you need to use a suffix to instruct the compiler what data type to use.

decimal d = 1.0m;
float f = 1.0f;

The default for non-integral numbers is double.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.