How to make AddRange type-safe - vb.net

I have this dummy code in vb.net
Sub dummy()
Dim a = New List(Of XDocument)
Dim b = New List(Of Net.Mail.MailAddress)
b.AddRange(a)
End Sub
Obviously, this cant ever work. but the compiler ignores it.
How can I force VS to flag this at compile time?
Thanks

The compiler only allows that because you have Option Strict Off. You should basically ALWAYS have Option Strict On at the project level and only set it Off at the file level on the very rare occasions that you actually need to use late-binding. Even then, you should only set it Off in those specific files that actually require it and you should use partial classes to keep the code in those files to an absolute minimum.
Set Option Strict On in your project properties and the compiler will correctly flag that as bad code and there's every chance that you'll see other problem areas highlighted too. You should also set it On in the VS options, so that it will be On by default for all future projects.

Related

Remove namespace or classname from VB.Net when used in VBA [duplicate]

Base Reference: Ten Code Conversions for VBA, Visual Basic .NET, and C#
Note: I have already created and imported a *.dll, this question is about aliases.
Let's say the programmatic name of a Test class is TestNameSpace.Test
[ProgId("TestNamespace.Test")]
public class Test ...
Now, say a C# solution has been sealed and compiled into a *.dll and I'm referencing it in a Excel's VBE. Note: at this point I cannot modify the programmatic name as if the *.dll wasn't written by me.
This is in VBA : Instead of declaring a variable like this:
Dim myTest As TestNameSpace.Test
Set myTest = new TestNameSpace.Test
I'd prefer to call it (still in VBE)
Dim myTest As Test
Set myText = new Test
In C# you would normally say
using newNameForTest = TestNamespace.Test;
newNameForTest myTest = new NewNameForTest;
Note: Assume there are no namespace conflicts in the VBA project
Question: is there an equivalent call in VBA to C# using or VB.NET imports aliases?
Interesting question (constantly using them but never thought about their exact meaning). The definition of the Imports statement (same for using) is pretty clear: its only function is shortening the references by removing the corresponding namespaces. Thus, the first question to ask is: has VBA such a thing (namespaces) at all? And the answer is no, as you can read from multiple sources; examples: Link 1 Link 2
In summary, after not having found a single reference to any VBA statement doing something similar to Imports/using and having confirmed that VBA does not consider the "structure" justifying their use (namespaces), I think that I am in a position to say: no, there is not such a thing in VBA.
Additionally you should bear in mind that it wouldn't have any real applicability. For example: when converting a VB.NET code where Imports might be used, like:
Imports Microsoft.Office.Interop.Word
...
Dim wdApp As Application
the code would be changed completely, such that the resulting string will not be so long:
Dim wdApp As Word.Application ' Prefacing the library's display name.
I think that this is a good graphical reason explaining why VBA does not need to have this kind of things: VB.NET accounts for a wide variety of realities which have to be properly classified (namespaces); VBA accounts for a much smaller number of situations and thus can afford to not perform a so systematic, long-named classification.
-------------------------- CLARIFICATION
Imports/using is a mere name shortening, that is, instead of writing whatever.whatever2.whatever3 every time you use an object of the given namespace in a Module/ Class, you add an Imports/using statement at the start which, basically, means: "for all the members of the namespace X, just forget about all the heading bla, bla".
I am not saying that you cannot emulate this kind of behaviour; just highlighting that having an in-built functionality to short names makes sense in VB.NET, where the names can become really long, but not so much in VBA.
The answer is no: there is a built-in VBE feature that recognizes the references added to a project and creates aliases at run-time(VBE's runtime) if there are no name collisions
In case of name conflicts in your registry all . dots will be replaces with _ underscores.
» ProgId's (Programmatic Identifiers)
In COM, it is only used in late-binding. It's how you make a call to create a new object
Dim myObj = CreateObject("TestNamespace.Test")
» EarlyBinding and LateBinding
In early binding you specify the type of object you are creating by using the new keyword. The name of you object should pop up with the VBA's intellisense. It has nothing to do with the ProgId. To retrieve the actual namespace used for your object type - open Object Explorer F2 and locate it there
This article explain where the names come from in Early Binding Section
use the same link for When to use late binding
for MSDN Programmatic Identifiers section please see this

VBA User form with ThemeColorScheme and late binding

I'd like to run a user form with status bar.
I show my form with code bolow.
How should I declare variables and assigning new values to those variables?
Very important: I have to use late binding in my project.
Sub RunMyUserForm()
With MyUserForm
.LabelProgress.Width = 0
.TextBox1 = 1
'to make the progress bar color match the workbook's current theme:
.LabelProgress.BackColor = ActiveWorkbook.Theme.ThemeColorScheme.Colors(msoThemeAccent1)
.Show vbModeless
End With
End Sub
Thank you in advance for your help!
Updated information:
When I try to run my macro with "Option Explicit", it doesn't work (Compile error: Variable not defined - part of code msoThemeAccent1 is marked as yellow color). That's why I asked for help in defining the variables.
When I try to run my macro without "Option Explicit", it dosen't work (Err.Description: "Value is out of range", Err.Number: -2147024809)
When I try to run my macro with early binding (reference to "MS Office Object Library" via Tools/References in VBE) everything works perfect with (and without) "Option Explicit".
Your compiler is seeing msoThemeAccent1 as a variable, and it is undeclared. This is why your code won't run with Option Explicit and also why your code raises an error when you disable Option Explicit. .Colors is a 1-based collection (?) so when you call:
ActiveWorkbook.Theme.ThemeColorScheme.Colors(msoThemeAccent1)
It is compiling to:
ActiveWorkbook.Theme.ThemeColorScheme.Colors(0)
Which raises an expected, albeit cryptic error.
I used some code to check the value of this constant, but in hindsight I should have just referred to the documentation:
http://office.microsoft.com/en-us/excel-help/HV080559557.aspx
This should fix it for you
ActiveWorkbook.Theme.ThemeColorScheme.Colors(5)
Alternatively, if you need to rely on this value in several places in your code, you could declare a variable (public or private, scope depends on what you need it for).
Public Const myAccentColor1 as Long = 5
And then, in your code you could:
ActiveWorkbook.Theme.ThemeColorScheme.Colors(myAccentColor1)
Revised
I understand now, without reference to MS Office Object Library this makes sense. This is one of the few libraries that I maintain a reference to in my XLSB file, so my confusion was a result of the fact that I thought I was using an appropriate late-binding, but I was really using early-binding.

Is it possible to use Variables without DIM in VB.NET?

Is it in VB.NET possible to use variables without the need of use DIM?
now I have to use the variables like this:
dim a = 100
dim b = 50
dim c = a + b
I want to be able to use vars in this way:
a=100
b=50
c=a+b 'c contains 150
I think in VB6 and older VB this was possible, but I am not sure.
As far as what #Konrad said, he is correct. The answer, buried in all his caveat emptors, is the answer of "yes", you can absolutely do this in VB.NET by declaring Option Explicit Off. That said, when you do a=1, the variable a is NOT an Integer - it is an Object type. So, you can't then do c = a + b without compiler errors. You'll need to also declare Option Strict Off. And at that point, you throw away all the benefits of a compiler. Don't do it.
As an alternative, with Option Infer On, Dim behaves the same as C#'s var keyword and gives you a lot of advantages if you're trying to save on typing.
You have a fundamental misunderstanding of how VB is supposed to work. The Dim statements are there to help you. Your wish to elide them is misplaced.
The compiler enforces variable declaration so that it can warn you when you have accidentally misspelt a variable name, thus inadvertently creating a new variable, and is required to enforce type safety. Without variable declaration, VB code becomes an unreadable, unmaintainable mess.
Incidentally, the same was true in VB6, and you should have used Option Explicit in VB6 to make the compiler force you to use them properly. This option still exists in VB.NET but switching it off has no advantage, and a whole lot of disadvantages so don’t do it – instead, learn to appreciate explicit variable declarations, and all the help that the compiler is giving you through them.

VB.Net variable declaration

I notice that both of these compile without any compiler warnings or errors, even with Option Strict and Option Explicit both turned on:
Dim x As Exception = New Exception("this is a test")
Dim y = New Exception("this is another test")
My question is, is it more proper to use the first way (see variable x) or the second way (see variable y)? My guess is that VB doesn't need the As clause since the variable is being initialized in place, so the compiler can infer the type.
I tend to like the first way as it just "feels" right and is more consistent with other languages like C#, just wondered if there was some good reason for one way over the other. I guess it's really personal choice.
Behold the wonder of Option Infer On, the compiler figures out the type of "y" automatically. Available since VS2008. You'll get the error you are looking for by turning it off:
Option Strict On
Option Infer Off
Module Module1
Sub Main()
Dim x As Exception = New Exception("this is a test")
Dim y = New Exception("this is another test") ''# error BC30209
Dim z As New Exception("this is a third test")
End Sub
End Module
I'd do Dim x As New Exception("this is a test"). Best of both worlds, no infering but you still only have to type Exception once :)
Option Infer is what controls this compiler feature. Both are equivalent--this is similar to the (moot) C# debate about whether to use the var keyword. My two-cents is to leave it up to the individual developer, however many people will likely say to establish a convention and follow it.
I think the first one (with the variable type declaration) would be the safest to use. If the program is small, it won't really make a difference, but for larger program's, there could be a noticeable compiler lag. So (in my opinion) declaring the type is the best thing to do.

.NET Default Properties Error [duplicate]

This question already has answers here:
Why can I access an item in KeyCollection/ValueCollection by index even if it doesn't implement IList(Of Key)?
(2 answers)
Closed 6 years ago.
I have a VB.NET project where I am able to iterate through the keys and values collections of a dictionary object using an index:
MyDictionary.Keys(idx)
MyDictionary.Values(idx)
When this code is taken from the test project and placed into the real project I get the following error:
'System.Collections.Generic.Dictionary(Of Double, String).KeyCollection' cannot be indexed because it has no default property.
and
'System.Collections.Generic.Dictionary(Of Double, String).ValueCollection' cannot be indexed because it has no default property.
This is using VB.NET and VS 2008. I don't know what the difference would be from one project to the next that would cause this error. The test is a console application and the program is a winforms app.
What conditions would cause the default property of these collections to change?
Edit - Thank you for all of the answers that tell me how to loop through a dictionary. Those, answers, however, do not answer my question of why I can use an index in one project and not the other. Should I not be able to copy and paste the code from one .net project to another and have it work the same? And, no, option strict, is not the cause of the problem.
Edit - Attempt to reproduce what I'm seeing:
Create a new VB.NET Console Application using VS 2008
Copy and paste the following code into the module:
Imports System.Collections
Imports System.Collections.Generic
Module Module1
Public dtf As Dictionary(Of Double, String)
Public Sub BuildDictionary()
dtf = New Dictionary(Of Double, String)
dtf.Add(1.0, "1")
dtf.Add(0.0, "0")
End Sub
Public Sub Search()
For idx As Integer = 0 To dtf.Keys.Count - 1
If dtf.Keys(idx) = 0 Then
Exit Sub
End If
Next
End Sub
Sub Main()
End Sub
End Module
In the line in sub search that says "dtf.Keys(idx) = 0" place your cursor after the right parenthesis and backspace you should get a tooltip that says, "<Extension> ElementAtOrDefault(index as Integer) as Double - index: the zero based element of the index to retrieve.
I am not getting that in my other project. Even though it seem I have the same references and settings.
KeyCollection does not implement indexers like that, you must enumerate through the MyDictionary.Keys.
c#
foreach(double key in MyDictionary.Keys)
Console.Write( MyDictionary[ key ] )
vb
For Each key As Double in MyDictionary.Keys
Console.Write( MyDictionary( key )
Next key
Looping with a for(;i++;) wouldn't be the correct way of going through your hashtable (dictionary) since it is not an array it really has no concept of an array index (array[index])
I bet your real project had OPTION STRICT ON, as all projects should, and that your test project had it OFF. That's why you didn't get a compiler error in your test project.
EDIT: the poster says he has OPTION STRICT ON for both projects. That makes this more interesting.
I still think the most likely reason for this difference is that in one case, the compiler compiled the code and saw the error; but in the other case, the compiler didn't comile the code. Is this the same version of Visual Studio on the same machine at the same time? Same .NET Framework version in both cases?
Are these both the same type of project, for instance, are they both console applications? I ask because ASP.NET Web Site "projects" usually don't attempt to compile code until the code is called. If your test project were such a "project", and if you didn't actualy test the code (that is, if you didn't actually step into this code and see it work), then you might have assumed that the fact you could press F5 meant that all the code was compiled, when it wasn't.
My next thoughts would be to see if MyDictionary was really of the same type in both cases.
Beyond that, if you really need to know why this happened, I'd make a copy of the "real" project, and start changing it to be more and more like the test project. This would probably be a matter of mass deletions at first. I'd keep changing it either until the problem was found, or until the two were identical.
EDIT 2: The default console project imports the System.Linq namespace (see the "References" tab in project properties). This import brings the ElementAtOrDefault extension method into scope. This extension method extends IEnumerable(Of T); in your case IEnumerable(Of Double), which is what the Keys property implements.
What surprises me about this is that VB.NET is automatically applying this extension method. In C#, the method would need to be explicitly named.
If you remove the Import of System.Linq, you'll find that your test application gets the same error as the production application.
The Keys and Values property of Dictionary(Of TKey,TValue) do not have an indexer property. They are implementations of ICollection vs. IList and hence don't support accesses by Index. If you want to iterate through a Dictionary, the best way is a For Each loop.
For Each pair in MyDictionary
Dim key = pair.Key
Dim value = pair.Value
Next
EDIT
Have you checked to make sure that System.Core is referenced in both projects and that you have a project level imports for System.Linq? That's the only thing I can think of that would produce a difference in ElementAtOrDefault which is a method inside of system.Core.
I'm still a bit baffled why that method would be bound to for a simple indexer. Going to look into that