PiZzL3
PiZzL3

Reputation: 2220

C# short if statement

Is there a way to do this in C# without making a new method to overload for every var type there is?

$box = !empty($toy) : $toy ? "";  

The only ways I can think of to do it is either:

if (toy != null)
{
    box += toy; 
}  

or this:

public string emptyFilter(string s) ...
public int emptyFilter(int i) ...
public bool emptyFilter(bool b) ...
public object emptyFilter(object o) 
{
    try 
    {
        if (o != null)
        {
            return o.ToString(); 
        }
        else 
        {
            return ""; 
        }
    }
    catch (Exception ex)
    {
        return "exception thrown": 
    }
}

box += this.emptyFilter(toy);

I basically wanna check to make sure that the variable/property is set/not empty/exists/has value/etc... and return it or "" without some ridiculous about of code like above.

Upvotes: 1

Views: 86192

Answers (5)

Brad Christie
Brad Christie

Reputation: 101614

return variable ?? default_value;

That what you're going for? I'm a little confused considering you're showing PHP code and tag this with C#.

There's also the Nullable<T> type you can use.


How bout an extender class?

public static class ToStringExtender
{
  public static String ToStringExt(this Object myObj)
  {
    return myObj != null ? myObj.ToString() : String.Empty;
  }
}

var myobject = foo.ToStringExt()

DEMO

Upvotes: 11

antoniuslin
antoniuslin

Reputation: 249

i think there may be a slight misunderstanding about how var is used; but that's a separate topic. maybe this below will help:

box += (toy ?? "").ToString();

Upvotes: 0

Charles Bretana
Charles Bretana

Reputation: 146603

or,

var s = (toy?? "").ToString();

or

var s = (toy?? string.Empty).ToString(); 

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039538

You could use the conditional operator (?:):

string box = (toy != null) ? toy.ToString() : "";  

Upvotes: 19

xanatos
xanatos

Reputation: 111950

I'm not sure of what he wants, BUT:

string str = String.Empty;
str += true;
str += 5;
str += new object();
str += null;

This is perfectly legal. For each one adition the ToString() will be called. For null, simply nothing will be added.

The value of str at the end: True5System.Object

Upvotes: 1

Related Questions