I've been trying to do this multiple times in my recent project, since I'm currently experimenting on how can I keep my main function in the main class as clean and tidy as possible, while making use of all my functions and values in different classes
Couldn't find solution to my current issue anywhere, so I wrote a simple example of what I mean by that, here I'm trying to make a simple method for generating a random name of a character and then access its name value from a main method
As you can see, if I'm creating an instance of a class in the main method, I can do it very easily, but when I try to use a method from another class, I get an error
So, my question is: could there be any way I could access the values of an instance of a class if it was created by using a method?
Any help or solutions would be much appreciated
class Program
{
public static Random rand = new Random();
public class Character
{
public static string[] nameList = new string[]
{
"John",
"Jack",
"Josh",
};
public string name = nameList[rand.Next(0,3)];
}
public class Functions
{
public void GetCharName()
{
var Char1 = new Character();
Console.WriteLine(Char1.name);
}
}
static void Main(string[] args)
{
//I want this to work, but it doesn't (The name 'Char1' does not exist in the current context)
var TestFunction = new Functions();
TestFunction.GetCharName();
Char1.name = "Arthur";
//This works, but I want to be able to get the name, using function from another class
var Char2 = new Character();
Char2.name = "Andrew";
Console.WriteLine(Char2.name);
}
}
You should create a class. Something like this:
public class Character
{
private readonly string[] nameList = new string[]
{
"John",
"Jack",
"Josh",
};
public string Name { get; private set; }
public Character()
{
Random randomGenerator = new Random();
Name = nameList[randomGenerator.Next(0, nameList.Length - 1)];
}
}
In Main class instantiate a Character type and you can reach the object name with getter.