Question

I have been using this ((Control)name) for some time, but I don't understand the construction of the brackets and what that means.

For example, when I'm looping through controls on a page, I do so like this:

foreach (Control ctrl in Booking_Quote.Controls)
{
    if (ctrl is Panel)
    {

        foreach (Control tb in ctrl.Controls)
        {
            if (tb is TextBox)
            {
                ((TextBox)tb).Text = "Hello world";

            }
            else
            {

            }
        }
    }
}

I am looking to know what ((TextBox)tb) means.

Was it helpful?

Solution

It means that you're casting your object to TextBox (or Control)

In your example, you wrote this:

if (tb is TextBox)
{
   ((TextBox)tb).Text = "Hello world";
}

If tb is a TextBox, then you cast your object to a TextBox to have access to its methods and set values as you want.

You can do a explicit cast, which will throw an exception if the cast fails, OR you can convert your object, using the as operator, which will return null if the conversion fails, like this:

(tb as TextBox).Text = "Hello world";

OTHER TIPS

That is a type cast to let the compiler know that the tb object is a actually a TextBox object.

It is the cast operator. In this code:

if (tb is TextBox)
{
    ((TextBox)tb).Text = "Hello world";
}

You're casting tb to TextBox type, to get access to the Text property. Without the cast it would remain of Control type and the Text property would not be available to you.

As a Control may not have a Text property, it first checks if the current Control tb is a TextBox via the line

if (tb is TextBox)
{
....
}

Then before using the Control tb as a TextBox you first need to explicitly cast it to TextBox in order to access the Text property.

You do this by preceding a variable with a Type object within parentheses, in this case (TextBox) tb

See Casting and Type Conversions (C# Programming Guide)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top