How to return a reference to a string in c#?

c#
14,256

Solution 1

To do this you need to write a setter property. Unfortunately, setters can’t take further arguments in C# so you won't be able to write this code 1:1 in C#. The closest you can get is a nested class with a default property:

class YourClass {
    public class Nested {
        public Nested(YourClass outer) { m_RefToOuterWorld = outer; }
        private readonly YourClass m_RefToOuterWorld;

        public string this[int index] {
            get { return m_RefToOuter.TestArray[index];
            set { m_RefToOuter.TestArray[index] = value; }
        }
    }

    private readonly Nested m_Nested;
    private string[] TestArray = new string[10];

    public YourClass() { m_Nested = new Nested(this); }

    public Nested TestIt { get { return m_Nested; } }
}

You can use it like this:

var test = new YourClass();
test.TestIt[2] = "Hello world!";

By the way, since this is so much effort, you probably don't want to do this. Also, it doesn't feel very C#-y. The useless indiretion through the nested class here isn't something you'll see very often.

Solution 2

The short answer is that you cannot return a reference to a string variable, i.e. a reference to the string reference).

The simple solution is to avoid this kind of API and require the user to set the string in another way:

myobj.SetString(0, "Hello, world!");

If you really need to represent (as a first-class object) a reference to your string reference, try something like this API:

Interface IStringReference
{
    void SetString(string value);
    string GetString();
}


class MyClass
{
    public IStringReference TestIt()
    {
        ... details left out ;) ...
    }
}

but I think this is going too far in mimicking C++'s lvalues.

Solution 3

I can recomend following sollution

 public class Test
    {
        Dictionary<int,string> str=new Dictionary<int,string>(); 
        public string this[int i]
        {
            get
            {
                return str[i];
            }
            set
            {
                if(!str.ContainsKey(i))
                    str.Add(i,value);
                else
                    str[i] = value;
            }
        }
Share:
14,256

Related videos on Youtube

Aaron Fischer
Author by

Aaron Fischer

I am a senior software developer and mentor with a focus on Microsoft technologies. My particular interests are in smart clients and web-based applications. I work for a small mortgage origination ISV.

Updated on April 23, 2022

Comments

  • Aaron Fischer
    Aaron Fischer about 2 years

    I am looking to write a function like

    ref String TestIt( int index )
    {
    return this.TestArray[index];
    };
    

    so that I could write code like:

    MyClass.TestIt(0) = "Hello World";
    

    My goal is to mimic this c++ declaration

    CString& MyClass::Data( UINT index);
    

    By Reference I am referring to the c++ term the Address of the variable.
    in other words after my call to TestIT(0) TestArray[0] would contain "Hello World".

    EDIT I can't use an indexer because my goal is to convert a .cpp file to c# on an ongoing basis. The closer I can mimic this c++ code, the less of a converter I have to write.

  • Joel Coehoorn
    Joel Coehoorn over 15 years
    Based on my VB background, I was starting to write a simple indexed property for him, kind of like this. Then I discovered that while VB.Net supports this out of the box, C# requires you to create a whole new class. Bummer.
  • Jon Skeet
    Jon Skeet over 15 years
    It's not trying to be a string comparison - it's trying to be an assignment, which therefore won't work.
  • Konrad Rudolph
    Konrad Rudolph over 15 years
    Bummer indeed. To be honest though, I've never needed this particular VB feature. What it's mostly used for is to emulate semantics of the implicit CType operator, anyway, so we can use that instead.
  • Konrad Rudolph
    Konrad Rudolph over 15 years
    To your edit: that's no wonder because you can google any search term containing “C#” and find an (excellent) answer by Jon. Man, this guy is so boring and predictable.
  • Konrad Rudolph
    Konrad Rudolph over 15 years
    This only counts for literal strings and strings you explicitly intern! All other identical strings may or may not share a reference.