Sign in to follow this  
IFooBar

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

Recommended Posts

IFooBar    906
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.

Share this post


Link to post
Share on other sites
Mike.Popoloski    3258
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.

Share this post


Link to post
Share on other sites
benryves    1999
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.

Share this post


Link to post
Share on other sites
kbirger    100
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)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this