I recently came across a problem in some C# code: Somebody had created a variable with the same name as an existing namespace. I wanted to refer to the namespace but I couldn't because of the variable. An example is below:
class Test
{
public Function()
{
string System = "this is a string called System";
// the line below will cause an error, because System
// refers to the variable above, not the "System" namespace
System.GC.Collect();
}
}
Obviously giving a variable the same name as an existing namespace isn't a very good idea, and should probably be avoided at all costs. However, I was intrigued to see if it was possible to get around this issue without having to rename the variable. C# does provide a solution:
using Sys = System;
class Test
{
public Function()
{
string System = "this is a string called System";
Sys.GC.Collect();
}
}
The line
using Sys = System;
creates an alias for the System namespace, which you can then use.
I've never run into this problem before because generally speaking people are sensible enough not to give their variables the same names as namespaces. I suspect this issue isn't only a C# one though, and I'd be interested to see if there are any similar work arounds in other languages. If you know of any please leave a comment!