How to check control types in switch case statement?
Private void CheckControl(Control ctl)
{
switch (ctl) {
case TextBox: MessageBox.Show("This is My TextBox");
break;
case Label: MessageBox.Show("This is My Label");
break;
}
}
Following is error in above statement:
'Textbox' is a type, which is not valid in the given context
Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached. This continuation may be desirable in some situations. The default statement is executed if no case constant-expression value is equal to the value of expression .
If no default clause is found, the program continues execution at the statement following the end of switch . By convention, the default clause is the last clause, but it does not need to be so. A switch statement may only have one default clause; multiple default clauses will result in a SyntaxError .
The position of default doesn't matter, it is still executed if no match found. // The default block is placed above other cases. 5) The statements written above cases are never executed After the switch statement, the control transfers to the matching case, the statements written before case are not executed.
The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.
As of C# 7 you can use type patterns for this:
private void CheckControl(Control ctl)
{
switch (ctl)
{
case TextBox _:
MessageBox.Show("This is My TextBox");
break;
case Label _:
MessageBox.Show("This is My Label");
break;
}
}
Here _
is the syntax for a discard, meaning you don't need to access the value as a TextBox
(or Label
) afterwards.
If you do want to access members of the specific type, you can introduce a pattern variable:
private void CheckControl(Control ctl)
{
switch (ctl)
{
case TextBox textBox:
// Use textBox for any TextBox-specific members here
MessageBox.Show("This is My TextBox");
break;
case Label label:
// Use label for any Label-specific members here
MessageBox.Show("This is My Label");
break;
}
}
try:
switch (ctl?.GetType().Name) {
case "TextBox": MessageBox.Show("This is My TextBox");
break;
case "Label": MessageBox.Show("This is My Label");
break;
}
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