Comments

Difference between string and String in C#

One of the questions that many novice C# programmers ask is: “What is the difference between string and String?”

In C#, string is an alias for the String class in .NET framework. In fact, every C# type has an equivalent in .NET. As another example, short and int in C# map to Int16 and Int32  in .NET.

So, technically there is no difference between string and String, but it is common practice to declare a variable using C# keywords. I’ve hardly seen anyone declaring an integer with Int32!

The only tiny difference is that if you use the String class, you need to import the System namespace on top of your file, whereas you don’t have to do this when using the string keyword.

Many developers prefer to declare a string variable with string but use the String class when accessing one of its static members:


String.Format()

The examples on MDSN also follow this convention.

Related Posts

Tags:

2 responses to “Difference between string and String in C#”

  1. Peter says:

    UpperCamel case defines a Class. So String is a class that has methods in C#. Like String.IsNullOrEmpty().

    The lower case string and then all the int,long,byte,etc are special keywords, that define a compiling type.

    Yes, can define a string as String or string because of historical reason needed for compatibility when people migrated VB5 and VB6 to .NET – And we are paying for that choice till today, instead of forcing the convention from the begging to be correct. Not many people remember that but I do. So that is where the damned Alias come from.

    Other than OCD it doesnot really mater in C# if you use int/Int32 long/Int64 string/String , unless you like your project to be very colourful.

Leave a Reply