Search code examples
c#parenthesesnegation

c# negation operator open parenthesis expected


In C#, I'm writing code for negation operator like this, but it show syntax error, '(' expected

DataTable tmp = new DataTable();
var col = tmp.Columns;
if !(col.Contains("COL1") && col.Contains("COL2") && col.Contains("COL3"))
{
    //DO STH
}

If I change to this code the error disappear:

DataTable tmp = new DataTable();
var col = tmp.Columns;
if (!col.Contains("COL1") || !col.Contains("COL2") || !col.Contains("COL3"))
{
    //DO STH
}

Docs from MS seems too simple and I didn't find how to correct the first code.

So why the first code has syntax error, and how to fix it?

enter image description here


Solution

  • an if always starts with a ( so the code should be

    DataTable tmp = new DataTable();
    var col = tmp.Columns;
    if (!(col.Contains("COL1") && col.Contains("COL2") && col.Contains("COL3")))
    {
        //DO STH
    }