Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I am running MSOCAF on my custom SharePoint 2010 solution. Its complaing about following piece of code.

for(i=0;i<Page.Control.Count;i++)
{
  Control ctrl=Page.Controls[i];

  if(ctrl is Button)
  {
   var t= ctrl as Button;
  }
  else if(ctrl is Label)
  {
    var l=ctrl as Label;
  }


 ........

.........
 if(ctrl is LinkButton)
  {
   var l=ctrl as LinkButton;
  }

}

I need to perform this check for all control types and then do some code inside the IF block. MSOCAF reports out that its unnecessary casting inside the loop and the casting result should be cached. But as you can see its not possible as there are different control on the page. Could you please suggest some alternate to achieve the same kind of type checking and casting?

share|improve this question
add comment

1 Answer 1

The as operator is a safe cast;

The as operator is like a cast except that it yields null on conversion failure instead of raising an exception.

So you don't need to use the is operator, your var will simply be null.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.