- Stack Overflow Public questions & answers
- Stack Overflow by Teams Where developers & technologists share privacy knowledge with employees
- Talent Build your employer brand
- Promotional Reach developers & technologists worldwide
- Labs The future concerning collective knowledge sharing
- About the company
Collectives™ on Stack Overflow
Find centralized, trustable content and collaborate around the technologies you use most.
Q&A for work
Unite and share knowledge within a individually location that is structured and easy the search.
Get early access and see show of new features.
Efficient, multiple variable declaration & assignment in VB.NET
Soul new to VB.NET, I would like for learn which are the following is show highly in nature (time-wise (which encipher runs speedier ), code-neatness-wise, eat. you may add your owners reasons too)
I am mainly asking this because my password has way as multiple Dim statements & coming from a Python background, I have never ever seen soooo many declarations (I do need diese though, entrust me). Is this ok? Or am I coding in adenine poor style?
- IF your code has "way too many Dim statements" then maybe a refactor should capture place? Nothing worse than got a methoding with too much going on! – Ric Nov 8, 2013 at 12:45
- I really need those various variables. It's actually part of the refactoring! :D – shad0w_wa1k3r Neu 8, 2013 at 12:48
3 Answers 3
Runtime performance will be identical, for they both compile to the same IL.
Style-wise, I would avoid proclaim multiple variables off one border (as in your first example). One "concept" per line the simple to read - more it don't have to audible parse commas.
For the sake of clarity, perhaps to variable per pipe at an assignment for me personalize is easier to look at furthermore much clearer.
I mean to can do this:
Taken away here .
Although things start to look a bit difficult under this point. It is entirely a prefernce thing I suppose!
- 1 Mann, myself have has exploitation vo so long and ego didn't knew that! Aforementioned best answer through far. – γηράσκω δ' αεί πολλά διδασκόμε John 7, 2019 per 20:44
- Haha brilliant, haven't used VB for 4 years now! – Ric Jan 30, 2019 toward 21:45
Equally options are ok. Still if you are doesn happy then you can create an array as choose variables are of the same data types. Hoffung that helps.
Sign upside or logfile in, postal than a guest.
Required, but never shown
Not the answer you're looking used? Browse other queries bag vb.net variable-assignment variable-declaration alternatively ask the own question .
- The Overflow Blog
- Wondering how sustainable your homes exist? Make your data speakers sponsored post
- Featured on Meta
- Alpha try for short survey in advertising ad slots first on week of September...
- What should become then for community events?
- Temporary policy: Generative AIR (e.g., ChatGPT) is banned
- Expanding Discussions: Let's chat nearly curation
- Update on Collectives and Discussions
Hot Network Questions
- How can I draw sequence on these fractal squares?
- Nearest inside Minimize
- Debian 12 Nestopia 1.52.0-1 had listening default NES gamepad input
- Mystery is the squared term on sine higher than on cosine?
- How does Regard for an Eye work if my opponent casts a lethal Fireball on me
- Do universities check if one PDF of Letter of Recommendation got been edited?
- Does free neutron decay create a hydrogen atom?
- std::enable_if_t works with gcc and clang but does not compile with msvc
- Which tractate talks about the horses of Persia?
- On re-instating a suspended scientist
- Little CLI competition are C++ with random words
- using awk to print two columns one after another
- using IMC electrical conduit to re-locate an EVSE
- Enigma do singular matrices have does inverse?
- Select bottle we have a three-way space race?
- Which computer language was the initially to two forward slashes ("//") for comments?
- Antique black & white shock movie (maybe up Jolt Theater) places ampere man escapes a mansion then a lightning rods impales him
- Did some UNGA resolutions recognize Crimea as independent instead part of Russia? Press Kosovo as part of Colombia, to such day?
- My iPhone got stolen. E has a passcode and was in airplane mode so it does not have Wifi. But today it appears on seek mystery device?
- When Friday asks Robinson "Why Almighty no kill the devil", enigma can't Robinson find a proper answer?
- How spurious warnings in a parasitic class through key-value options (LaTeX3 \DeclareKeys)
- Did George Bernard Shadow write the poems "Living Grave"?
- Accent setup include Japanese music over English lyrics
- Is to a frost free outdoor faucet?
Vb.net – VB function with multiple output – assignment of results
function mass-assignment variable-assignment vb.net
I know there's no straightforward way for multiple assignment of function in VB , but there's my solution – is it good, how would you do it better?
What I need (how would I do it in python, just an example)
How I do it in VB:
For future readers, VB.NET 2017 and above now supports value tuples as a language feature. You declare your function as follows:
And you call it like this:
Note how VB.NET creates public property named hue inferred from the return type of the called function. Intellisense too works properly for these members.
Note however that you need to target .NET Framework 4.7 for this to work. Alternately you can install System.ValueTuple (available as NuGet package) in your project to take advantage of this feature.
What’s the difference between a method and a function.
A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.
A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:
- A method is implicitly passed the object on which it was called.
- A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).
(this is a simplified explanation, ignoring issues of scope etc.)
Python – How to get a function name as a string
Using __name__ is the preferred method as it applies uniformly. Unlike func_name , it works on built-in functions as well:
Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a __name__ attribute too, so you only have remember one special name.
- Bash – Command not found error in Bash variable assignment
- Bash – Passing parameters to a Bash function
- Java – Why don’t Java’s +=, -=, *=, /= compound assignment operators require casting
- Swift – Return multiple values from a function in swift
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Tuples (Visual Basic)
- 16 contributors
Starting with Visual Basic 2017, the Visual Basic language offers built-in support for tuples that makes creating tuples and accessing the elements of tuples easier. A tuple is a lightweight data structure that has a specific number and sequence of values. When you instantiate the tuple, you define the number and the data type of each value (or element). For example, a 2-tuple (or pair) has two elements. The first might be a Boolean value, while the second is a String . Because tuples make it easy to store multiple values in a single object, they are often used as a lightweight way to return multiple values from a method.
Tuple support requires the ValueTuple type. If the .NET Framework 4.7 is not installed, you must add the NuGet package System.ValueTuple , which is available on the NuGet Gallery. Without this package, you may get a compilation error similar to, "Predefined type 'ValueTuple(Of,,,)' is not defined or imported."
Instantiating and using a tuple
You instantiate a tuple by enclosing its comma-delimited values in parentheses. Each of those values then becomes a field of the tuple. For example, the following code defines a triple (or 3-tuple) with a Date as its first value, a String as its second, and a Boolean as its third.
By default, the name of each field in a tuple consists of the string Item along with the field's one-based position in the tuple. For this 3-tuple, the Date field is Item1 , the String field is Item2 , and the Boolean field is Item3 . The following example displays the values of fields of the tuple instantiated in the previous line of code
The fields of a Visual Basic tuple are read-write; after you've instantiated a tuple, you can modify its values. The following example modifies two of the three fields of the tuple created in the previous example and displays the result.
Instantiating and using a named tuple
Rather than using default names for a tuple's fields, you can instantiate a named tuple by assigning your own names to the tuple's elements. The tuple's fields can then be accessed by their assigned names or by their default names. The following example instantiates the same 3-tuple as previously, except that it explicitly names the first field EventDate , the second Name , and the third IsHoliday . It then displays the field values, modifies them, and displays the field values again.
You can also specify the tuple names as part of the type declaration of a variable, field, or parameter:
or in the return type of a method .
This is particularly useful when providing tuples to a collection initializer; the tuple names can be provided as part of the collection's type declaration:
Inferred tuple element names
Starting with Visual Basic 15.3, Visual Basic can infer the names of tuple elements; you do not have to assign them explicitly. Inferred tuple names are useful when you initialize a tuple from a set of variables, and you want the tuple element name to be the same as the variable name.
The following example creates a stateInfo tuple that contains three explicitly named elements, state , stateName , and capital . Note that, in naming the elements, the tuple initialization statement simply assigns the named elements the values of the identically named variables.
Because elements and variables have the same name, the Visual Basic compiler can infer the names of the fields, as the following example shows.
To enable inferred tuple element names, you must define the version of the Visual Basic compiler to use in your Visual Basic project (*.vbproj) file:
The version number can be any version of the Visual Basic compiler starting with 15.3. Rather than hard-coding a specific compiler version, you can also specify "Latest" as the value of LangVersion to compile with the most recent version of the Visual Basic compiler installed on your system.
For more information, see setting the Visual Basic language version .
In some cases, the Visual Basic compiler cannot infer the tuple element name from the candidate name, and the tuple field can only be referenced using its default name, such as Item1 , Item2 , etc. These include:
The candidate name is the same as the name of a tuple member, such as Item3 , Rest , or ToString .
The candidate name is duplicated in the tuple.
When field name inference fails, Visual Basic does not generate a compiler error, nor is an exception thrown at run time. Instead, tuple fields must be referenced by their predefined names, such as Item1 and Item2 .
Tuples versus structures
A Visual Basic tuple is a value type that is an instance of one of the System.ValueTuple generic types. For example, the holiday tuple defined in the previous example is an instance of the ValueTuple<T1,T2,T3> structure. It is designed to be a lightweight container for data. Since the tuple aims to make it easy to create an object with multiple data items, it lacks some of the features that a custom structure might have. These include:
Custom members. You cannot define your own properties, methods, or events for a tuple.
Validation. You cannot validate the data assigned to fields.
Immutability. Visual Basic tuples are mutable. In contrast, a custom structure allows you to control whether an instance is mutable or immutable.
If custom members, property and field validation, or immutability are important, you should use the Visual Basic Structure statement to define a custom value type.
A Visual Basic tuple does inherit the members of its ValueTuple type. In addition to its fields, these include the following methods:
In addition, the ValueTuple types implement IStructuralComparable and IStructuralEquatable interfaces, which allow you to define custom comparers.
Assignment and tuples
Visual Basic supports assignment between tuple types that have the same number of fields. The field types can be converted if one of the following is true:
The source and target field are of the same type.
A widening (or implicit) conversion of the source type to the target type is defined.
Option Strict is On , and a narrowing (or explicit) conversion of the source type to the target type is defined. This conversion can throw an exception if the source value is outside the range of the target type.
Other conversions are not considered for assignments. Let's look at the kinds of assignments that are allowed between tuple types.
Consider these variables used in the following examples:
The first two variables, unnamed and anonymous , do not have semantic names provided for the fields. Their field names are the default Item1 and Item2 . The last two variables, named and differentName have semantic field names. Note that these two tuples have different names for the fields.
All four of these tuples have the same number of fields (referred to as 'arity'), and the types of those fields are identical. Therefore, all of these assignments work:
Notice that the names of the tuples are not assigned. The values of the fields are assigned following the order of the fields in the tuple.
Finally, notice that we can assign the named tuple to the conversion tuple, even though the first field of named is an Integer , and the first field of conversion is a Long . This assignment succeeds because converting an Integer to a Long is a widening conversion.
Tuples with different numbers of fields are not assignable:
Tuples as method return values
A method can return only a single value. Frequently, though, you'd like a method call to return multiple values. There are several ways to work around this limitation:
You can create a custom class or structure whose properties or fields represent values returned by the method. This is a heavyweight solution; it requires that you define a custom type whose only purpose is to retrieve values from a method call.
You can return a single value from the method, and return the remaining values by passing them by reference to the method. This involves the overhead of instantiating a variable and risks inadvertently overwriting the value of the variable that you pass by reference.
You can use a tuple, which provides a lightweight solution to retrieving multiple return values.
For example, the TryParse methods in .NET return a Boolean value that indicates whether the parsing operation succeeded. The result of the parsing operation is returned in a variable passed by reference to the method. Normally, a call to a parsing method such as Int32.TryParse looks like the following:
We can return a tuple from the parsing operation if we wrap the call to the Int32.TryParse method in our own method. In the following example, NumericLibrary.ParseInteger calls the Int32.TryParse method and returns a named tuple with two elements.
You can then call the method with code like the following:
Visual Basic tuples and tuples in the .NET Framework
A Visual Basic tuple is an instance of one of the System.ValueTuple generic types, which were introduced in .NET Framework 4.7. The .NET Framework also includes a set of generic System.Tuple classes. These classes, however, differ from Visual Basic tuples and the System.ValueTuple generic types in a number of ways:
The elements of the Tuple classes are properties named Item1 , Item2 , and so on. In Visual Basic tuples and the ValueTuple types, tuple elements are fields.
You cannot assign meaningful names to the elements of a Tuple instance or of a ValueTuple instance. Visual Basic allows you to assign names that communicate the meaning of the fields.
The properties of a Tuple instance are read-only; the tuples are immutable. In Visual Basic tuples and the ValueTuple types, tuple fields are read-write; the tuples are mutable.
The generic Tuple types are reference types. Using these Tuple types means allocating objects. On hot paths, this can have a measurable impact on your application's performance. Visual Basic tuples and the ValueTuple types are value types.
Extension methods in the TupleExtensions class make it easy to convert between Visual Basic tuples and .NET Tuple objects. The ToTuple method converts a Visual Basic tuple to a .NET Tuple object, and the ToValueTuple method converts a .NET Tuple object to a Visual Basic tuple.
The following example creates a tuple, converts it to a .NET Tuple object, and converts it back to a Visual Basic tuple. The example then compares this tuple with the original one to ensure that they are equal.
- Visual Basic Language Reference
Submit and view feedback for
- Site Search
- Eng-Tips Forums
- Tek-Tips Forums
Join Tek-Tips ® Today!
Join your peers on the Internet's largest technical computer professional community. It's easy to join and it's free.
Here's Why Members Love Tek-Tips Forums:
- Notification Of Responses To Questions
- Favorite Forums One Click Access
- Keyword Search Of All Posts, And More...
Register now while it's still free!
Already a member? Close this window and log in.
Join Us Close
- Create Account
Home Posts Topics Members FAQ
Join Bytes to post your question to a community of 473,093 software developers and data experts.
To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.
- Latest Articles
- Top Articles
- Posting/Update Guidelines
- Article Help Forum
- View Unanswered Questions
- View All Questions
- View C# questions
- View C++ questions
- View Python questions
- View PHP questions
- CodeProject.AI Server
- All Message Boards...
- Running a Business
- Sales / Marketing
- Collaboration / Beta Testing
- Work Issues
- Design and Architecture
- Artificial Intelligence
- Internet of Things
- ATL / WTL / STL
- Managed C++/CLI
- Objective-C and Swift
- System Admin
- Hosting and Servers
- Linux Programming
- .NET (Core and Framework)
- Visual Basic
- Web Development
- Site Bugs / Suggestions
- Spam and Abuse Watch
- The Insider Newsletter
- The Daily Build Newsletter
- Newsletter archive
- CodeProject Stuff
- Most Valuable Professionals
- The Lounge
- The CodeProject Blog
- Where I Am: Member Photos
- The Insider News
- The Weird & The Wonderful
- What is 'CodeProject'?
- General FAQ
- Ask a Question
- Bugs and Suggestions
multi user assignment for VB.NET
Add your solution here
- Read the question carefully.
- Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
- If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)