简体   繁体   中英

Clipboard.SetText() using ternary operator

Clipboard.SetText(txtBox1.Text);

How can I use a ternary operator here to set the text of the clipboard to txtbox1.Text if txtbox1.Text is not equal to string null, (nothing) ?

Thanks

You cannot. You are calling "SetText" either way. The correct way to achieve that would be to not call SetText if the text is not null. Using Clipboard.SetText( a ? b : c); would give you nothing here if you dont want to set the text (only except hoping that SetText would ignore a null) unless you want some default. in that case something like:


clipboard.SetText(string.IsNullOrEmpty(txtBox1.Text) ? "default text" : txtBox1.Text);

You don't. Just a simple if statement will work though:

if (!string.IsNullOrEmpty(txtBox1.Text)) {
    Clipboard.SetText(txtBox1.Text);
}

Why do you want to use the ternary operator? If you don't need to SetText, then don't.

if (!String.IsNullOrEmpty(txtbox1.Text))
     Clipboard.SetText(txtbox1.Text);

I suppose you could do

Clipboard.SetText(String.IsNullOrEmpty(txtbox1.Text) ? (default here, or as is: Clipboard.GetText()) : txtbox1.Text);

I would suggest simple if , with ternary operator I can not imagine adequate solution.

if (!String.IsNullOrEmpty(txtbox1.Text))
{
  Clipboard.SetText(txtbox1.Text);
}

Ternary mess: (do not use this in a real application!!!)

Action executeAction = String.IsNullOrEmpty(txtbox1.Text) 
                        ? () => {} 
                        : () => { Clipboard.SetText(txtbox1.Text); };

executeAction.Invoke();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM