Friday, March 17, 2006
« Do graphics within Internet Explorer on ... | Main | Select the Edit Text in a GridView »

The compiler is typically pretty smart when it comes to string literals. Take a look at your code with Reflector and the debugger disassembler.

static void Main(string[] args)

{

    string a = "A" + "B" + "C" + "D" + "E" + "F" + "G";

    Console.WriteLine(a);

}

 

//reflector:

private static void Main(string[] args)

{

    string text1 = "ABCDEFG";

    Console.WriteLine(text1);

}

 

//but it not smarter than your application:

static void Main(string[] args)

{

    string a = "A";

    string b = "B";

    string c = "C";

    string d = a + b + c;

    Console.WriteLine(a);

}

 

//reflector:

private static void Main(string[] args)

{

    string text1 = "A";

    string text2 = "B";

    string text3 = "C";

    string text4 = text1 + text2 + text3;

    Console.WriteLine(text1);

}

 

//and now for a slightly different question and answer:

static void Main(string[] args)

{

    string a = "A" + "B" + "C" + "D" + "E" + "F" + "G";

    string b = "ABCDEFG";

}

 

take a look at the debug disassembly and you will see that both a and b are initialized with the same literal:
string a = "A" + "B" + "C" + "D" + "E" + "F" + "G";
00000029 mov eax,dword ptr ds:[0227307Ch]
0000002f mov edi,eax
string b = "ABCDEFG";
00000031 mov eax,dword ptr ds:[0227307Ch]
00000037 mov esi,eax

kick it on DotNetKicks.com   Friday, March 17, 2006 10:02:22 PM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [0]  | 
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview