Sebastiaan Jansen Sebastiaan Jansen - 2 months ago 11
C# Question

C# Using data from another class in a class

First time posting a question because up untill now I've always found the answer I'm looking for here so bear with me. :)

On to the problem, I'm testing an interface I'm making in a console application to use in a game.
I got an interface for a character, also made a class for it. In my main code I can succesfully call my "sCharacterName" from my class(Character1Class).

In my (SwordClass) I have a void for equiping the weapon and i want it to show like this: "(sCharacterName) equiped (sWeaponName)."
But whenever I try it shows up as a blank space instead of the name.
This is part of my code:

namespace ConsoleInterfaceTest
{
class Program
{
public interface ICharacters
{
// The name of the character
string sCharacterName { get; set; }
}

public interface IWeapon
{
// The name of the weapon
string sWeaponName { get; set; }

void Equip();
}

public class Character1Class : ICharacters
{
// The name of the character
public string sCharacterName { get; set; }

public Character1Class(string v)
{
sCharacterName = ("ZeeAars");
}
}

public class SwordClass : IWeapon, Characters.ICharacters
{
// The name of the weapon
public string sWeaponName { get; set; }

public string sCharacterName { get; set; }

public SwordClass(string sName)
{
sWeaponName = sName;
}

public void Equip()
{
Console.WriteLine(sCharacterName + " equiped " + sWeaponName + ".");
}
}

public static void Main (string[] args)
{
Characters.Character1Class character1 = new Characters.Character1Class("");
character1.CharacterDamage(50);


Weapons.SwordClass sword = new Weapons.SwordClass("TestSword");
sword.Equip ();

Console.ReadKey();
}
}
}


Thanks in advance, really been scratching my head for a couple days with this problem :D

Answer

I agree with the other's comments that you need to rethink how you are using Interfaces and how you are structuring your object hierarchy, but to simply answer the asked question;

Weapons.SwordClass sword = new Weapons.SwordClass("TestSword");
// Add the following line to your code
sword.sCharacterName = character1.sCharacterName;
sword.Equip();
Comments