Skip to main content

Posts

Showing posts with the label #String in C#

#C# String is Immutable in C#

There is a term called immutable, which means the state of an object can't be changed after is has been created.  A string is an immutable type. The statement that a string is immutable means that, once created, it is not altered by changing the value assigned to it. If we try to change the value of a string by concatenation (using + operator) or assign a new value to it, it actually results in creation of a new string object to hold a reference to the newly generated string. It might seem that we have successfully altered the existing string. But behind the scenes, a new string reference is created, which points to the newly created string. string s1="Hi"; string s2=s1; s2=s2+"Raj"; s1  -> pointer to data "Hi" s2  -> pointer to date "Hi" -> pointer to data "Hi Raj" here s2 is pointing to new data. that is s2 pointer is changed.(Immutable)

#c# String is a reference type. Why?

The data type Integer is a  value type , but a String is a  reference type .  Why ? A String is a reference type even though it has most of the characteristics of a value type such as being immutable and having == overloaded to compare the text rather than making sure they reference the same object. Why a string is just a value type Why isn't a string just a value type, then?   First of all let's understand what value types and reference types are and the difference between them in a glance. The types can be classified depending on whether a variable of a specific type stores its own data or a pointer to the data. That means, instead of storing data, it stores its address. I f it stores its own data it is a value type and if it holds a  pointer  to data  elsewhere  in memory it is a reference type. Value types are stored in the Stack whereas reference types are stored in the Heap.