Paul Böttger
Paul Böttger

Reputation: 45

Casting and using the result in one line

I want to cast WrapPanel

wp = (WrapPanel)topSP.Children[0];
wp.Children.Add(txtB1);

so that it looks something like that

topSP.Children[0](WrapPanel).Add(txtB1);

is that possible?

Upvotes: 0

Views: 93

Answers (4)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

Another way of changing the type is this:

(topSP.Children[0] as WrapPanel).Children.Add(txtB1);

This is not the same as a cast, as if topSP.Children[0] is not a WrapPanel, this will throw a NullReferenceException, as in that case (topSP.Children[0] as WrapPanel) == null.

Upvotes: 1

Emond
Emond

Reputation: 50672

Yes you can but all this 'chaining' of properties and casts can cause a lot of work when chasing null reference and index out of range exceptions. Keep them on separate lines and check for nulls and index ranges.

So even though this might work:

((WrapPanel)topSP.Children[0]).Children.Add(txtB1);

It is much safer to do this:

if(topSP.Children.Count > 0)
{
    var wrapPanel = topSP.Children[0] as WrapPanel;
    if(wrapPanel != null)
    {
        wrapPanel.Children.Add(txtB1);
    }
}

Upvotes: 2

Rohit Vats
Rohit Vats

Reputation: 81243

Wrap cast in parenthesis and you are good to go -

((WrapPanel)topSP.Children[0]).Children.Add(txtB1);

Upvotes: 1

nvoigt
nvoigt

Reputation: 77294

((WrapPanel)topSP.Children[0]).Children.Add(txtB1);

Note that there probably is a better way. But this should work.

Upvotes: 4

Related Questions