Variable Declared Inside A For Loop - Make This To A Compile Time Error?

Mar 27, 2012

Today I investigated a logical bug in our software and figured out that this is related to the way VB.NET thread variables inside a loop.Let's say I have the following code:

Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5}
For Each number As Integer In numbers
Dim isEven As Boolean

[code]....

The problem is that isEven is declared but not assigned.In this specific case, it would be correct to write dim isEven as Boolean = false but I haven't done this.In VB.NET, a variable that is declared inside a for loop keeps its value for the next itaration. This is by design: [URL]but this is also dangerous pitfall for programmers.

However, until now, I haven't been aware of this problem/behaviour. Until now.Most of our code base is C# anyway, which doesn't allow the use of an uninitialized variable, so there is no problem. But we have some legacy code that is written in VB.NET that we have to support. So the best thing would be to generate a warning or even an error in this specific case.But even with Option Explicit / Option Strict this does not generate a warning / an error.Is there a way make this a compile time error or maybe a way to check this with FxCop?

View 2 Replies


ADVERTISEMENT

Compile Error: Variable Not Defined And It Points To The Second "Environment" String, The One Inside The Parenthesis

Apr 28, 2010

I have this code

Text1.Text = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)

but, when I run it, it produces an error: Compile Error: Variable not defined and it points to the second "Environment" string, the one inside the parenthesis. Is there a reference that I should be enabling?

View 3 Replies

IDE :: Linq Causing Run-time Compile Error But No Compile Error In VS2008?

Apr 20, 2009

I have a Linq-to-SQL class diagram in my web application containing the two tables in my database (held in a DBPro database project in the same solution). All was working fine yesterday. I start doing some work tonight and note that the solution compiles fine in Visual Studio, but when I run the web app I get a compilation error:

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: BC30002: Type 'FrostAlertDatabaseDataContext' is not defined.

[code]....

View 5 Replies

Declared A Class Variable Inside Sub?

Jul 26, 2010

I have a text file to read, at the first line will have a size of array, that means I cannot guess size of array, and I have to create a array in side a sub (Local Variable). Then, I want to use value of array in another sub, but I cannot use value of variable of another sub. What I have to do to make an array con be used in every sub/function in a class? Also, I've post an example file, code and error list.

[Code]...

View 1 Replies

Force A Compile-time Warning / When Using An Unassigned Local Variable?

Nov 15, 2010

Today I discovered that something I had assumed about VB.NET for many years was not true (worrying!). I assumed that a variable declared within a loop had a lifetime of the iteration it was declared in, but in fact it seems it has a lifetime of the whole procedure.[code]I had assumed an output of False, True, False, True but instead it is actually False, True, True, True..In C# the equivalent code would not compile as you would get a compile time error of Error "Use of unassigned local variable 'var1'".I realise there are many ways to fix this and that best practice would be to declare the variable outside of the loop and reset it at the beginning of every loop through.I find this behaviour so counter-intuitive to me that I would like at least a compile time warning in VB.NET when/if I do this. (I could also then set this on any projects I already have and get warning that would allow me to check that my assumptions aren't causing errors).Does anyone know how/if I can get this to generate a compile time warning in VB.NET? Am I the only one that finds this counter-intuitive?

View 1 Replies

Error - Variable Is Not Declared

Aug 11, 2011

I have a simple IF THEN ELSE block which checks for the presence of a querystring and then checks if it is set. The idea is that if no querystring, the form is empty and people can enter a new form. If there is a querystring and it isn't blank, a db query for the form data occurs, fields are populated and a user can update the form.

so here is my code block.

Dim strQueryStingCheck As String
If Not (Request.QueryString("pid") Is Nothing) Then ' is there a querystring?
If Request.QueryString("pid").ToString <> "" Then ' does it have a value?

[code]....

I am getting the "Variable is not declared; it may be inaccessible due to its protection level" for strQueryStringCheck ONLY on the Else code block - that is when I set strQueryStringCheck to "e". I can't figure it out.I've looked at other posts, particularly this one. and it was helpful. I can make the error go away, but I want to understand why I am getting it in the first place. I declared it within the subroutine. And if I was doing something wrong, shouldn't it throw an error on BOTH blocks of the IF THEN ELSE block? It doesn't when I set strQueryStringCheck to "u". Why only in the ELSE block?

View 2 Replies

Make .net Run In Compile Time?

Oct 12, 2011

Basically I am creating a program and would like it to run in compile time as opposed to the standard run time?

View 1 Replies

Dimension Of Variable Inside For Loop

Mar 30, 2010

Using VB.NET .NetFramwork 3.5. This fails and strikes me as odd. Is this correct behavior:
Public Sub TestForEach()
For index As Integer = 1 To 10
Dim z As Integer
Assert.AreEqual(0, z)
z = index
Next
End Sub
I would expect z to always equal 0 as I thought the dim-ing of an integer would set the value to 0. If you run this. It fails at the second loop. For some reason z retains it's value of 1. I know I can manually initialize z to = 0, but I wanted to know if this is a bug or expected behavior.

