0
0
0nk0l0g2017-02-06 21:52:27
OOP
0nk0l0g, 2017-02-06 21:52:27

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

2 answer(s)
A
Arseniy Efremov, 2017-02-07
@0nk0l0g

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());
        }

However, to be honest, this violates OOP principles.

R
res2001, 2017-02-07
@res2001

As far as I understand, you will have a copy of Name in word at the time of the init call, and not a link.
You have word declared as a string, not as a reference to a string.
I won't say anything more, because C# is not mine.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question