C# Use discard '_'

I'm not quite sure of the different between

DataTable itemTable = new DataTable();
itemTable = //CODE


_ = new DataTable();
DataTable itemTable = //CODE

Both worked exactly the same, why would I need to change it to an _ like shown?


enter image description here

2 answers

  • answered 2020-03-31 08:22 MyBug18

    Because you have not used the value new DataTable() after assigning, the intellisense thought that you won't need it, so just made the leftside wildcard.

    Its just like:

    int a = 5;
    a = 6; // you didn't even used the value 5 assigned above!

    But, in case that the constructor of DataTable has side-effect, the intellisense suggested you not to discard the entire statement, using wildcard _. That's what happened.

    If the constructor of DataTable has no side-effect, you are free to remove the statement, just like the above int example.

  • answered 2020-03-31 10:17 Jeppe Stig Nielsen


    DataTable itemTable = new DataTable();
    itemTable = //CODE


    _ = new DataTable();
    DataTable itemTable = //CODE

    seem wrong to me.

    In both cases you have an assignment in the first line which is useless.

    There are two ways to make it better, depending on whether the new DataTable() expression has side effects.

    In the most frequent and good case, the allocation of a new DataTable in the first line can be omitted completely. You then write:

    DataTable itemTable;
    itemTable = //CODE

    The first line declares the local variable. The second line assigns it. However, it is much more common to put these two things together in one statement, namely:

    DataTable itemTable = //CODE

    This is the one you should use.

    Often you would use an implicit type with var. The variable will still be strongly typed:

    var itemTable = //CODE

    If the type of the expression //CODE is DataTable, this is entirely equivalent to what you had before. If the (compile-time) type of the right-hand side is instead something more specific, say YourItemDataTable, then using var will give the local variable that more specific type as well. That may very well be fine. So very often, it is appropriate to use var, but it is also a matter of style.

    In the unlikely (theoretically possible) scenario where the initialization of a new object instance is intended and needed (a constructor may have side effects), C# allows a new-object expression to be a statement by itself. So in that case, write:

    new DataTable();
    DataTable itemTable = //CODE

    The language has a support for this situation, but I doubt it is useful. When DataTable is the one in the System.Data.dll assembly, it is not relevant.