Reputation: 3
Coding enthusiast/hobbyist here, new to C#, trying to wrap my head around the language and have been beating my head against a wall on this problem for a few days. Have tried searching on this site as well as reading the documentation on this error on msdn, as well as documentation on classes, field, intitialization, etc. Apologies if this is obvious to everyone else, but I've tied my brain in knots trying to understand this error.
I'm writing a basic MUD game (text-based RPG run in the command line) as my first C# program, and I'm running into an issue when I try to access monster stats (which I've put in a different namespace titled "Bestiary," which will contain the stats for all monsters as their own Class). I've tried several different methods but have been unable to get the program to compile without error.
using System;
using System.Collections;
using Bestiary;
//Battle system is contained in this namespace.
class Combat(string playerName)
{
public int[] playerStats= new int[] { 25, 10};
public int[] monsterStats= new int[] { 10, 10};
string playerName = playerName;
Slime s = new Slime();
string monsterName = s.Name();
...
//Bestiary section being referenced in Combat
using System;
using System.Collections;
namespace Bestiary
{
//List of Monsters and their stats
class Slime
{
private string name = "Slime";
public string Name
{
get { return name; }
set { name = value; }
}
private int hp = 10;
public int HP
{
get { return hp; }
set { hp = value; }
}
private int atk = 1;
public int ATK
{
get { return atk; }
set { atk = value; }
}
}
When I try to compile this I get the error at the line "string monsterName = s.Name();".
Upvotes: 0
Views: 80
Reputation: 1057
You should reference your slime's name like this:
string monsterName = s.Name;
Properties were designed specifically to allow you to put logic inside get
and set
'methods' while retaining the syntax of reading or writing fields.
Also, put the code inside the constructor:
class Combat
{
public int[] playerStats = new int[] { 25, 10};
public int[] monsterStats = new int[] { 10, 10};
string playerName;
string monsterName;
public Combat(string playerName)
{
this.playerName = playerName;
Slime s = new Slime();
monsterName = s.Name;
}
}
Apart from that, I suggest you leverage the usage of var
.
Slime s = new Slime();
Will become
var slime = new Slime();
Also, there is no need to declare backing fields directly. Use this:
public string Name { get; set; } = "Slime";
Good luck with C#.
Upvotes: 2