1

Possible Duplicate:
C# - Assignment in an if statement

I find my myself doing the following multiple time

if (e.row.FindControl("myLiteral") is Literal)
{
    (e.row.FindControl("myLiteral") as Literal).Text = "textData";
}

Is there way to replace the "if" part and simplify the setter:

(e.row.FindControl("myLiteral") <some operator that combines is and as> .text = "textData";

EDIT: I should have mentioned this before- I want to remove the 'if' entirely.
"some operator " should do this internally and set the ".text" only if e.row.FindControl is a literal

Community
  • 1
  • 1
Bitmask
  • 918
  • 2
  • 11
  • 22

6 Answers6

6

Normally I wouldn't combine them like that to start with - I'd either use a cast or I'd use as and a null check:

Literal literal = e.row.FindControl("myLiteral") as Literal;
if (literal != null)
{
    literal.Text = "textData";
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

There is no built-in way to do this. However you could author an extension method which gives you this capability

public static void AsType<T>(object o, Action<T> action) where T : class
{
    var value = o as T;
    if (value != null)
    {
        action(value);
    }
}

You could then write

e.row.FindControl("myLiteral").AsType<Literal>(l => l.Text = "textData");
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
1

the as operator already does an is. If the cast succeed it returns the casted value, otherwise it returns null.

Literal lit = e.row.FindControl("myLiteral") as Literal;
if (lit != null)
{
    lit.Text = "textData";
}

or

if (e.row.FindControl("myLiteral") is Literal)
{
    Literal lit = (Literal)e.row.FindControl("myLiteral");
    lit.Text = "textData";
}
meziantou
  • 20,589
  • 7
  • 64
  • 83
1

A check using is is typically followed by a cast:

if (e.row.FindControl("myLiteral") is Literal)
{
    ((Literal)e.row.FindControl("myLiteral")).Text = "textData";
}

Whereas as functions as such a check that returns either a successfully cast instance or null to the assigned variable, which you can then check for null (See @Jon Skeet's answer).

Community
  • 1
  • 1
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
0

You could do:

var literal = e.row.FindControl("myLiteral") as Literal;
if (literal != null)
{
    literal.Text = "textData";
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

Well, you could use as more like this (the standard usage):

Literal lit = e.row.FindControl("myLiteral") as Literal;
if (lit != null) {
  lit.Text = "textData";
}

If you're using .Net 3.5 or greater you could create an extension method to handle this (kind of):

internal static class Extensions {
  internal static void SetTextLiteral(this Control c, string text) {
    Literal lit = c as Literal;
    if (lit != null)
      lit.Text = text;
  }
}

void Sample() {
  e.row.FindControl("myLiteral").SetTextLiteral("textData");
}
Joshua
  • 8,112
  • 3
  • 35
  • 40