The project uses 2 components ( listBox , metroComboBox ), in which you need to record information. To do this, I use the UpdateListOfSports function, passing as an object either a listBox or a metroComboBox . When determining the type of object in the function itself, I encounter an error CS0173 , which I described below. I would be very grateful if you help solve this problem.

 public void UpdateListOfSports(object obj) { DBConnect dbConnect = new DBConnect(); DataTable dt = dbConnect.SelectValues("SELECT * FROM sport"); var list = (obj is ListBox) ? (ListBox)obj : (MetroComboBox)obj; // тут ошибка list.Items.Clear(); foreach (DataRow row in dt.Rows) list.Items.Add(row["KindOfSport"].ToString()); list.SelectedIndex = 0; } 

Error CS0173 Cannot determine the type of conditional expression because the implicit conversion between System.Windows.Forms.ListBox and MetroFramework.Controls.MetroComboBox does not exist.

  • one
    Well, what type, as you think, should be the variable list ? - VladD
  • This is depending on the parameter being passed. If I transfer listBox1, then accordingly type ListBox, otherwise - MetroComboBox. - Sayan
  • 2
    About strict typing in the C # language heard? This is not for you, this is not for you, this is not for you javascript. - Bulson

2 answers 2

I'll try to explain on the fingers. var is not a type. var is just a magic word for the lazy, so as not to write the desired type with your hands.

Every time you write var i = 1; or var s = "acb"; the compiler substitutes var the type that is on the right side of the expression.

That is, the entry var s = "acb"; absolutely equivalent to string s = "acb";

The compiler saw that we are trying to initialize the variable s with a string, guessed that it (the variable) should have the type string and substituted it. And this happens at compile time.

And your expression var list = (obj is ListBox) ? (ListBox)obj : (MetroComboBox)obj; var list = (obj is ListBox) ? (ListBox)obj : (MetroComboBox)obj; calculated only during program operation. That is, the compiler simply does not know what type the list variable will have and cannot substitute it.

In short: the error occurs because it is impossible to write like this in C #.

    Thank you all for the clarification! Solved the problem in this way:

      dynamic list; if (obj is ListBox) list = (ListBox)obj; else list = (MetroComboBox)obj;