1. Home
  2. Computing & Technology
  3. C / C++ / C#
photo of David Bolton

David's C / C++ / C# Blog

By David Bolton, About.com Guide to C / C++ / C#

Answer to C# Programming Puzzle and Another!

Thursday May 8, 2008
If you're used to C or C++ and not C#, you'd expect the compiler to whinge about the casual mixing of incompatible types but C# is more like some scripting languages (eg PHP) in this regard. C# is actually strictly typed but is happy to compile and run this (and outputs a= David 45.60) because all objects, including number literals and types include a ToString() method. So concat works fine!

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() ;
        }
    }
}

Comments

May 8, 2008 at 9:55 am
(1) Robert C. Cartaino says:

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

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Explore C / C++ / C#

More from About.com

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

©2008 About.com, a part of The New York Times Company.

All rights reserved.