SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

  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

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

Your Answer


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.