'Friend WithEvents' in Visual Basic vs. 'private' in C#
In Windows Forms projects, why does the designer by default use the Friend WithEvents
attributes in VB.NET and private
ones in C#?
For example, in a form.designer.
file:
.cs
private Label L开发者_StackOverflowabel1;
.vb
Friend WithEvents Label1 as Label;
For WithEvents
, it is more or less clear (for using Handles
, apparently). But why Friend in Visual Basic and private in C#?
Friend
is used for compatibility with older Visual Basic code, where normally a control was used outside the form which contained it.
In C# there isn't that necessity.
private
is a better solution, for new code.
Typically VB.NET leans towards exposing too much (privacy is mostly opt-in) whereas C# is the inverse, privacy is typically opt-out. As others have mentioned the reason is likely due to VB.NET's legacy and the "friendliness" of exposing everything; it makes it easy to get started but also leads to poor design and additional effort to ensure loose coupling.
I think it is to help with migration from earlier versions of VB as code in the forms tended to be modified from outside more frequently. Friend is also the default.
Private is better from a code design perspective and is used in C# as there is no similar historic coding practice I guess!
Perhaps Visual Basic is trying to be friendlier to new programmers and allow them to see all the Friend controls in the form from anywhere in their project?
Friend being internal, the only thing I can think of, an I am not sure why the defaults would be different other than to assist new programmers...
精彩评论