简体   繁体   中英

VB.NET class members public by default

According to MSDN :

Public access is the normal level for a programming element when you do not need to limit access to it. Note that the access level of an element declared within an interface, module, class, or structure defaults to Public if you do not declare it otherwise.

So, if I declare a class method in VB.NET without specifying an access modifier, then it is public by default:

Sub DoSomething()

End Sub

This is insane! I want members to be private by default, and only those specifically marked as Public to be visible outside the class. Like in C#... How do I modify this behaviour?

This is insane! I want members to be private by default

As Fredrik has already commented, you should always provide explicit access modifiers.

The code will be much more clear for other readers if you always explicitly include the access modifier.

I assume that this is due to downwards compatibility or developers who are not familiar with access modifiers at all.

But you are right, as in C# I would suggest to make everything as private as possible by default. You can make it more public when needed.

Declaration Contexts and Default Access Levels (VB.NET)

Any idea how to modify this behaviour?

I don't think that it's possible to specify the default access modifier somewhere in Visual Studio. You could try to create a template-class which is suggested here (not tested):

Visual C# 2010 Express: Specify default access modifier for new classes?

Visual Basic 6 properties and methods were by default Public. As VB.NET was the successor to VB6, I believe the decision was made to continue this behaviour.

https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa266191(v=vs.60)?redirectedfrom=MSDN

As for the topic of modifying the behaviour in VB.NET - other than changing the templates or creating a Macro to find/replace, there is no way to achieve this.

(Yes, I know this is a very old topic)

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