Reputation: 51
I'm new in C# and I try to learn it from the very basics, but I stuck with classes. I made my first example to practice which is working properly but when I add a little complexity I get an error:
"The name 'iArcher' doesn't exist in the current context."
Please help to explain what's wrong and suggest a proper (and easy) solution.
Thanks!
using System;
namespace Units
{
class Archer
{
public int id;
public int hp;
public float speed;
public float attack;
public float defence;
public float range;
public void setProp(int id, int hp, float sp, float at, float de, float ra)
{
this.id = id;
this.hp = hp;
speed = sp;
attack = at;
defence = de;
range = ra;
}
public string getProp()
{
string str = "ID = " + id + "\n" +
"Health = " + hp + "\n" +
"Speed = " + speed + "\n" +
"Attack = " + attack + "\n" +
"Defence = " + defence + "\n" +
"Range = " + range + "\n" ;
return str;
}
static void Main(string[] args)
{
string input = Console.ReadLine();
if (input == "create: archer")
{
Archer iArcher = new Archer();
iArcher.setProp(100, 20, 4f, 8f, 3.5f, 25f);
}
if (input == "property: archer")
{
Console.WriteLine(iArcher.getProp()); // ERROR!
}
Console.ReadLine();
}
}
}
Upvotes: 1
Views: 34924
Reputation: 38737
C# has scopes. An item within a scope can see everything in the scopes that contain it, but outer scopes can't see within inner scopes. You can read about scopes here.
Take your example:
if (input == "create: archer")
{
Archer iArcher = new Archer();
iArcher.setProp(100, 20, 4f, 8f, 3.5f, 25f);
}
iArcher
is in the scope of your if
statement, so code outside that if statement can't see it.
To resolve this, move the definition or iArcher
outside the if statement:
Archer iArcher = new Archer();
if (input == "create: archer")
{
iArcher.setProp(100, 20, 4f, 8f, 3.5f, 25f);
}
if (input == "property: archer")
{
Console.WriteLine(iArcher.getProp());
}
Note that this now leaves you with another problem: input
cannot be both "create: archer" and "property: archer".
One solution might be to move reading user input inside a loop, while keeping iArcher
outside that loop:
Archer iArcher = new Archer();
string input = null;
while ((input = Console.ReadLine()) != "exit")
{
if (input == "create: archer")
{
iArcher.setProp(100, 20, 4f, 8f, 3.5f, 25f);
}
else if (input == "property: archer")
{
Console.WriteLine(iArcher.getProp());
}
}
To exit the loop simply type "exit" as the input.
Upvotes: 5
Reputation: 8106
Move this line:
Archer iArcher = new Archer();
outside your if-block, and it will work.
Upvotes: 2