Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

c# - The name 'xyz' does not exist in the current context

This is probably really basic in C#, but I looked around a lot to find a solution.

In my MVC controller's action method, I have an incoming routeid (programid) that I need to use to create another string variable (accounttype). I have an if/else to evaluate the value of accounttype. Later in the same action method's code, I have nother if/else that takes the variable accounttype and creates a JSON string to pass to a payment gateway. But I get an error "The name 'accounttype' does not exist in current context.' Do I need to declare it as public or something?

Here are the two if/else statements:

if (programid == 0)
{
    string accounttype = "Membership";
}
else
{
    string accounttype = "Program";
}

Later on in same controller action, I need to use the accounttype variable to calculate another string variable (URL)

if (results.Count() > 0)
{
    string URL = accounttype + "some text"
}
else
{
    string URL = accounttype + "some other text"
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Scope is your problem :)

Since I guess you are new, I'll try to define it in simple words: the scope of a variable is the place where a variable lives. Not all the variables can be called everywhere in your program, and we call those who can, global.

In your case, you are declaring those variables inside an if .. else statement, and, because of C# rules, they die as soon as the if block ends. This is what the compiler is telling you: you can't call something that doesn't exist.

To solve your problem, you just have to declare

string accounttype;

before the if.. else and you will be fine.

If you want to read more about scopes, this is a good place to start!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...