简体   繁体   中英

Differences about importing namespace in C# and VB

I'm starting to learn C#.

In VB, when we adding a new references - in my case web references -, it simply type namespace followed by the class name to make a new object. For example:

Dim obj As NamespaceName.ClassName = New NamespaceName.ClassName

Then I apply this concept in C#. So my code will be:

NamespaceName.ClassName obj = new NamespaceName.ClassName

...and it doesn't work.

Actually, is there any difference about Importing Namespace between those two? And also can you give me a little explanation about Project-Wide Default Namespace Imports in VB?

UPDATE My point is why "In C#, When I've typed NamespaceName, the ClassName was not listed in the Intellisense?". However, it did well in VB, do I have to import something? Maybe, there is something to do with the term "Project-Wide Default Namespace Imports". (CMIIW)

SOLVED

In C# you need parenthesis () when invoking the constructor at the end:

NamespaceName.ClassName obj = new NamespaceName.ClassName();

VB.NET is more permissive and doesn't require them.

As pointed out in the comments by Anthony Pegram, in C# if you use object initializer syntax, you don't need the parenthesis, you replace them by braces { }

NamespaceName.ClassName obj = new NamespaceName.ClassName
{
    SomeProperty = "some value"
};

您是否尝试过

NamespaceName.ClassName obj = new NamespaceName.ClassName();

In your C# project, do you have a reference to the assembly where this class exists? Different project templates may have different default assembly references, or you may have forgotten to add a reference in your C# project that you have in your VB project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM