VB.NET namespace abbreviation: How do I make this work in equivalent C# code?
-
27-04-2021 - |
Question
I am a VB.NET programmer by nature and I am having a hard time figuring this out. Any help with the following would be appreciated.
I need to get the C# code (1) below to work. The VB.NET equivalent works just fine, but the C# does not.
Note that both (2) and (3) do work, but this is actually auto-generated code, and I need the VB.NET and C# versions to be as similar as possible.
This does not compile (the fully-qualified name of
Engine
isThreeD.QVB.Engine
):using ThreeD.QVB; namespace QVBScript { public class ScriptCode { public void Main(ref Engine.QVBObjectsDictionary objects, Engine.Commands commands) { …
However, this does work:
//using ThreeD.QVB; // I'm instead using fully-qualified names in the method namespace QVBScript { public class ScriptCode { public void Main(ref ThreeD.QVB.Engine.QVBObjectsDictionary objects, ThreeD.QVB.Engine.Commands commands) { …
This works, too:
using eng = ThreeD.QVB.Engine; namespace QVBScript { public class ScriptCode { public void Main(ref eng.QVBObjectsDictionary objects, eng.Commands commands) { …
Solution
In VB.NET if you have an import
for the first part of a namespace, you can reference just the later half. In C# you cannot do this. You must have a using
for the full namespace, or fully qualify your type names. Different languages, different rules.
In your last example you do not need to use the alias.
using ThreeD.QVB.Engine;
namespace QVBScript
{
public class ScriptCode
{
public void Main(ref QVBObjectsDictionary objects, Commands commands)
{
UI.Output Output = (UI.Output)objects["Output"];
OTHER TIPS
Basic rules to remember:
using A.B;
does allow you to refer to types from namespaces
A
andA.B
without fully qualifying them with their namespace (everywhere in the same file).does not allow you to abbreviate the names of sub-namespaces of
A
orA.B.
by omitting theA.
orA.B.
part from their names.
namespace A.B { … }
does allow you to refer to types from namespaces
A
andA.B
without fully qualifying them with their namespace (inside the block).does allow you to abbreviate the names of sub-namespaces of
A
orA.B
by omitting theA.
orA.B.
part from their names.
Example:
using System.Collections;
namespace A
{
class Top : IDisposable, // importing System.Collections also imports System
IEnumerable, // inside the imported namespace
System.Collections.Generic.IEnumerable<int>
{…} // ^ "using" does not permit namespace abbreviation
}
namespace A.B
{
class Middle : Top, // namespace A available inside namespace A.B
C.IBottom // namespace blocks permit namespace abbreviation
{…}
}
namespace A.B.C
{
interface IBottom {…}
}