user3037055
user3037055

Reputation:

Using ternary operator on Console.WriteLine

I need to print some string based on the true or false of a condition.

For example:

    if(i == m) {
        Console.WriteLine("Number is valid");
    } else {
        Console.WriteLine("Number is invalid");
    }

How can I check this condition and print a message using conditional operator and with only one Console.WriteLine?

I was trying:

    (i == m) ? Console.WriteLine("Number is valid") : Console.WriteLine("Number is not valid");

I know I'm doing it wrong here. Can someone please tell me the correct way?

Upvotes: 2

Views: 10312

Answers (5)

Asad Saifi
Asad Saifi

Reputation: 1

#include <iostream>
using namespace std;

int main() {
    string name;
    cout>>"enter your name: ";
    cin>>name;
    return 0;

Upvotes: 0

Joel Fernandes
Joel Fernandes

Reputation: 4856

Try this:

    Console.WriteLine("Number is " + ((i == m) ? "valid" : "not valid"));

Upvotes: 15

Sedatyf
Sedatyf

Reputation: 48

I know it's an old topic, but I wanted to add my two cents.

You can also use string.Concat() like below C# code

Console.Writeline(string.Concat("Number is ", (i == m) ? "valid" : "not valid"));

In my opinion, it is a cleaner way to do it.

Upvotes: 2

John Saunders
John Saunders

Reputation: 161773

The conditional operator is an operator. It returns a value. The value it returns is the value from one of its branches.

Console.WriteLine is a void method. It does not return a value. As a result, you cannot use it as one of the branches of the conditional operator.

BTW, this operator is correctly called "the conditional operator". It happens to be a ternary operator, meaning that it is an operator which takes three parameters. ere It runs:

  1. Unary
  2. Binary
  3. Ternary
  4. Quaternary

etc.

There happens to be only a single ternary operator in C# at present - the conditional operator. There happen to be no quaternary or higher-order operators.

Upvotes: 2

gzaxx
gzaxx

Reputation: 17600

Move your ternary operation inside WriteLine

Console.WriteLine((i == m) ? "Number is valid" : "Number is not valid");

Upvotes: 2

Related Questions