user2621858
user2621858

Reputation: 121

Reference types behaves like value type in VB.NET

Even though "String" is a reference type, in VB.NET, we only get the effect of using of a reference type if we pass a parameter as ByRef. So, unlike C# even reference types in VB.NET behaves like value type by default. Why is there this kind of difference?

Upvotes: 1

Views: 885

Answers (2)

Hans Passant
Hans Passant

Reputation: 941277

No, System.String is as much a reference type in C# as it is in VB.NET. It is however a bit special; it doesn't have any method or property that lets you change the string.

You can only ever assign a string reference variable with another string object. It tends to confuse programmers because the syntax resembles the way you assign a value type value; you very rarely use the New operator. You don't have to; assigning a literal doesn't require New. And System.String has many methods that return a new string object; creating the object is done inside the method. Notable is that using the Replace() method and forgetting to use the return value is a very common mistake.

This design was quite intentional; it makes it safe to pass a string as a method argument without any risk that the called method will change it. And automatically makes a string thread-safe. Both very important properties for such a common type.

It does have a notable disadvantage; your program tends to generate a lot of garbage when it uses strings. Since they rarely live for very long. Which is okay; the garbage collector was written to optimize this case, and it performs generation 0 collections very quickly. The StringBuilder class is a fallback; it is mutable.

Upvotes: 1

samar
samar

Reputation: 5201

If you are trying to understand reference types and value types and their differences in VB.NET and C#.NET using string as an example then you will confuse yourself big time.

Just as David mentioned, strings are reference types, but they are special, that is, immutable. Which means that once you have created a string on a reference address you cannot modify them. If you try to do that then .NET will store your modified string on a different address and start pointing to the new address. The old address will get garbage collected over a period of time.

For example

string str = "new string"; //One address space
str = "modified" + str; //Different address and not same address as above

Moreover, when you are passing a string by reference to a method and modifying the string in the method, it is actually just pointing to a different reference, but it makes you feel that the actual reference is updated.

I hope this clarifies your question a little.

Upvotes: 1

Related Questions