I'm currently adding some new extended classes to this code:
foreach (BaseType b in CollectionOfExtendedTypes) {
if (b is ExtendedType1) {
((ExtendedType1) b).foo = this;
}
else if (b is ExtendedType2) {
((ExtenedType2) b).foo = this;
}
else {
b.foo = this;
}
}
and was curious if there is a way to use the is
keyword functionality in a switch statement?
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Here, We can define various statements in the multiple cases for the different values of a single variable.
A general syntax of how switch-case is implemented in a 'C' program is as follows: switch( expression ) { case value-1: Block-1; Break; case value-2: Block-2; Break; case value-n: Block-n; Break; default: Block-1; Break; } Statement-x; The expression can be integer expression or a character expression.
switch(f1) // same reason as above. switch("string") // string is not allowed.
The switch keyword is probably the least well understood of the C/C++ language keywords (although, const probably comes a close second). The keywords switch , case , and default always go together and cannot be used independently in any other context. There is a small difference in behaviour between C and C++.
The latest version of C# (7) now includes this functionality
Type pattern
The type pattern enables concise type evaluation and conversion. When used with the switch statement to perform pattern matching, it tests whether an expression can be converted to a specified type and, if it can be, casts it to a variable of that type. Its syntax is:
case type varname
This really looks like a situation for a good polymorphic implementation. If you override the appropriate methods in the derived classes, you may not need the checks in the loop at all.
Nope. See
C# switch statement limitations - why?
In C# it's not possible to use the "is" keyword as part of a switch statement. All case labels in a switch must evaluate to constant expressions. "is" is not convertible to a constant expression.
I definately feel the pain though when it comes to switching on types. Because really the solution you outlined works but it's a conveluted way of saying for x do y, and a do b. It would be much more natular to write it more like the following
TypeSwitch.Do(
sender,
TypeSwitch.Case<Button>(() => textBox1.Text = "Hit a Button"),
TypeSwitch.Case<CheckBox>(x => textBox1.Text = "Checkbox is " + x.Checked),
TypeSwitch.Default(() => textBox1.Text = "Not sure what is hovered over"));
Here's a blog post I wrote on how to achieve this functionality.
http://blogs.msdn.com/jaredpar/archive/2008/05/16/switching-on-types.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With