Is there a way to store a pointer to immutable types like strings in C#? How can execute: Instance1.SomeFunction(out MyString);
,and store a pointer to MyString inside of Instance1?
Is there a way to store a pointer to immutable types like strings in C#? How can execute: Instance1.SomeFunction(out MyString);
,and store a pointer to MyString inside of Instance1?
I have been fighting with pointers in C# for a while now, and was amazed by the lack of options. You encounter all kinds of obscure obstacles when dealing with pointers and pointer arguments in C#:
Pretty neat solution I found recently, and also the reason for this post is:
void Test()
{
string ret = "";
SomeFunction(a=>ret=a);
}
void SomeFunction(string_ptr str)
{
str("setting string value");
}
delegate void string_ptr(string a);
Use this class as a pointer (note: untested notepad code, might need some fixing):
public class Box<T> {
public Box(T value) { this.Value = value; }
public T Value { get; set; }
public static implicit operator T(Box<T> box) {
return box.Value;
}
}
For example,
public void Test() {
Box<int> number = new Box<int>(10);
Box<string> text = new Box<string>("PRINT \"Hello, world!\"");
Console.Write(number);
Console.Write(" ");
Console.WriteLine(text);
F1(number, text);
Console.Write(number);
Console.Write(" ");
Console.WriteLine(text);
Console.ReadKey();
}
void F1(Box<int> number, Box<string> text) {
number.Value = 10;
text.Value = "GOTO 10";
}
Should output
10 PRINT "Hello, world!"
20 GOTO 10
In regards to the answer by the asker, what's wrong with:
class Program
{
static void Main()
{
string str = "asdf";
MakeNull(ref str);
System.Diagnostics.Debug.Assert(str == null);
}
static void MakeNull(ref string s)
{
s = null;
}
}
Ok, I found another partial solution to my problem. You can use overloading, if you want some ref/out-arguments to have null values:
void Test()
{
string ret1 = "", ret2 = "";
SomeFunction(ref ret1, ref ret2);
SomeFunction(null, ref ret2);
SomeFunction(ref ret1, null);
SomeFunction(null,null);
}
string null_string = "null";
void SomeFunction(ref string ret1,ref string ret2)
{
if( ret1!=null_string )
ret1 = "ret 1";
if( ret2!=null_string )
ret2 = "ret 2";
}
// Additional overloads, to support null ref arguments
void SomeFunction(string ret1,ref string ret2)
{
Debug.Assert(ret1==null);
SomeFunction(null_string,ret2);
}
void SomeFunction(ref string ret1,string ret2)
{
Debug.Assert(ret2==null);
SomeFunction(ret1,null_string);
}
void SomeFunction(string ret1,string ret2)
{
Debug.Assert(ret1==null&&ret2==null);
SomeFunction(null_string,null_string);
}