jay's old blog

this blog will be deleted soon - please visit my new blog - https://thesanguinetechtrainer.com

Strings and stuff

Can you think of any program where you don’t use a string? I cannot. We are constantly working with strings. When learning programming, the first thing that we do is write the 'hello world' program which is about displaying a string. When working with web services, and data comes back in json, it’s a string. Everything and anything can be represented as a string. Numbers, decimals, date, weather, temperature and you name it. All of them can be represented as strings.  

That is why c sharp has a lot of  string related stuff to help you, the developer, reduce the workload related to playing with strings. Almost anything and everything related to strings (manipulating them, traversing them, building them and so on) is already available in .net and c sharp.  

Other blog posts will spend a little more time on focusing on specific string related features. Here, I want to emphasize on one simple thing. That is the fact that strings are immutable. What does that mean really? The thing is, once you create a string (and assign a value to it) it cannot be modified. It's sort of like a tattoo. It's set in shape until it dies.  

So, when you do  

string hello_world = "hello world";  

The string "hello world" will remain as its until it is no longer referenced and garbage collected. That means, the following statement will make you think. 

Hello_world_2 = hello_world + "there"; 

When executing this statement, a new string is created called "there". Then, the contents of "hello world" and "there" are copied over to another new string which will eventually contain "hello world there". Why did two new strings created instead of the original string modifying itself from "hello world" to "hello world there"? That would be simpler isn't it?  

On the outset, it would be simpler. However, the property of being immutable makes sure that the string object cannot be modified. This is a better way of dealing with strings because, as a developer, I know that once a string is created, it cannot be modified by any part of the program. This certainty allows me build thread save string related applications.  

I have not attached any doe to this blog post. We have already used strings many times in many our previous code repos.

Follow me on twitter, facebook and instagram for more updates. Thanks!

Comments are closed