Reputation: 85
I'm trying to learn some C#, one of the code snippets I found used:
(CheckBox)c
(Where c was the result of foreach)
I get that it's doing this so that the compiler knows that c will behave as a checkbox, my question is: what is this type of construction called? I'd like to be able to google to understand it better.
Thanks!
Upvotes: 3
Views: 138
Reputation: 1762
It casts the c variable to type CheckBox. I think in your example it is a object the variable c, and if you then convert it to CheckBox, you get access to all the properties like "IsChecked" "Name" etc
In other words.
before the cast:
bool isItChecked = c.IsChecked; // this would not compile because object does not have a property "IsChecked"
So to get this working we must tell the compiler that the variable c is of type CheckBox like this:
var checkBoxC = (CheckBox)c; // The Cast
bool isItChecked = checkBoxC.IsChecked; // access the casted items properties.
Here is a good beginners tutorial on typecasting, you should check "Explicit casts" because that is what you are doing.
PS: This is needed because c# is strongly typed and not weakly typed.
Upvotes: 2
Reputation: 3363
It is called "Casting" or "UnBoxing"
static private void TestBoxingAndUnboxing()
{
int i = 123;
object o = i; // Implicit boxing
i = 456; // Change the contents of i
int j = (int)o; // Unboxing (may throw an exception if the types are incompatible)
}
//this function is about 2*Log(N) faster
static private void TestNoBoxingAndUnboxing()
{
int i = 123;
i = 456; // Change the contents of i
int j = i; // Compatible types
}
Understand the difference between two, although they are doing the same thing.
Upvotes: 1
Reputation: 9294
This is called casting. You do this when you know that the type of 'c' will be Checkbox when the code executes. However, it is possible that c is not a Checkbox, in which case you will get an InvalidCastException.
In truth, C# provides many constructs to avoid casting, like Generics and Generic Type Constraints
As a rule of thumb: only use casting when you really cannot avoid it.
Upvotes: 1
Reputation: 4030
That we call casting
. See MSDN. Some tutorials: one and two
You also have something related that is called boxing and unboxing
. MSDN
What your example does is letting you know that the object c
is actually a checkbox
. That way you can access all the properties of a checkbox
.
Upvotes: 1
Reputation: 12513
It's called a cast. As you say, it's used here to tell the compiler that c
is in fact a checkbox. There is also a longer article on casting on MSDN. In case of foreach
with a non-generic IEnumerable
, which I think is what you're doing, there are also two ways to avoid this cast in the loop body:
for (CheckBox c in xs) {
}
for (var c in xs.Cast<CheckBox>()) {
}
Both pieces of code expose c
as a CheckBox
now, eliminating the need for a cast. I'd probably use the first one, as it's the most idiomatic (as well as the approach familiar from .NET 1.1 and Java).
Upvotes: 4