Can someone help me with passing values from one class method to another in c#. I\'ve tried looking it up, but I get lost in pages of code and I cant find a simple example. Take
First you need to actually store the variable somewhere. Right now it's a local variable in the method, so it will go away right after you have assigned the value to it.
Make it a property in the class, and make the method an instance method instead of a static method:
namespace simplecode
{
public class Values
{
public string MyName { get; set; }
public void getName()
{
Console.Clear();
Console.Write("Enter name: ");
MyName = Console.ReadLine();
}
}
}
Now you can call the method and pick up the value afterwards:
namespace simplecode
{
class Program
{
static void Main(string[] args)
{
Values myValues = new Values();
myValues.getName();
Console.WriteLine(myValues.MyName);
}
}
}
Typically you would return the value from the function. You will want to think how your code calls different modules.
You may find if the flow is complicated you may want to look in to inversion of control, although off topic and more advanced it is related to how code is chained together and that I feel is your underlying question/issue.
If you had more than one value to return you could use a struct/class or mark parameters as ref allowing you to modify from within the function (variables passed by reference, as opposed to passing them by value which is done by default).
You could have the method return this value:
public static string getName()
{
Console.Clear();
Console.Write("Enter name: ");
return Console.ReadLine();
}
and then in your main program call the method and store the result in a local variable:
static void Main(string[] args)
{
string myName = Values.getName();
}
Notice that since getName
is a static method you do not need to create an instance of the Values
class in order to invoke it. You could directly call it on the type name.
If on the other hand the getName
method wasn't static:
public string getName()
{
Console.Clear();
Console.Write("Enter name: ");
return Console.ReadLine();
}
then you need the instance:
static void Main(string[] args)
{
Values values = new Values();
string myName = values.getName();
}