6 Ağustos 2015 Perşembe

Avoiding casting multiple times


((Button)sender).Text = "Test1";
(sender as Button).BackColor = Color.Red;
((Button)sender).Width = 120;
((Button)sender).Height = 45;
(sender as Button).TextAlign = ContentAlignment.MiddleCenter;

warning  : CA1800 : Microsoft.Performance : 'sender', a parameter, is cast to type 'Button' multiple times in method 'FormMain.btnTest_Click(object, EventArgs)'. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant castclass instruction.
warning  : CA1800 : Microsoft.Performance : 'sender', a parameter, is cast to type 'Button' multiple times in method 'FormMain.btnTest_Click(object, EventArgs)'. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant castclass instruction.
warning  : CA1800 : Microsoft.Performance : 'sender', a parameter, is cast to type 'Button' multiple times in method 'FormMain.btnTest_Click(object, EventArgs)'. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant isint instruction.
warning  : CA1800 : Microsoft.Performance : 'sender', a parameter, is cast to type 'Button' multiple times in method 'FormMain.btnTest_Click(object, EventArgs)'. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant isint instruction.
warning  : CA1800 : Microsoft.Performance : 'sender', a parameter, is cast to type 'Button' multiple times in method 'FormMain.btnTest_Click(object, EventArgs)'. Cache the result of the 'as' operator or direct cast in order to eliminate the redundant isint instruction.


Recommended fix:

Button currentButton = sender as Button;
if (currentButton != null)
{
    currentButton.Text = "Test1";
    currentButton.BackColor = Color.Red;
    currentButton.Width = 120;
    currentButton.Height = 45;
    currentButton.TextAlign = ContentAlignment.MiddleCenter;
}

Hiç yorum yok :

Yorum Gönder