[.net] c# references and strings and stuff (pointer to string?)

Started by
2 comments, last by kbirger 14 years, 11 months ago
Hi, I have class A which has a string inside member variable and a function. I have another class B which has a function. I would like to be able to do something like:

class A {

  string s_out = new string("");

  A(ref string s) {
    s = s_out;
  }

  void func() {
    s_out = "something";
  }
}

class B {
  void func() {
    string s = null;
    A a = new A(ref s);
    a.func();
    // will s be "something" here? or how would you get that done?
  }
}

Thanks in advance.
[size=2]aliak.net
Advertisement
No, that won't work. Strings are immutable in C#, and assigning a string literal to a variable simply updates the variable to point to the new reference. It doesn't actually change the value stored at that reference.

There isn't really a direct way to do what you're asking, but if you let us know what you're actually trying to do, we can probably help you out with a solution that works around the problem.
Mike Popoloski | Journal | SlimDX
For what it's worth, StringBuilder works as a mutable string, though as Mike.Popoloski pointed out it would be better to understand what you're trying to achieve first.

[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]

In addition to what was said...

"ref" grants the SCOPE access to the pointer. When you assign s = s_out, you're assigning the pointer of s to be the pointer of s_out.

I also don't think you can do ref in constructors... It seems like a bad idea

Instead of referencing the string directly in places, consider making a property on A that returns the updated string, or if you need late binding, make "func()" return the string, and create a delegate to it. (or just train all your code to be able to deal with instances of A and know to call the property on it, whichever makes more sense to you)

This topic is closed to new replies.

Advertisement