Alexandre
Alexandre

Reputation: 13318

To simplify the code

I confused: is there any way to simplify that code?

private void Page_Load(object sender, EventArgs e)
{
   if (string.IsNullOrWhiteSpace(pnlMain.Title) && string.IsNullOrWhiteSpace(Title))
                pnlMain.Title = DefaultTitle;
            else if (string.IsNullOrWhiteSpace(Title))
                pnlMain.Title = DefaultTitle;
            else  
                pnlMain.Title = Title;
 }

Upvotes: 2

Views: 107

Answers (4)

Jonas Elfström
Jonas Elfström

Reputation: 31458

Your else if (string.IsNullOrWhiteSpace(Title)) will always be true and the last else will never be reached. You probably meant something like this:

if (string.IsNullOrWhiteSpace(pnlMain.Title))
    pnlMain.Title = string.IsNullOrWhiteSpace(Title) ? DefaultTitle : Title;

Upvotes: 1

Ondrej Tucny
Ondrej Tucny

Reputation: 27974

This code is readable. Simplifying further, i.e. playing with ?:, ||, &&, would lead to unreadable code. Hence it is simple just enough.

Upvotes: 0

Chris
Chris

Reputation: 27627

If you draw up a logic table for it you should be able to work it out... Have columns for true and false for pnlMain.Title being null or whitespace and rows for Title being null or whitespace and then in each cell mark whether you use the DefaultTitle or Title when you go through the above logic.

You should get the result that it doesn't matter what pnlMain.Title is.

So that code is the same as:

        if (string.IsNullOrWhiteSpace(Title))
            pnlMain.Title = DefaultTitle;
        else  
            pnlMain.Title = Title;

You can probably see it when you know the answer because in your code your first two checks are the same except with and without pnlMain.Title being checked as well and the same outcome.

From looking at what you might be trying to do you might in fact be wanting to do this:

    if (string.IsNullOrWhiteSpace(pnlMain.Title))
    {
        if (string.IsNullOrWhiteSpace(Title))
            pnlMain.Title = DefaultTitle;
        else  
            pnlMain.Title = Title;
    }

The above code will only change pnlMain.Title if it is null or white space and will use Title if that is not null or whitespace and otherwise fall back to DefaultTitle. This seems like more what I'd expect you to be wanting to do...

Upvotes: 2

J0HN
J0HN

Reputation: 26961

Looks like you can use ternary operator.

pnlMain.Title = (!string.IsNullOrWhiteSpace(Title))?Title:DefaultTitle;

You don't have to check string.IsNullOrWhiteSpace(pnlMain.Title) because you are overwriting it anyway. But maybe it is another error in your code. So, what that piece of code meant to do?

Upvotes: 1

Related Questions