Value Assigned Is Not Used - c#

I may be overlooking something, well obviously I am. I am using an uninitialized variable of type int (carRequired). I am utilizing this variable inside an IF statement (code below). However, I get a warning stating the variable is never used yet it is. Yes, I am aware of not being good practice to embed sql, however I am told to do it this way for now.
public bool UpdateDiscrepancyReport()
{
var errorStatus = false;
int carRequired ;
carRequired = cbxCarRequired.Checked == false ? 0 : 1;
var updateQuery = "my query string ";
dbf.OpenConnection(updateQuery);
bool updateStatus = dbf.OpenConnection(updateQuery);
if (updateStatus)
{
errorStatus = true;
}
else
{
MessageBox.Show(#"Error in updating DR" + tbxDRNumber.Text+#" ",#"Update Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return errorStatus;
}

The variable is never used. It is assigned to, but the variable is never used after that assignment; you don't do anything after assigning the result of the ternary operation to it. In fact, the variable isn't necessary at all, and neither is errorStatus (in the original code you posted), since you never do anything in the code that will change it's value after it is initialized.
The code you've posted (prior to your edit that added several more lines) is the exact equivalent of
public bool UpdateDiscrepancyReport()
{
dbf.OpenConnection(updateQuery);
return false;
}
The compiler is telling you that the variable declaration and assignment to carRequired is meaningless, because it does not affect anything in your code. Determining whether the checkbox is checked or not only has meaning if your code does something differently based on that information, and the use of carRequired as written does nothing based on the value assigned; therefore, the assignment (and variable declaration) are useless.

Related

Field is never assigned to and will always have its default value 0

I get the following error in my code and I'm not sure why:
Warning - 'SummaryForm.m_difficulty' is never assigned to, and will always have its default value 0
Code
public partial class SummaryForm : Form
{
// Declares variables with the values pulled from the 'MainForm'
int iCorrectACount = MainForm.iCorrectACount;
int iCurrentQIndex = MainForm.iCurrentQIndex;
private Difficulty m_difficulty;
public SummaryForm()
{
InitializeComponent();
double modifier = 1.0;
if (m_difficulty == Difficulty.Easy) { modifier = 1.0; }
if (m_difficulty == Difficulty.Medium) { modifier = 1.5; }
if (m_difficulty == Difficulty.Hard) { modifier = 2; }
// Sets the labels using integer values
lblCorrectNum.Text = iCorrectACount.ToString();
lblWrongNum.Text = (iCurrentQIndex - iCorrectACount).ToString();
lblScoreTotal.Text = (iCorrectACount * modifier).ToString();
}
Maybe this has something to do with why lblScoreTotal.Text will not change to the value * modifier but will on another form?
The reason I asked this question here is because someone advised me to disable warning messages but I didn't think that was the appropriate solution?
Thanks.
The compiler is entirely correct: nothing is going to change your m_difficulty field, as far as you've shown. What do you expect to set that value? Did you actually mean to set it to something based on MainForm as per iCorrectACount and iCurrentQIndex?
How do you expect it would ever be anything other than whatever (Difficulty) 0 evaluates as?
It's pretty dodgy to be pulling initial values from a statically-accessed instance of a form, too, IMO. It would be much better if the constructor accepted initial values from whatever was constructing it.
m_difficulty is private, so it can't be accessed from outside your class, but you never assign it inside, so it will never change.
Therefore, it makes no real sense to compare it, as it will always be equal to 0.
You should always initialize a variable after you declared it.
private Difficulty m_difficulty = new Difficulty();
Something like that.
So you prevent it to be null (in this case you would get an exception).
The warning just tells you this.
It sounds to me like you're expecting m_difficulty to be bound to a dropdown selection on your user form. It is not. Even if it were, you would want to access the SelectedValue property instead of the object itself. Maybe this is what you're looking for.
Difficulty m_difficulty = (Difficulty)Enum.Parse(ddDifficulty.SelectedValue);

How to tell if an out parameter was set already?

Is there a way to know if an out parameter was set already or not. This is the pseudocode for what I am looking for:
public virtual string blabla(long num, out bool bval)
{
if (!bval.HasValue)
{
//Do some default logic
bval = defaultValue;
}
return blabla2(num, bval);
}
You can't - you can't read the variable until it's been definitely assigned within your method. You should think of it as being like a local variable, declared but not assigned any value at the start of the method - but which you must assign a value to before you return. (It's okay not to have assigned a value to it if an exception is thrown.)
If you want a parameter which carries information as input to the method as well as propagating information out, you should use ref instead of out.
See my article on parameter passing for more information.
In addition to Jon's excellent answer, if you want the parameter to still be out, but need to see if it has been assigned a value at some place inside the method, you could use a local nullable type like follows:
public virtual string blabla(long num, out bool bval)
{
bool? bvalLocal;
... //I'm assuming there is some code here that may or
//may not assign bvalLocal?
// This whole if block may not be needed if the default
// value is the default for the type (i.e. false) as
// GetValueOrDefualt() will take care of that (see
// second to last line).
if (!bvalLocal.HasValue)
{
//Do some default logic
bvalLocal = defaultValue;
}
bval = bvalLocal.GetValueOrDefault();
return blabla2(num, bval);
}

Question about compilation error related to a use in the keyword/reserved word "out"

Hello
I'm having an error with this code:
"The out parameter 'o_BlockingSquaresArr' must be assigned to before control leaves the current method"
Now this error paints each return statement of each method apart from the last one with red..
I don't understand what is the problem regarding my specific code
Please help me,
Thanks in Advance
internal bool isLegalMove(Square i_Move, out List<Square> o_BlockingSquaresArr)
{
bool result;
if (m_GameBoard[i_Move.RowIndex, (int)i_Move.ColIndex].Coin != null)
{
result = false;
m_MessageBuffer = "You have enterd a square which is already
occupied, please try again...";
m_ErrorFlag=true;
}
else
{
result = checkIfThereIsAtLeastOneSeqInOneDirection(i_Move,out o_BlockingSquaresArr);
}
return result;
}
internal bool checkIfThereIsAtLeastOneSeqInOneDirection(Square i_Move, out List<Square> o_BlockingSquaresArr)
{
const int k_EightDirections = 8;
bool isSequenceFound, finalRes = false;
for (int i = 1; i <= k_EightDirections; i++)
{
isSequenceFound = checkOpponentSequenceInDirection(i_Move, (eDirections)i, out o_BlockingSquaresArr);
if (isSequenceFound)
{
finalRes = true;
}
}
return finalRes;
}
internal bool checkOpponentSequenceInDirection(Square i_Move, eDirections i_Direction, out List<Square> o_BlockingSquaresArr)
{
//I've shortened this code only relevant things
Square o_AdjacentSquare = new Square();
adjacentCoin = doSwitchAndRetrieveAdjacentCoin(i_Move, i_Direction, out o_AdjacentSquare);
// ...
if (isThereAnOpponentSequence)
{
o_BlockingSquaresArr.Add(o_AdjacentSquare);
}
return isThereAnOpponentSequence;
}
As the compiler error says, an out parameter has to be definitely assigned before any non-exceptional return of a method. I can't see any assignment to o_BlockingSquaresArr anywhere. Why are you even declaring it as an out parameter to start with?
An out parameter must be assigned a value before the method returns. In your isLegalMove method, o_BlockingSquaresArr is only assigned in the else block, so the compiler detects there are some cases where it is not initialized. You must make sure that all code paths in the method assign a value to o_BlockingSquaresArr before returning
You need to assign something to the out parameter in every execution path. In your case, you forget that in one case. Simply assign a default value of the beginning of the method so you don't run into it.
I can't tell you where as you didn't include the method name it is happening in.
In the IsLegalMove function, you need to assign a value to the o_BlockingSquaresArr variable
You need to assign something to out parameters in every (normally terminating) codepath. And you don't do that.
For example in some functions you only assign to the parameter inside the for-loop. And if the loop has 0 iterations this will never happen.

c# Object obj's value is {}. What is "{}"?

I'm using some old code that runs a sql query as a reference.
At some point, it gets to something like:
sqlDataAdapter.Fill(dataSet);
DataRow dataRow = dataSet.Tables[0].Rows[0];
Object obj = dataRow[fieldName];
The old code does:
string output;
if (!string.IsNullOrEmpty(obj.ToString())) { output = obj.ToString(); }
else { output = "Not Available"; }
I changed them to:
output = obj as string ?? "Not Available"
But sometimes, it broke. As I suspected, it was happening breaking when the entry was an int. Casting as an int in those cases solved that problem.
Then another problem arose when there was no entry for obj[fieldName] of type int. When I stepped through the debugger, I was surprised to find that obj wasn't null. In VS, mousing over revealed it had a value {}.
What the heck is {}? How do I make a boolean test of it?
(In the old code, it appears .ToString() returns "" in this case and works as expected.)
{ and } are opening and closing braces and symbolic of the start and finish of an object. Hence an empty object with no special properties is depicted in shorthand as {}. The debugger uses this notation to help you visually distinguish between an empty object, an empty string and null.
If you hover over obj[fieldName] and there is no entry for fieldName, the debugger won't care about that, it'll show the value of obj. You'll have to use the immediate window or a watch/quickwatch. The debugger will only see you hovering over obj and assume you're referring to the array itself, not the contents of the array at the specified index.
In case anyone comes across again this problem.
Solution if val object is shown {} in debug mode
// Check if its not null or empty
if (!IsNullOrEmpty(val.ToString().ToArray()))
{
// Do something with val
dt.Rows.Add(val);
}
public static bool IsNullOrEmpty<T>(T[] array)
{
return array == null || array.Length == 0;
}

Getter/Setter problem in C#

I am doing
static bool isWorking
{
get { return _isWorking; }
set {
myform.treeView1.Enabled = !value;
_isWorking = value;
}
}
and stepping through the debugger shows it stops at the first set line.
After trying this line instead
set { myform.treeView1.Enabled = !(_isWorking = value); }
I see that isWorking is set but myform.treeView1.Enabled is not. Whats going on?
What do you mean by "the debugger shows it stops"? Is it possibly that myform is null, or myform.treeView1 is null?
I can't remember the exact evaluation order in this case, but it could explain the symptoms you're describing. Knowing why the debugger "stops" is crucial though. Another possibility is that you're trying to access the UI from a non-UI thread, which would prevent the assignment to Enabled from working properly.
Oh, and please don't use your second version - assignment as a side-effect is very, very rarely a good idea. The only idiomatic use I know is when looping with IO:
string line;
while ( (line = reader.ReadLine()) != null)
and I only consider that acceptable because it's reasonably common. In this case it really looks like you could mean "==" instead of "=".
Because (_isWorking = value) returns always true. If you would write:
myform.treeView1.Enabled = !(_isWorking == value);
It works like: if isWorking is equal to value then Disable treeView. But in you case - no

Categories