In a recent VB.NET project I adopted the naming conventions I'm used to using in C#. Namely, often calling a variable the same name as the class it references, only with a different case, e.g.
Foo foo = new Foo(); // C#
Dim foo As New Foo() ' VB.NET
I find this is often the clearest way to write code, especially for small methods. This coding style obviously works fine in C#, being case sensitive, and because of the syntax highlighting provided by Visual Studio, it is very easy to see that the class name and the variable name are different.
However, to my surprise, this also worked fine nearly 100% of the time* in VB.NET. The only issue was that the variable name then appeared to take on a multiple identity. Namely it could be used to call both instance methods and Shared (static) methods of the Foo class. This didn't really cause any problems though, it just meant that Intellisense would provide a list containing both static and instance methods after you hit the '.' after the variable name.
I found, again to my surprise, that this didn't actually lead to any confusion in my project, and it's been very successful so far! However I was the only person working on this particular project.
Here is a slightly longer example:
Dim collection as Collection = New Collection()
For Each bar As Bar in Bar.All()
collection.SomeInstanceMethod(bar)
Next
collection.SomeSharedMethod()
* The only issue I found with this was that sometimes the 'Rename' refactoring tool got confused, i.e. when renaming a class it would rename the variables with the same name as the class as well, in their declaration lines (Dim foo As...), but not the other references to that variable, causing compiler issues (duh). These were always easy to correct though.
Another small annoyance is that the VB.NET syntax highlighter doesn't highlight class names any differently than variable names, making it not quite as nice as when using it in C#. I still found the code very readable though.
Has anyone else tried allowing this in a team environment? Are there any other potential issues with this naming convention in VB.NET?
Although VB is case-insensitive, the compiler is intelligent enough to not being confused between the object-instance and the class.
However, it's certainly very dangerous and wrong to use the same name in a case-insensitive language! Especially if other programmers are working on that project.
I have to move back and forth between VB and C#, and we consider this poor practice. We also don't like letting variable names in C# differ from their type only by case. Instead, we use an _ prefix or give it a more meaningful name.
Whenever you start a new language it's inevitable you'll notice a bunch of things that are different and miss the old way of doing things. Often this is because you are initially unaware of different features in the other language has that address the same problem. Since you're new to VB, here are a couple notes that will help you get things done:
It's not 100% correct to say that VB.Net is case-insensitive unless you also make the point that it is case-aware. When you declare an variableidentifier, the IDE will take note of what case you used and auto-correct other uses to match that case. You can use this feature to help spot typos or places where the IDE might be confused about a variable or type. I've actually come to prefer this to real case-sensitive schemes.
VB.Net imports namespaces differently. If you want to use the File class, you can just say IO.File without needing to import System.IO at the top. The feature especially comes in handy when learning a new API with a few nested namespace layers, because you can import a top-level section of API, type the next namespace name, and you'll be prompted with a list of classes in that namespace. It's hard to explain here, but if you look for it and start using it, you'll really miss it when going back to C#. The main thing is that, for me at least, it really breaks my flow to need to jump to the top of the file to add yet another using directive for a namespace I may only use once or twice. In VB, that interruption is much less common.
VB.Net does background compilation. The moment your cursor leaves a line, you know whether or not that line compiles. This somewhat makes up for not highlighting class names, because part of why that's useful in C# is so you know that you typed it correctly. VB.Net gives you even more confidence in this regard.
I'm going to differ with the rest of the answers here... I don't think there is any problem with doing this. I do it regularly, and have absolutely 0 problems resulting from it.
If you use lowercase for the variable name you can easily differentiate the variable from the type, and the compiler will not confuse the two identifiers.
If you delete the variable declaration, the compiler will think other references to this variable now refer to the type, but it's not really a problem because those will be tagged as errors.
I have done the same thing in the past. I'm starting to move away from it though because Visual Studio will occasionally get confused when it auto formats the code and changes the casing on my static method calls to lower case. That is even more annoying than not being able to differentiate the variable and class names by case only. But, purely from technical perspective it should not cause any issues.
As Moayad notes, the compiler can tell the difference--but it's bad practice that can lead to maintenance issues and other side effects.
A better practice all-around is to try to name the variable in the context they're being used, rather than just the type name. This leads to self-documenting code and requires fewer comments (comments are greatly abused as an excuse to write dense code).
It's only safe as long as the compiler can always tell whether Foo means the class or the variable, and eventually you'll hit a case where it can't. Eric Lippert discusses the sort of thing that can go wrong on his blog.
I use this convention all the time, and it's never been a problem. The most natural name for a variable is often the class name, and therefore that's what you should call it (Best name for an arbitrary Line? line.).
The only downside is when some tool interprets the context incorrectly. For example, visual studio 2010 beta 1 sometimes uses the class highlight on variables named the same as the class. That's a bit annoying.
Context sensitivity is much closer to how I think than case sensitivity.
Well, this isn't the final answer, and I don't think there is a definitive one, but the general opinion seems to be that it's not a good idea to use this naming convention! There must be one true way to write nice VB.NET variable names though, and I don't like any of the alternatives...
Here are links to the official Microsoft guidelines for anyone who's interested, although they don't seem to cover this particular question (please correct me if I've missed it).
Visual Basic Naming Conventions: http://msdn.microsoft.com/en-us/library/0b283bse.aspx
Declared Element Names: http://msdn.microsoft.com/en-us/library/81ed9a62.aspx
Cheers all!
VB.NET isn't case sensitive! This equates to:
Foo Foo = new Foo(); // C#
As a standard in our team environment we would use:
Dim oFoo as New Foo 'VB.NET
Related
I have a class named AppVisum.Membership.Views.AppVisum.Membership.Controllers.Membership._Page_Views_AppVisum_Membership_Controllers_Membership_Validate_cshtml. Yeah, I know it is hidious, but I rather think it has to be named that, and as for the namespaces, those are unnecessary, but the class is generated by a tool, and the folder needs to be named AppVisum.Membership.Controllers.Membership, so I don't know if I can change the namespaces. However, hideous names isn't the real problem, the main issue is getting to the class AppVisum.Sys.AppSys. The ide tells me that it can't find AppVisum.Membership.Views.AppVisum.Sys.AppSys, so how can I tell it that I want the root one?
[Edit]
Sorry I wasn't specific enough as I thought this would be a simple problem to solve. The global:: would've worked perfectly if this had been a normal .cs file, however, it's a razor-file and razor don't quite like #using global::AppVisum.Sys (that just translates to using global, which doesn't make any sense). I've found 2 possible solutions, the first is to simply change the rule that search for files to search for folders with _ instead of .. Then I'd get paths like AppVisum.Membership.Views.AppVisum_Membership_Controllers_Membership._Page_Views_AppVisum_Membership_Controllers_Membership_Validate_cshtml. This would probably work just fine, and unless someone comes up with a better alternative I think I'm going for that. Another option is to rewrite the custom-tool that generates the classes (it's opensource, so I think I should be able to do that too fairly simply). Hope that clarifies things.
Add the global:: prefix to the namespace.
try:
using Sys = AppVisum.Sys;
or:
using AppSys = AppVisum.Sys.AppSys;
Basically, you can reduce ambiguity by aliasing types and namespaces in your using directives. (And the aliases don't need to be the same as the type/namespace names, they just are in my examples.)
As SLaks mentions in a comment, you should basically fix your project's default namespace - either that, or avoid creating the folder hierarchy. You've tagged this question with C#, but is your generated code actually in VB? While the VB compiler prepends the project's namespace when compiling, I don't believe the C# compiler does, so I'm surprised you're getting this namespace to be honest.
I disagree with your claim that "hideous names isn't the real problem" - I'd say it is the real problem, and making it hard to get at a particular namespace is one consequence of the problem. Fix the real problem (the bad namespaces) and the rest will go away. Using global:: etc is just a workaround, and one that you'll need to apply all over the place. It would be better to sort this out once and for all.
Basically if you can tell us more about how you've got into this situation, we're more likely to be able to help you get out of it.
maybe you can simplify by adding an using alias :
using AV = AppVisum.Membership.Views.AppVisum;
and in the code :
var s = new AV.Sys.AppSys();
edit typos
Hi,
This is possibly a moronic question, but if it helps me follow best practice I don't care :P
Say I want to use classes & methods within the System.Data namespace... and also the System.Data.SqlClient namespace.
Is it better to pull both into play or just the parent, ie...
using System.Data
using System.Data.SqlClient
or just...
using System.Data
More importantly I guess, does it have ANY effect on the application - or is it just a matter of preference (declaring both the parent and child keeps the rest of the code neat and tidy, but is that at the detriment of the application's speed because its pulling in the whole parent namespace AND then a child?)
Hope thats not too much waffle
It doesn't make any difference to the compiled code.
Personally I like to only have the ones that I'm using (no pun intended) but if you want to have 100 of them, it may slow down the compiler a smidge, but it won't change the compiled code (assuming there are no naming collisions, of course).
It's just a compile-time way of letting you write Z when you're talking about X.Y.Z... the compiler works out what you mean, and after that it's identical.
If you're going to use types from two different namespaces (and the hierarchy is largely illusional here) I would have both using directives, personally.
Click Organize->Remove Usings and Visual Studio will tell you the correct answer.
Firstly, it has no effect on the application. You can prove this by looking at the CIL code generated by the compiler. All types are declared in CIL with their full canonical names.
Importing namespaces is just syntactical sugar to help you write shorter code. In some cases, perhaps where you have a very large code file and are only referring to a type from a specific namespace a single time, you might choose not to import the namespace and instead use the fully-qualified name so it's clear to the developer where the type comes from. Still, though, it makes no difference.
Express what you mean and aim for concise, clear code - that's all that matters here. This has no effect on the application, just on you, your colleagues and your future workers brains.
Use whatever happens when write your type name and press Ctrl + .,Enter in VS.
In my background in C++ I was a supporter of using the scope resolution operator, for example
class Foo
{
std::list<int> m_list;
...
}
for external libraries, to keep clear which library you were using.
Now in C# I don't know if there's a rule of thumb or a best practice to know which packages should be included via the using keyword and which classes should be fully qualified. I suppose that this can be a subjetive issue, but would like to know the most extended practices.
I pretty much never fully qualify names - I always use using directives instead.
If I need to use two names which clash, I'll give both of them aliases:
using WinFormsTextBox = System.Windows.Forms.TextBox;
using WebFormsTextBox = System.Web.UI.WebControls.TextBox;
That rarely comes up though, in my experience.
I tend to make autogenerated code fully qualify everything though, just for simplicity and robustness.
I think the saving grace in C# is the directives are fully constrained to the file you place them in. I use them whenever their use is clear for the code in the file and it helps readability of the code. Another team at my office doesn't use them at all - I think it's nuts but they came up with their own rules and are happy with them.
Tend towards whatever makes the code more readable and understandable.
If the name may be ambiguous and their is no common "most likely case" then fully/partially qualifying to make this clear can be sensible even if this increases verbosity.
If confusion exists but one candidate is far more likely then qualify only in those cases where you do not use the most common case.
Common example is the use of System.Collection.X classes rather than the System.Collections.Generics versions (perhaps for back wards compatibility). In this case importing the generic namespace is fine and any non generic ones are fully qualified.
This makes it clear where you are using legacy code.
If you will be dealing with multiple clashes and the resulting full qualification would make you code extremely unreadable then it may make sense to use aliases to separate them out but you should be pretty averse to doing this since it renders the resulting code easier to physically read but harder to conceptually understand.
You have injected an element of inconsistency with the wider world. this makes code snippets within the class harder to understand in isolation.
If you must do this consider alias names which make it very clear that these are aliases as an indication to readers that they should look at the using statements for confirmation of the real types.
I have a team with people that are quite comfortable in C# but we got a requirement to write a project in VB.net. How hard would it be to think in C# and on the fly convert to VB?
Is that doable?
Could you list the issues that we can come across?
I heard that VB.net doesn't have closures. Is that still true for .net 3.5?
If you are approaching VB.Net with the mindset of C# it's best to set the following options in the project
Option Strict On
Option Explicit On
Option Infer On
This essentially removes the late binding semantics of VB.Net and forces it to be a strictly typed language. This will make it closer to C# semantic wise (still not exact by any means).
VB.Net has Lambda Expression (and hence Closure) support starting with the Visual Studio 2008 / .Net Framework 3.5 release. Not expression and not Statement. Statement lambdas are not supported until VS2010 / .Net Framework 4.0. Although you can use the 4.0 compiler to downtarget 2.0 frameworks.
As C# and VB.NET uses the same framework and compile to very similar IL code, you have a lot for free. Writing Basic syntax instead is not that hard.
The C# syntax is more aimed at showing what's going on, while the VB syntax often hides away some details, so a C# programmer is already familiar with some concepts that may not at all obvious to a VB programmer. In some ways learning C# is a better way to learn how VB works than to learn VB itself...
I frequently answer VB.NET questions in different forums mostly based on my C# knowledge, and I still haven't written anything more than short test programs in VB.NET myself.
There are of course some quirks to look out for in VB. Like the / operator for example that always converts both operands to double, or the = operand that uses VB specific comparison code rather than the comparison specified for the equality operator in the .NET classes.
One area that VB.NET tends to try and cover up is working with events; others have briefly touched on some of the differences, but here's a little more on them:
VB.NET provides a WithEvents keyword for fields that raise events. If the field is declared WithEvents then you can add a Handles field.Event to the end of a method whose signature is compatible with the event; that method will automatically be a delegate of the event without needing to manually AddHandler and RemoveHandler (+= and -=).
Private WithEvents SomeField
Public Sub SomeField_SomeEvent(sender as Object, e as EventArgs) Handles SomeField.SomeEvent
Console.Writeline("SomeEvent occured")
End Sub
Event declarations and raising events are simplified a bit. VB.NET doesn't require that you check if an event is null prior to notifying listeners:
Public event SomeEvent as EventHandler(of SomeEventArg)
Public Sub SomeMethod()
RaiseEvent SomeEvent(Me, new EventArgs)
End Sub
One "hidden" feature of events in VB.NET is accessing the underlying MulticastDelegate, to do something like GetInvocationList() Note: the event is named SomeEvent and the code to access the multicastdelegate calls an invisible field named SomeEventEvent:
Public event SomeEvent as EventHandler(of SomeEventArg)
Public Sub SomeMethod()
// Note that SomeEvent's MulticastDelegate is accessed by appending
// another "Event" to the end, this sample is redundant but accurate.
// If the event was named ListChanged then it would be ListChangedEvent
dim invocationList = SomeEventEvent.GetInvocationList()
End Sub
One of the biggest issues I've found is the apparent verbosity of VB. It has all these big keywords like MustInherit, NotInheritable, MustOverride, etc., where C# just has things like sealed, abstract and virtual. You have to have an End to everything (End Sub, End Function, End While, End Namespace, End Class, etc.) And you have to explicitly mark read-only properties with the ReadOnly keyword; simply omitting the setter won't fly. Also remembering AndAlso and OrElse instead of the more intuitive (but non-short-circuiting) And and Or, and things like Is Nothing and IsNot Nothing instead of == null or != null.
None of these are necessarily problems with the language, but if you're accustomed to the relative simplicity of C#, VB code may look like a whole lot of extra stuff to you.
There were some useful articles in Visual Studio magazine back in Jan 2008.
What C# developers should know about VB
And for completeness, What VB developers should know about C#
You might also be interested in the question "what's allowed in VB that is prohibited in C# (or vice versa)"
A point which hasn't been mentioned here is that field initializers in C# run before the base constructor, while those in VB run between the base constructor and the first "real" statement of the derived-class constructor (after the base-constructor call, if any). This makes it possible for field initializers in a derived class to make use of base-class members (which may have been initialized using parameters passed to the constructor), but also means that if the base-class constructor of an object passes itself anywhere before it returns, the partially-constructed object may get used before all the field initializers have run. In C#, all of the field initializers will run before the base constructor starts execution, but none of the field initializers will be able to use the partially-constructed object.
PS--if any of the Microsoft people behind C# read this, would there be any particular difficulty adding a context-sensitive keyword for field declarations to specify whether they should be processed before or after the base constructor, or possibly have them performed by some special method that could be called from the constructor, which could be wrapped in a try-finally block (so any IDisposables thus allocated could be cleaned up) and might also be able to make use of parameters passed to the constructor?
I find this to be a handy article in highlighting the differences. I'm a vb.net programmer, and this helps me figure out c# code, so I'm sure it will work the other way!
http://www.codeproject.com/KB/dotnet/vbnet_c__difference.aspx
Just like any language (human or computer), you first learn to "translate in your head," then you eventually start "thinking" in the other language.
The quicker your team can make that leap, the better. So, do it the same way the experts tell you to learn a human language: real-world examples and immersion.
There are a few C# to VB.NET conversion utilities available online, so start by having the team write in C#, convert to VB.NET, and clean it up. (The conversion utilities vary in quality and have some limitations, especially with newer language features.)
Once they get the hang of the basic "grammar," drop them into VB.NET 100%.
I use both every day, often in different code windows at the same time, and have no problem context-switching or doing the "right thing" in each.
Apart from what Jared has already mentioned you should have no problems in doing this. The only other source of irritation is weird defaults. E.G. Did you know that VB.NET projects, by default hide the references node in solution explorer? (you have to select ShowAllFiles to see it).
Appreciating the age of this question, this one is probably quite well known now, but I'll add the one biggest gotcha I have seen in terms of writing VB.NET like a C# user:
Nothing does not mean null, it means default(T)
This means that...
Dim a As Integer = Nothing
Dim b As Integer? = Nothing
...is entirely valid, and effectively means...
int a = default(int); // 0
int? b = default(int?); // null
John M Gant's answer touches on the fact that there are dedicated keywords for comparing to Nothing-meaning-null -- Is Nothing and IsNot Nothing but, if you forget and use =, you might get an unexpected result which is hard to track down:
Dim a As Integer? = Nothing
If a = Nothing Then Console.WriteLine("a = Nothing")
If a <> Nothing Then Console.WriteLine("a <> Nothing")
If a Is Nothing Then Console.WriteLine("a Is Nothing")
If a IsNot Nothing Then Console.WriteLine("a IsNot Nothing")
'Output:
'a Is Nothing
This one is at least caught by a compiler warnings (BC42037 and BC42038), so you might want to force those warnings to be errors in your VBPROJ file.
I think C# to VB.NET won't be too painful, it's just a case of learning a new syntax. In the current versions the capabilities of both languages are fairly closely aligned.
The other way round (VB.NET to C#) could be harder because people might be used to making use of the 'My' namespace and other things put in there to make VB6 developers feel at home.
There are some subtle differences you'll have to watch out for. For example VB.Net has no concept of short circuiting an if statement (I was corrected that apparently it does). If it just a short term project, you probably won't have a problem, but different languages do have different approaches to solving the same problem. An example of this is Python programmers talking about doing things in the "pythonic" way. They talk about this concept in the book Dreaming in Code where java programmers were trying to program java using the python syntax. It leads to taking the long way around to solving a problem. Will this happen with C# and VB.Net? It is hard to say, they both use the underlying frame work, so the differences won't be huge, but it would still help to try and learn how to use VB.NET the way it was intended.
Edit: so apparently, it does has the concept of short circuiting, but it doesn't do this by default where C# does. This just further proves the point of learning how the language functions can be beneficial in the long term.
I don't think it would be too hard. VB.NET and C# are languages that are close to each other, only the syntax really differs. Of course it's going to take some time for your team to get used to the new language, but I don't think you'll run into big problems.
Oh, and VB.NET does have closures. It's missing a few other features from C# like the yield keyword, multi-statement lambdas and auto properties, but nothing very critical.
One option if you don't feel like writing the vb.net code is to write your project in C#, compile it, and use Reflector to see what the vb.net equivalent looks like. It all compiles down to MSIL anyway!
Would having a nice little feature that makes it quicker to write code like Automatic Properties fit very nicely with the mantra of VB.NET?
Something like this would work perfect:
Public Property FirstName() As String
Get
Set
End Property
UPDATE: VB.NET 10 (coming with Visual Studio 2010 and .NET 4.0) will have Automatic Properties. Here's a link that shows a little info about the feature: http://geekswithblogs.net/DarrenFieldhouse/archive/2008/12/01/new-features-in-vb.net-10-.net-4.0.aspx
In VB.NET 10 Automatic Properties will be defines like this:
Public Property CustomerID As Integer
One reason many features get delayed in VB is that the development structure is much different than in C# and additionally, that often more thought goes into details. The same seems to be true in this case, as suggested by Paul Vick's post on the matter. This is unfortunate because it means a delay in many cases (automatic properties, iterator methods, multiline lambdas, to name but a few) but on the other hand, the VB developers usually get a much more mature feature in the long run (looking at the discussion, this will be especially true for iterator methods).
So, long story short: VB 10 will (hopefully!) see automatic properties.
It also wasn't as big of a pain point in vb.net, since visual studio will automatically create 90% of the skeleton code of a property for you whereas with C# you used to have to type it all out.
If you want to do properties a little quicker, try code snippets.
Type:
Property
and just after typing the "y", press the Tab key :-).
I realize this doesn't answer the particular question, but does give you what the VB team provided...
I know this post is old so you may already know but VB is getting Auto Properties in next version of VS.
Based on response to feedback and Channel9.
C# and VB.NET don't exactly line up on new features in their first versions. Usually, by the next version C# catches up with some VB.NET features and vice versa. I kind of like literal XML from VB.NET, and hoping they add that to C#.
There's no particular reason really. It's been always been the case that even when VB.NET and C# are touted to be equally powerful (and to be fair, they are) their syntaxes and some of the structures sometimes differ. You have two different development teams working on the languages, so it's something you can expect to happen.
automatic properties are not necessary in vb
the concession one makes by using an automatic property is that you can not modify the Get and Set.
If you dont require those, just make a public data field.
VB has had automatic properties for years. They just called them something else.