'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 1:[1]
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;
}
}
Solution 2:[2]
Just pass a regular array instead:
var strings = new[] { myString1, myString2 };
new Category(strings);
Then keep the array and change its elements whenever you want.
Solution 3:[3]
For that to work, you would have to wrap the strings in a custom wrapper class:
public class StrWrapper
{
public string Value {get; set;}
public StrWrapper(string val) => Value = val;
}
You can pass the object reference around and change the string inside it at any time.
Also note that you cannot save a string ref: https://stackoverflow.com/a/2982037/1974021
So even if you could get the ctor to accept a (string ref)[] array, you could only use it then & there and not store it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
| Solution 2 | IS4 |
| Solution 3 |
