Jump to content
  • Advertisement
Sign in to follow this  
dmreichard

[.net] C# string reference parameters

This topic is 3724 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

A minor curiosity I've had... Since System.String is a class, and therefor a reference type, why is it that when I pass a string to a function it acts as a value type and makes a copy of the string? I realize I can use the ref/out modifiers if desired, but this has just been a minor curiosity of mine since I started learning the C# language, and no book or article I've read has explained it yet. I also realize this is a cleaner design choice if one would actually want a copy of the string without having to manually create one to avoid changing the original, forcing the programmer to pass by reference explicitly to avoid undesired effects. But I've just been curious how this is implemented or if I am completely wrong. [smile] Thanks!

Share this post


Link to post
Share on other sites
Advertisement
strings don't act as value types. They always act as reference types. The trick is that no operation that modifies a string returns the same string. It always returns a new (modified) string.

Share this post


Link to post
Share on other sites
Strings are reference types, but in many ways you can think of them as a value type, since they are immutable. Like you said, this makes string handling much cleaner, and also makes sense when you think about that fact that strings can reference literal values, which you can't really change.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!