View 9 Replies

Variable Declaration Inside A Loop?

Aug 26, 2011

For i As Integer = 1 To 10
Dim j As Integer = 10
Next

now my question is, Is memory allocated to j every time its executed inside for loop? or only value of 10 is assigned on subsequent iterations?

View 2 Replies

LINQ Variable Not Declared Error

May 24, 2012

I am trying to run this line of code: Dim OrderedFiles() As String = Directory.GetFiles(FilePath).OrderBy(x >= x.CreationTime)

I get an error on x saying x is not declared. I have my project set to Option Strict Off and Option Infer On. If I turn ON Option Strict then I get thousands of errors from the project(it is inherited) and I don't have the time to fix all of them, but x no longer gives me an error. I have googled until I want to throw my computer out the window.

I was hoping for a more elegant solution but here is what I came up with to solve this particular problem.

[Code]...

It is not particularly elegant but it does the job. I was hoping for a one liner LINQ solution and I just don't have the background in LINQ to know how to do the job, time to go buy a book.

View 2 Replies

How To Compile Time Error

Aug 27, 2010

I am having a problem while compiling one of my projects in vb.net. I have a solution consisting of multiple project,one of which is the exe. Now when i am trying to compile that project i get an error which states

View 1 Replies

Error - Variable Is Not Declared, It May Be Inaccessible Due To Its Protection Level

Jul 11, 2011

Today I decided to come up with a program that would be useful for me in VB.net (I have never coded in VB.net before). All is going fine up till this point but I have hit a snag with the error mentioned above. The problem is with the windowssevenexistsonsource boolean under the get get of profiles comment. I will also take any code criticism well as I would like to get out of bad practices before I start! (the sub does end but I have not included that code)

Code:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'Check that the entries required are not empty
If String.IsNullOrEmpty(sourceipaddress.Text) Or String.IsNullOrEmpty(destinationipaddress.Text) Then

[code]....

View 1 Replies

Make Property Required / Catch At Compile Time?

Sep 2, 2011

[code] i get an app error when running the app, because i didn't set the ID.I was wondering if there's a way to make sure the programmer assigns all properties in the class,and fail at COMPILE TIME rather than have to catch the error at runtime...

View 2 Replies

VS 2008 Make Some Kind Of Loop Inside A Timer To Make Them Change?

Dec 14, 2010

Basically I have 10 .png images.They contain a walk cycle I need to make some kind of loop inside a timer to make them change.

View 2 Replies

Make Loop In Program And Calculate Time Taken To Complete Loop?

Nov 23, 2011

I am constructing a program, i am new to Visual Basic, but i have past programming experience. I was wondering if anyone knew how to form a loop that could...lets say calculate the answer when two numbers are added together,and it would repeat this thousands of times, etc. And if there is a way, would it be possible to calculate the time taken to complete this loop.

View 5 Replies

Error: A Local Variable Named 'arow' Cannot Be Declared In This Scope Because It Would Give A Different Meaning To 'arrow'

May 24, 2010

This webservice is almost converted form VB to C#, except I get this error shown below on the DataRow arow object when I use it in the foreach statement below to populate the Results Class with a DataSet Object...

Error: A local variable named 'arow' cannot be declared in this scope because it would give a different meaning to 'arrow', which is already used in a 'parent or current' scope to denote something else

using System;
using System.Web;
using System.Collections;

[code]....

View 1 Replies

VS 2010 For Loop Inside Backgroundworker Gives Thread Error?

Jul 5, 2011

I have a backgroundworker that is downloading data from different webpages and process them to a datagridview.I get the Cross-thread operation not valid error on the first For loop.

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
dim i as integer
tot = (numPostnrTo.Value - numPostnrFrom.Value) / 10

[code]....

View 12 Replies

VS 2005 Error When Loop Exceed To The Files Inside Folder

Apr 22, 2009

i got error when

1.) Looping exceed the images files found in the folder

2.) When program get not valid file

3.) when changing the source of images

the error says "Parameter is not valid"

here is the code below....

Function getnewImage()
Try
If (Me.Ping.Send("pc1", 6000).Status) = Net.NetworkInformation.IPStatus.Success Then

[Code].....

View 6 Replies

Declared Variable Appearing Not Declared?

Feb 24, 2011

The following is a screenshot of the problem: What can I do?

View 3 Replies

Error - Variable Not Declared For "OptionGroupsOption"

Mar 15, 2009

I am getting this variable not declared for "OptionGroupsOption". You can see that in the first block I either Dim it as a new radiobutton or a new checkbox. So why is it saying its not declared?

