To string or not to String.


 

When to use String and string.

 

This question seems to come up periodically and I find myself going through this exercise to explain. So, I thought it was time to write it up. After all one of the core principles I live by as a developer is, “if you do or know you will be doing something more than once, automate it!”

 

 All of .Nets reference types inherit from System.Object either directly or indirectly, and the String class is no different. The keyword “string” (lower case s) is simply an alias for System.String and thus can be used directly. Let’s take a look here when we typeof both them and see what we get:

 

 

However, this is about understanding when to use ‘string’ and when to use ‘String’, who cares about a lower or upper case S right? Well, anyone trying to read your code will care and you will help them do that task much easier by knowing this little bit. When we declare and instantiate the following:

 

string  _foo = “This ‘string’ is a variable”;

 

We know by the lower case string and the dark color blue (at least in Visual Studio) that this is a variable.

Now, when we do it this way:

 

String  _foo = “This ‘String’ is a variable as well but looks like a the convention we use for methods”;

 

Here we know by the upper case S and the teal-ish color that this is a coding convention we use for Classes and Methods.

 

Now does it work this way? Sure let’s jump to Visual Studio and take a look:

 

 

 

As you can see in the output, both strings compiled and function just fine but again the second instantiation or capital style looks like a Class or Method convention. Further on down in code I call the String.Equals method and pass our 2 strings _roadGlide and _streetGlide to give you a visual comparative. Also, at the top in the first line of the code you can see where we define the class for ‘Program’ and compare its convention.

 

So in conclusion, when you need to declare or instantiate a string to use as a variable use ‘string’ and when you are calling a method off the String Class us the capital S convention. Anyone reading your code will thank you for it and as well you will thank yourself as you go back to read your code down the road.

 

Now get out there and color the world in CODE!


Comments (0)

Skip to main content