Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why C# is not allowing non-member functions like C++
Instead of writing StaticClass.Function() I'd like to simply write Function(). There will be many functions and all should be accessible from different (and unrelated) classes and files. How do I put these functions in a specific namespace? Simply declaring it there will give me a compile error
error CS1518: Expected class, delegate, enum, interface, or struct
I know other .NET languages can do it. Is there a compile option i may use? Perhaps even undocumented?
C# does not allow for free functons. Each function must reside in a type. This is just the way it works, it's not a matter of technical possibility, it was a design decision.
You may be interested in this article.
On a side note, ever notice how Intellisense works much, much better when writing C# than C++? This is one of those things that help (not the only one, but one).
EDIT: Funny, in reading that linked article I noticed that this is a dup...
C# does not allow this, by design.
However, if your goal is merely to reduce typing, you have a couple of options.
First, you can use the using Directive to simplify this. By adding this:
using SC = YourNamespace.StaticClass;
You can shorten the calls within that specific document to:
SC.Function();
Another option which is occasionally appropriate would be to use an
Extension method. This can eliminate the need to specify the type, as the function appears to be a member function of the first argument. Of course, this wouldn't work for the supplied example (as it requires a parameter), but is potentially another option to reduce the amount of typing and searching, depending on the specific use case.
C# is a purely object-oriented which means you cannot have functions or declarations outside of a class. You'll have to use static to achieve what you want.
I know this has been discussed many times, but I am not sure I really understand why Java and C# designers chose to omit this feature from these languages. I am not interested in how I can make workarounds (using interfaces, cloning, or any other alternative), but rather in the rationale behind the decision.
From a language design perspective, why has this feature been declined?
P.S: I'm using words such as "omitted", which some people may find inadequate, as C# was designed in an additive (rather than subtractive) approach. However, I am using such words because the feature existed in C++ before these languages were designed, so it is omitted in the sense of being removed from a programmer's toolbox.
In this interview, Anders said:
Anders Hejlsberg: Yes. With respect to
const, it's interesting, because we
hear that complaint all the time too:
"Why don't you have const?" Implicit
in the question is, "Why don't you
have const that is enforced by the
runtime?" That's really what people
are asking, although they don't come
out and say it that way.
The reason that const works in C++ is
because you can cast it away. If you
couldn't cast it away, then your world
would suck. If you declare a method
that takes a const Bla, you could pass
it a non-const Bla. But if it's the
other way around you can't. If you
declare a method that takes a
non-const Bla, you can't pass it a
const Bla. So now you're stuck. So you
gradually need a const version of
everything that isn't const, and you
end up with a shadow world. In C++ you
get away with it, because as with
anything in C++ it is purely optional
whether you want this check or not.
You can just whack the constness away
if you don't like it.
I guess primarily because:
it can't properly be enforced, even in C++ (you can cast it)
a single const at the bottom can force a whole chain of const in the call tree
Both can be problematic. But especially the first: if it can't be guaranteed, what use is it? Better options might be:
immutable types (either full immutability, or popsicle immutability)
As to why they did it those involved have said so:
http://blogs.msdn.com/ericgu/archive/2004/04/22/118238.aspx
http://blogs.msdn.com/slippman/archive/2004/01/22/61712.aspx
also mentioned by Raymond Chen
http://blogs.msdn.com/oldnewthing/archive/2004/04/27/121049.aspx
In a multi language system this would have been very complex.
As for Java, how would you have such a property behave? There are already techniques for making objects immutable, which is arguably a better way to achieve this with additional benefits. In fact you can emulate const behaviour by declaring a superclass/superinterface that implements only the methods that don't change state, and then having a subclass/subinterface that implements the mutating methods. By upcasting your mutable class to an instance of class with no write methods, other bits of code cannot modify the object without specifically casting it back to the mutable version (which is equivalent to casting away const).
Even if you don't want the object to be strictly immutable, if you really wanted (which I wouldn't recommend) you could put some kind of 'lock' mode on it so that it could only be mutated when unlocked. Have the lock/unlock methods be private, or protected as appropriate, and you get some level of access control there. Alternatively, if you don't intend for the method taking it as a parameter to modify it at all, pass in a copy of that object, or if copying the entire object is too heavyweight then some other lightweight data object that contains just the necessary information. You could even use dynamic proxies to create a proxy to your object that turn any calls to mutation methods into no-ops.
Basically there are already a whole bunch of ways to prevent a class being mutated, which let you choose one that fits most appropriately into your situation (hint: choose pure immutability wherever possible as it makes the object trivially threadsafe and easier to reason with in general). There are no obvious semantics for how const could be implemented that would be an improvement on these techniques, it would be another thing to learn that would either lack flexibility, or be so flexible as to be useless.
That is, unless I've missed something, which is entirely possible. :-)
Java have its own version of const; final. Joshua Bloch describes in his Effective Java
how you effectively use the final keyword. (btw, const is a reserved keyword in Java, for future discrepancies)
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!
I know that in C# 3.0 you can do some functional programming magic with Linq and lambda expression and all that stuff. However, is it really possible to go completely "pure" functional in C#? By "pure" I mean having methods that are pure (always gives the same output for the same input) and completely free of side-effects. How do we get around the fact that we do not even have immutable integer type in C#?
If you want to program in a pure functional way, there is nothing stopping you.
On the other hand, if you have some program, there is no magic flag you can flip to force the program to behave in a pure functional way.
For ints (immutable)
If you use an int as a parameter, it is passed by value. Any changes are not propogated to the caller.
If you use an int declared in one method's scope in a closure within the method, than that int variable is shared. In this case, one must either pledge not to modify the int (programmer enforced), or simply not use an int in this way.
And if you truly need an immutable int, have you seen the readonly keyword?
Have you looked into F#? It seems much more along the lines of what you are talking about. C# just really isn't designed with functional programming in mind, and therefore won't really give you any of the benefits that are normally associated with a functional language.
Unfortunately no - C# is not a pure functional language and it does not intend to be. What has happened is that the C# team has seen that there are benefits to adding certain functionally-styled constructs and syntax to the language.
Functional purity is better found in other places (Lisp derivatives like Common Lisp and Scheme are good places to start).
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