Click here to Skip to main content
15,887,585 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hello
i want to perform some validation operation. here using if statement i am done my validation but i wanted to ask can we use ternary operator for displaying message.

What I have tried:

Suppose i want to restrict if name textbox is null. and here using if condition i am doing well like this .
else if (txtName.Text == "")
          {
              MessageBox.Show("Please enter the name");
              return;
          }

i want using ternary

bool chechvalidation = txtUName.Text != "" ? true : false  MessageBox.Show("Please enter name")return;
Posted
Updated 26-May-17 0:45am

You can't use a ternary for that. Ternary operations are to decide the output from two options.

string a = <some condition> ? x : y


So "x" and "y" both have to conform to the desired target, ie they have to be "string" as you're ultimately doing either this

string a = x


or this

string a = y


Wanting to put code there like a message box means doing this

string a = "Hello" MessageBox.Show


Obviously that's not valid.
 
Share this answer
 
No, not directly.
You could do it:
C#
private bool DoSometheingFairlyPointless(string s)
   {
   MessageBox.Show(s);
   return false;
   }
...
bool chechvalidation = txtUName.Text != "" ? true : DoSometheingFairlyPointless("Please enter name");
But even then, you can't exit the calling method within the operator.

Even if you could, it wouldn't be particularly readable and I'd suggest you avoid it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900