Thread: Reference Types

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    329

    Reference Types

    Hi,

    I've just started looking at C#, and I have a question about reference types, such as string.

    If I wanted to pass a string into a function by reference, would I need to use the ref keyword with the string already being a reference type? Or should I simply pass the string as-is?

    Thanks,


    Darren.

  2. #2
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    It is a bit tricky when you think of a StringBuilder and a string since you might think that they are both reference types. But you would do this:
    Code:
    void Update(StringBuilder text) {...}
    void Update(ref string text) {...}
    The reason is that strings are immutable.
    Consider this
    Code:
    void Update(string text) {...}
    ...
    string str = "Hey";
    Update(str);
    What will happen is that the function will do text = str. But since strings are immutable the value of the string will be copied not the "reference". If it was a StringBuilder which is like a string but mutable the actual reference (the pointer - the location in memory) would be copied and you would have been OK. So it is not their type, it is the way they are copied.

    The thing you need to know is that strings are kind of an exception of a reference type and you shouldn't use them as such. So you would just need the "ref" keyword.

  3. #3
    Registered User
    Join Date
    Feb 2009
    Posts
    329
    Thanks, thats pretty much clear now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  2. non-const reference and const reference
    By George2 in forum C++ Programming
    Replies: 3
    Last Post: 12-15-2007, 05:03 AM
  3. C OpenGL Compiler Error?
    By Matt3000 in forum C Programming
    Replies: 12
    Last Post: 07-07-2006, 04:42 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Problem with OpenGL tutorial
    By 2Biaz in forum Windows Programming
    Replies: 18
    Last Post: 09-16-2004, 11:02 AM