What is the Difference Between String and string in C#?

What is the Difference Between String and string in C#?

Are you new to C# and .NET and struggling to understand the difference between 'string' and 'System.String'? This post will clear things up and provide code examples.

In C#, there is technically no difference between 'string' and 'System.String'. 'System.String' is a class in the .NET framework that belongs to the namespace 'System', while 'string' is simply an alias for 'System.String' in C#.

To demonstrate this, consider the following code:

string lowerCaseString = "What is Lorem Ipsum?";
System.String capitalString = "Lorem ipsum is placeholder text.";
            
Console.WriteLine("Type is: " + lowerCaseString.GetType().FullName); 
// Type is: System.String
Console.WriteLine("Type is: " + capitalString.GetType().FullName); 
// Type is: System.String

As you can see, both variables lowerCaseString and capitalString are of type System.String, indicating that both are referring to the same type.

It is recommended to use the lowercase 'string' when declaring string variables in C#, although some developers prefer using the keyword 'string'. 'System.String' is typically used when calling built-in string methods, such as System.String.IsNullOrEmpty().

.NET Data Type Aliases

In .NET, data type aliases are alternative names for data types that are provided for convenience and readability. These aliases are equivalent to the underlying data types and can be used interchangeably with the full data type names.

Here are some common data type aliases in .NET:

Alias

.NET Type

byte

System.Byte

sbyte

System.SByte

int

System.Int32

uint

System.UInt32

short

System.Int16

ushort

System.UInt16

long

System.Int64

ulong

System.UInt64

float

System.Single

double

System.Double

char

System.Char

bool

System.Boolean

object

System.Object

string

System.String

decimal

System.Decimal

DateTime

System.DateTime


Post a Comment

Previous Post Next Post