Answer the question
In order to leave comments, you need to log in
How to create a reference to a string inside a class object that points to a variable outside the object?
Good evening.
I'm trying to store inside the object a reference to the variable (Name) outside this object, so that when the value changes by reference inside the object's method, the Name variable itself also changes.
In short, I expect the line Console.WriteLine(Name); will output what was entered in the startExecution() method.
Tell me, is it possible to implement this at all?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public class stateEnterWord
{
private string word;
public void init(ref string input)
{
word = input;
}
public void startExecution()
{
word = Console.ReadLine();
}
}
static void Main(string[] args)
{
stateEnterWord obj = new stateEnterWord();
string Name = "";
obj.init(ref Name);
obj.startExecution();
Console.WriteLine(Name);
}
}
}
Answer the question
In order to leave comments, you need to log in
This is not possible within C# because the string type is an immutable type. Each new string has its own string instance (all ValueTypes have the same behavior).
If you want to achieve different behavior, you need to use System.Text.StringBuilder .
For example:
public class stateEnterWord
{
private StringBuilder word;
public void init(StringBuilder input)
{
word = input;
}
public void startExecution()
{
word.Append(Console.ReadLine());
}
}
static void Main(string[] args)
{
stateEnterWord obj = new stateEnterWord();
StringBuilder Name = new StringBuilder();
obj.init(Name);
obj.startExecution();
Console.WriteLine(Name.ToString());
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question