Home
Do you initialize variables outside of the try block?
  v1.0 Posted at 27/04/2018 7:45 AM by Tiago Araujo

You should initialize variables outside of the try block.​

Cursor cur;
try
{
...
cur = Cursor.Current; //Bad Code - initializing the variable inside the try block
Cursor.Current = Cursors.WaitCursor;
...
}
finally
{
Cursor.Current = cur;
}

Bad Example: Because of the initializing code inside the try block. If it failed on this line then you will get a NullReferenceException in Finally

Cursor cur = Cursor.Current; //Good Code - initializing the variable outside the try block
try
{
...
Cursor.Current = Cursors.WaitCursor;
...
}
finally
{
Cursor.Current = cur;
}

Good Example : Because the initializing code is outside the try​​​ block​​

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments:

    Note: Social Media login for Yotpo is not working in IE or Safari, please use Chrome. We are waiting for Yotpo to fix it.