Search | | Contact Us | Resource Center Login | Home|

What is the output of the following program?

namespace confusion
  public class String
    public method String
    in req val, a
      m_val = val
    public static method op_Explicit, a
    in req s, @String
      mreturn s.m_val.ToUpper()
    private m_val, @System.String

	s	,@String
	s = new String("abc")

Which answer is correct?

a. "abc"
b. "ABC"
c. A compilation error
d. A runtime error

Correct answer: (b)


In this program, we have defined our own class named ”String” within a namespace called ”confusion”.  The ”System” namespace also contains a class named ”String”—so our question comes down to whether Synergy/DE can allow this. If not, when does it catch the problem? And if so, which one does it use in this case?

Synergy/DE does allow classes with the same name to be defined in different namespaces, but we’ve complicated the issue here by referring in the ”main” program to the ”String” class without qualifying it.

The ”System” namespace is automatically imported, and the ”confusion”
namespace is imported by virtue of being defined within this source file.
In fact, precisely because it is defined here, it has precedence when looking up unqualified class names.  Thus, the answer is (b), which is the result of confusion.String.op_Explicit, invoked by the cast.

If the ”confusion” namespace were defined in an external source file and imported here, then the compiler would have no way to assign a priority to one version of String over another.  That would result in an ”Ambiguous symbol” compilation error (c).

Answer (a) could be achieved in two ways: either don’t define the confusion.String class at all, or qualify the references in ”main” as ”System.String”  (Note, however, that in Synergy.NET neither of these compile because Microsoft’s System.String class does not include an appropriate constructor).

You can’t generate answer (d) in this case, because the Synergy/DE compiler sorts out all of the ambiguities it can, and doesn’t allow others to persist.  That means that you, the developer, may see these problems, but your users won’t.

The real lesson here, though, is that even though these kinds of puzzles don’t confuse the compiler, they can certainly confuse the next programmer who looks at the code.  Don’t use ambiguous class names unless you have a very good reason why you should.

More information about News and Events

Contact Synergex to learn more about  News and Events