Search code examples
c#ref

Assign a variadic array of strings by reference in C#


I have a class called Category that takes a variadic constructor. The arguments are strings.

class Category
{
    string[] definedSets;  // Sets supplied to the constructor

    public Category(params string[] specifiedSets)
    {
        definedSets = specifiedSets;
    }

etc.

A call to the constructor might look like Category myCat = new Category(myString1, myString2);

The problem is that I would like definedSets to change if the content of myString1 or myString2 changes. I tried definedSets = ref specifiedSets;, but I get an error The left hand side of a ref assignment must be a ref variable and I don't know how to resolve that.

Am I on the right track here? What do I do?


Solution

  • strings are immutable, and you can not change their value. Whenever you assign a new value it allocates new memory. It is not possible to refer to the same memory location every time.

    I would suggest to use the StringBuilder class and change type of definedSets to StringBuilder,

    public class Category
    {
        StringBuilder[] definedSets;  // Sets supplied to the constructor
    
        public Category(StringBuilder specifiedSets)
        {
            this.definedSets = specifiedSets;
        }
    }
    

    Proof of concept: .NET Fiddle