Is a C# String a Value Type or a Reference Type?

First, let’s establish the difference between a value type and a reference type in C#.

There are two types in C#, class and struct, and the .NET Framework deals with them in different ways.

Structs are the value type. In addition to defined structs this also includes primitive value types like bool, int, and char. When a Struct, or value type, instance is created a single memory space is allocated to store the value. When the framework is dealing with a value type it deals directly with the memory location. This is quite efficient for simple data such as numbers and single characters.

Classes are the reference type. Unlike structs, memory for classes is accessed indirectly through pointers. Each instance points to a different section of memory. This allows a greater degree of flexibility while incurring a performance cost. Fortunately in C#, unlike C++, we don’t have to worry about managing pointers to our data, the runtime handles it for us.

When we consider strings in C# it can get confusing since, although they’re a reference type, they behave somewhat like a value type too. For example, we can use the equal sign to set the value of a string from another string just like we do for integers. This is different than how we set the value of a new object we’ve defined in our code or, for that matter, other classes in the Framework. However, behind the scenes, the .NET Framework is allocating memory for separate instances for each string for us.

This ‘shorthand’ can cause you to think that a string is a value type and not a reference type. That’s why we have to be careful in order to avoid performance sapping operations like looping string concatenations. Each iteration of such a loop causes new instances to be created in a different memory area. As the string builds, considerable resources are used to construct the string over and over again. That’s why using StringBuilder is preferred in this situation since it doesn’t allocate a new string for each concatenation operation.

I hope this answers the question, “Is a C# String a Value Type or a Reference Type?” for you.

Related posts:


No Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment

Theme Provided By Free HTML Layouts