Search code examples
c#if-statementassignment-operator

Does the assignment operator in c# take any other value other than bool in any scenario?


I recently started learning c# and got to know that the if condition takes only the boolean value for the assignment operator like in the below code. But I wanted to know if there is any scenario where if takes any value other than bool.

I tried changing the type of 'a' to char but it gave me a compile time error.

Console.Write("Enter a character: ");
char c = (char)Console.Read();
bool a;
if (a=Char.IsLetter(c))
{
    if (a=Char.IsLower(c))
    {
        Console.WriteLine("The character is lowercase.");
    }
    else
    {
        Console.WriteLine("The character is uppercase.");
    }
}
else
{
    Console.WriteLine("Not a character");
}

Solution

  • I sometimes have used an expression like this:-

    string a = null;
    
        if((a = GetValue()) != null){
        DoSomething();
        }
    

    It is a nice syntax to assign other values other than null and check it for a boolean expression. Although keep in mind that the outermost bracket will always ask for a boolean expression.