Answer to C# Programming Puzzle and Another!
Continuing the C# oddities as I've just finished the next C# Tutorial on strings. Is there any difference between the two string variables s1 and s2 in the code below? Is the comparison true or false?
using System;
using System.Text;
namespace ex1
{
class Program
{
static void Main(string[] args)
{
string s1 = "".PadRight(60) + '*';
string s2 = String.Empty.PadRight(60) + '*';
if (s1 == s2)
Console.WriteLine("They're the same!") ;
else
Console.WriteLine("They're not the same!") ;
Console.ReadKey() ;
}
}
}
- Link to C# Tutorials
- Link to Compilers and Interpreters Article


Comments
string s1 = “”.PadRight(60) + ‘*’;
string s2 = String.Empty.PadRight(60) + ‘*’;
Functionally, they are identical (i.e., it will print “They’re the same!”.
Internally, String.Empty is a static constant so no object will be created. But (”") will create a new manage object and treat it as such.
The memory footprint may be a bit different but they will execute the same way, though.
Robert C. Cartaino