''
'If the optiongroup is required add the options as a radio
'Else add them as checkboxes.
''
If CInt(dr.Item("intRequired")) = 1 Then

[code]....

View 3 Replies

Create A (in Excel ) Variable Table (database) Inside A Function Which Could Be Called For Filling And Reading Through "for To Next" Loop Module?

Feb 4, 2012

i just got 1 question how do u create a (in excel ) variable table (database) inside a function which could be called for filling and reading through "for to next" loop module

View 2 Replies

.net : "Statement Lambdas Cannot Be Converted To Expression Trees" Compile Time Error

Feb 18, 2011

Why can I do the following :

Dim qNodes As IQueryable(Of XmlNode) = xDoc.ChildNodes.AsQueryable()
Dim test = qNodes.Where(Function(node) True)

although the following gives the error I stated in the title :

Dim qNodes As IQueryable(Of XmlNode) = xDoc.ChildNodes.AsQueryable()
Dim test = qNodes.Where(Function(node)
Return True
End Function)

View 3 Replies

VS 2010 Compiler Creates New Variable Automatically When Use If Statement Without Strictly Declared Variable?

Jan 10, 2011

Say that i have the following code that parse about 20k records from the DB.

Code #1

vb.net While reader.Read()
list.Add(If(Integer.TryParse(reader(0).ToString, 0), Integer.Parse(reader(0).ToString), 0))
End While

And then another code which does the very same thing but it seems to be a little cleaner.

Code #2

vb.net While reader.Read()
Dim storeowner As Integer = 0
Integer.TryParse(reader(0).ToString, storeowner)
list.Add(storeowner)
End While

This is what i am confused about; does the compiler creates a new variable automatically when i use the if statement without strictly declared variable? What approach is better in sense of performance?

View 2 Replies

Variable Naming Conventions To Illustrate Variable Type And Where Variables Are Declared

Aug 24, 2009

I am looking for a good resource on variable naming conventions to illustrate variable type and where variables are declared. So I will have public variables, Private variables, private or local variables. I also may want to declare variables with the same name in different class code (i.e. in the code behind different forms). I am assuming good coding would dicatate a prefix for declaration location.

View 4 Replies

Run Time Error During Long Loop?

Dec 7, 2011

I wrote a program which loops through a very long CSV file (50 meg) and parses the data as it goes.Sometimes, the program aborts and I get the following message:The CLR has been unable to transition from COM context 0x37a090 to COM context 0x37a200 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.

I know its going to take a while. There are several hundred thousand lines of text in the file that this program is reading. I am not sure exacly waht the message means, but my program seems to work fine other than the message. odd thing is sometimes the message doesnt always pop up..

View 1 Replies

Protected Error In Compile Time, When No Protected Class Is Used?

Nov 10, 2011

Dim box As MultiTextBox = New MultiTextBox

Dim i As Integer
for i = 1 to 3 Step 1
lengthWidthHeight = MultiTextBox.GetItemValues()
Next i

This excerpt of code is using the NXOpen API. In the NXOpen API, the MultiTextBox class is public. However, when I compile the code I get the message:

'NXOpen.UIStyler.MultiTextBox.Protected Sub New(ptr As System.IntPtr)' is not accessible >in this context because it is 'Protected'

My question is, how am I getting an error about protected scope? Could it also be that the API documentation is incorrect?

View 2 Replies

Multiple Referers One At A Time Loop Error ?

Jan 21, 2012

Here is the code:

CODE:

What I want to do is I want to post to different referers one at a time and of course the links will be provided by a richtextbox(i.e. richtextbox1.lines(i) ). I will use only password(which will be chosen by the user from a combobox(combobox1.text)) because the username is harcoded. This is what so far ive come up with but it always gives me the result of the first line(or referer) from richtextbox1. I think there might be a problem with my "FOR" code.

CODE:

View 3 Replies

Adding Time Error When Passing Value To Variable?

May 24, 2012

dim pvalue as datetime pvalue = (Date.Now.AddHours(3), Date.Now.AddMinutes(2))

above code getting error of ')' expected

No Error MessageBox.show(Date.Now.AddHours(3), Date.Now.AddMinutes(2))

View 4 Replies

VS 2008 Error "WithEvents Variable 'Move' Conflicts With Event 'Move' In The Base Class 'Control' And Should Be Declared Shadows"

Sep 3, 2010

What does this error mean? I havent modified anything in the designer code, but its giving me an error? WithEvents variable 'Move' conflicts with event 'Move' in the base class 'Control' and should be declared 'Shadows'. The error relates to Friend WithEvents Move As System.Windows.Forms.DataGridViewCheckBoxColumn

View 1 Replies

Possible To Return A Value That Is Not Declared Any Where Inside A Function?

Aug 15, 2009

Module Exercise
Private Function SetMembershipLevel()
Dim MemberAge

[code].....

View 6 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved