How to check control Type in Switch Case

  • A+
Category:Languages

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

 


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;     } } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: