embryo
embryo

Reputation: 157

if/then/else variable frustration in C#

I asked a question a few days ago and folks were very forthcoming with help. My circumstance have changed a little, and my code has as well.

I first need to ascertain if the current article group is one of several that need to be treated differently. If it is, it defines the var "strbody" using a complete value as retrieved from the database. If it is not one of those special article groups, then I have to do some string manipulation to format the retrieved value before defining and displaying it.

My string manipulation code works just like it should, but neither of the strbody vars I define in my if/then/else block is recognized when I call it below the code block???

Here is my code:

@{
    string group = Model.ArticleGroupName;
    if (group.Contains("Spacial Orientation")||group.Contains("Topography")||group.Contains("Osteology")||group.Contains("Angiology")||group.Contains("Neurology")||group.Contains("Myology")||group.Contains("Radiology")||group.Contains("Misc. Drawings")||group.Contains("Clinical Testing"))
    {
        var strbody = item.ShortBody;
    }
    else
    {
        string s = item.ShortBody;
        string sLess = s.Remove(0, 12);
        int index = sLess.IndexOf("Summary");
        var strbody = (sLess.Substring(index + 8));
    }
}
@strbody

This is the error:

\Plugins\FoxNetSoft.Articles\Views\ArticleRead\List.cshtml(76): error CS0103: The name 'strbody' does not exist in the current context

I don't understand how the var does not exist when I JUST defined it under either possible scenario...

I am new to this, so please don't hesitate to chastise me for doing dumb stuff...I need to learn!

UPDATE:

It is working perfectly now. Thanks to all those who helped!

Below is the final working code:

   @{
    string strbody = item.ShortBody;
    string group = Model.ArticleGroupName;
    var thestrbody = " ";

    if (group.Contains("Spacial Orientation")||group.Contains("Topography")||group.Contains("Osteology")||group.Contains("Angiology")||group.Contains("Neurology")||group.Contains("Myology")||group.Contains("Radiology")||group.Contains("Misc. Drawings")||group.Contains("Clinical Testing"))
        {
        thestrbody = strbody;
        }
    else
        {
        string s = item.ShortBody;
        string sLess = s.Remove(0, 12);
        int index = sLess.IndexOf("Summary");
        thestrbody = (sLess.Substring(index + 8));
        }
    }
   @thestrbody

Upvotes: 1

Views: 172

Answers (1)

David
David

Reputation: 218877

You defined it within a specific code block, and the scope is only within that code block. As soon as you close that block, the variable falls out of scope. In order to use it outside of that code block, you need to declare it before:

string strbody;
if(...)
{
    // set the value of strbody
}
@strbody

Upvotes: 5

Related Questions