Home  >  Blog  >   VB Net

VB.NET Interview Questions

VB.NET, or Visual Basic .NET, is a programming language that is part of the .NET framework and is used for developing Windows applications, web applications, and other software solutions. Currently, there is a tremendous demand for talented professionals in the field. In this article, we have compiled a list of VB.NET interview questions and answers from basic to advanced. This list would be helpful for both freshers and experienced professionals.

Rating: 4.6
  
 
23191

If you're looking for VB.NET Interview Questions and Answers for Experienced or Freshers, you are at the right place. There are a lot of opportunities from many reputed companies in the world. According to research, VB.NET has a market share of about 87.63%. So, You still have the opportunity to move ahead in your career in VB.NET. Mindmajix offers Advanced VB.NET Interview Questions 2024 that helps you in cracking interview & acquire your dream career as VB.NET Developer.

If you want to enrich your career and become a professional in VB.NET, then enroll in "VB.NET Training". This course will help you to achieve excellence in this domain.

Top VB.NET Interview Questions and Answers

VB.NET Interview Questions For Experienced and Freshers

1. Explain the difference between And and AndAlso in VB.net?

The And operator evaluates both sides, where AndAlso only evaluates the right side of the left side is true.
An example:
If mystring IsNot Nothing And mystring.Contains(“Foo”) Then
‘ bla bla
End If
The above throws an exception if mystring = Nothing
If mystring IsNot Nothing AndAlso

mystring.Contains(“Foo”)

Then
‘ bla bla
End If
This one does not throw an exception.
So if you come from the C# world, you should use AndAlso like you would use &&.
More info here: The Ballad of AndAlso and OrElse

AndAlso is much like And, except it works like && in C#, C++, etc.
The difference is that if the first clause (the one before AndAlso) is true, the second clause is never evaluated – the compound locical expression is “short-circuited”.
This is sometimes very useful, eg. in an expression such as
If Not IsNull(myObj) Andalso myObj.SomeProperty = 3 Then

End If
Using the old And in the above expression would throw a NullReferenceException if myObj were null.

2. Integer.Parse VS. CInt

Basically, I have been using both Integer.Parse and CInt in most of my daily programming tasks, but I’m a little bit confused about what is the difference between the two.
Is there anyone out there who can help me clarify the difference between Integer.Parse and CIntin VB.NET?

Ans: CInt does a whole lot more than integer.Parse.
Cint will first check to see if what it was passed is an integer, and then simply casts it and returns it. If it’s double it will try to convert it without first converting the double to a string.
See this from the help for CInt and other TYPE CONVERSION FUNCTIONS
Fractional Parts. When you convert a nonintegral value to an integral type, the integer conversion functions (CByte, CInt, CLng, CSByte, CShort, CUInt, CULng, and CUShort) remove the fractional part and round the value to the closest integer.
If the fractional part is exactly 0.5, the integer conversion functions round it to the nearest even integer. For example, 0.5 rounds to 0, and 1.5 and 2.5 both round to 2. This is sometimes called banker’s rounding, and its purpose is to compensate for a bias that could accumulate when adding many such numbers together.
So in short, it does much more than convert a string to an integer, e.g. applying specific rounding rules to fractions, short-circuiting unnecessary conversions, etc.
If what you’re doing is converting a string to an integer, use integer.parse (or integer.TryParse), if you’re coercing an unknown value (e.g. a variant or object from a database) to an integer, use CInt.

3. VB.NET Single statement across multiple lines.

Is there any way to have a statement across multiple lines without the underscore character? It is really annoying in multi-line strings such as SQL statements, and especially LINQ queries.
Besides the ugliness and difficulty when changing a line (nothing lines up anymore) you can’t use comments in the middle of the multi-line statement.
Examples of my daily personal hell.

dim results = from a in articles _
where a.articleID = 4 _ ‘ articleID     – Nope, cant do this
select a.articleName
dim createArticle as string = _
“Create table article ” & _
”    (articleID int ” & _
”    ,articleName varchar(50) ” & _
”    )”

No, you have to use the underscore, but I believe that VB.NET 10 will allow multiple lines w/o the underscore, only requiring if it can’t figure out where the end should be.
VB uses line break as the statement terminator. There is no way to change it (it’s like asking C# not to expect; at the end of statements). There is a solution however, you can always switch to C#!

Q4. What is the VB.NET select case statement logic with case OR-ing?

When writing some vb code I tripped and I’m still left wondering why. I was ORing the case expectation yet a value that lies within this range didn’t warrant a match; why not?
Example Code:

Select Case 2
Case 0
”// Some logic
Case 1
”// Some other logic
Case 2 Or 3
Console.WriteLine(“hit”)
End Select


With the above, I would naturally assume that “hit” would be printed, but that’s not the case.

JaredPar has it right but you can also use the To construct

Select Case 2
Case 0,1
Case 2 To 3
Console.WriteLine(“Hit”)
End Select


This would be 0 or 1 do nothing, 2 or 3 print Hit…The To construct is a range…

HERE’S THE MSDN
Edit: It appears I was wrong in assuming that VB.NET doesn’t allow Case ORing. I was thinking in C# and IL and it appears I was wrong.
However, as someone pointed out, the reason your code did not work was that Case 2 Or 3 was evaluating 2 Or 3 as a bitwise or and hence evaluating to Case 3.
For clarification:

2 binary = 0000 0010
3 binary = 0000 0011
2 Or 3 binary = 0000 0011 (= 3)
Select Case 2
Case 0            ‘–> no match
Case 1            ‘–> no match
Case 2 Or 3       ‘(equivalent to Case 3  –> no match)
End Select


However, I feel that I should point out that for the sake of performance, one should not use such constructs. When the compiler encounters Select statements (switch in C#) it will try to compile them using lookup tables and the switch MSIL instruction but in the case where you have something likeCase 1,2,11,55 the compiler will not be able to convert that to a lookup table and it will have to use a series of compares (which is like using If.. Else).
The point is that in order to really take advantage of the Select statement, the cases should be designed with that in mind. Otherwise, the only benefit is code readability.
A well-designed switch is an O(1) operation whereas a poorly designed one (which is equivalent to a series of If..Then..Else statements) is an O(n) operation.

MindMajix Youtube Channel

5. What is the use of shared variables in vb.net?

The “shared” keyword in VB.NET is the equivalent of the “static” keyword in C#.
In VB.NET, the shared keyword can be applied to Dim, Event, Function, Operator, Property, and Sub statements within a class; however, in C#, the static keyword can be applied both to these statements within a normal class and also at the class level to make the entire class static.
A “shared” or “static” method acts upon the “type” (that is, the class) rather than acting upon an instance of the type/class. Since shared methods (or variables) act upon the type rather than an instance, there can only ever be one “copy” of the variable or method as opposed to many copies (one for each instance) in the case of non-shared (I.e. Instance) methods or variables.
For example: If you have a class, let’s call it MyClass with a single non-shared method called MyMethod.

Public Class MyClass
Public Sub MyMethod()
// Do something in the method
End Sub
End Class
In order to call that method you would need an instance of the class in order to call the method. Something like:
Dim myvar as MyClass = New MyClass()
myvar.MyMethod()
If this method was then made into a “shared” method (by adding the “shared” qualifier on the method definition, you no longer need an instance of the class to call the method.
Public Class MyClass
Public Shared Sub MyMethod()
// Do something in the method
End Sub
End Class
And then:
MyClass.MyMethod()

You can also see examples of this in the .NET framework itself. For example, the “string” type has many static/shared methods. Ie.

// Using an instance method (i.e. Non-shared) of the string type/class.
Dim s as String = “hello”
s.Replace(“h”, “j”)
// Using a static/shared method of the string type/class.
s = String.Concat(s, ” there!”);

 

Here’s a good article that explains it further:
SHARED MEMBERS AND INSTANCE MEMBERS IN VB.NET

6. Convert Boolean to Integer in VB.NET

What will this print, and why?

Skip code block
Sub Main()
Dim i As Integer
Dim b As Boolean
i = 1
b = i
i = b
Console.WriteLine(i)
i = Convert.ToInt32(b)
Console.WriteLine(i)
End Sub

 

I know what it prints (check the revision history or run it yourself to see). I’m interested in the “why”.
EDIT: (Just a joke :) You can get 0 too…
I

nt32.TryParse(“True”, i)
Console.WriteLine(i)

Ans: What you’re seeing is a bit of legacy code showing its head.
At the heart of the matter is the VT_BOOL type. Visual Basic 6.0 used the VT_BOOL type (AKA VARIANT_BOOL) for its boolean values. True for a VARIANT_BOOL is represented with the value VARIANT_TRUE which has the integer value -1. During the conversion to .NET it was decided that when using Visual Basic conversion routines to convert a boolean value to an Integer value, Visual Basic 6.0 semantics would be maintained on the return value; it would be -1.
The first implicit conversion occurs with the b = i line. Under the hood, this does an implicit conversion from integer to boolean. Any non-zero value is deemed to be true, therefore the resulting value is true.
However, the following line of code is doing an implicit conversion to an integer type.
i = b
Under the hood, this uses one of the Visual Basic conversion routines (CTYPE or CINT) to convert the value to an integer. As such Visual Basic semantics are in play and the value returned is -1.
The next interesting line is the Convert.ToInt32() line. This is using a .NET conversion routine that does not use Visual Basic semantics. Instead, it returns the underlying BCL representation for a true boolean value which is 1.

7. Classes vs. Modules in VB.Net

Is it considered an acceptable practice to use Modules instead of Classes with Shared member functions in VB.Net?

I tend to avoid Modules because they feel like leftover remains from VB6 and don’t really seem to fit in anymore. On the other hand, there doesn’t seem to be much difference between using a Module and a Class with only Shared members. It’s not that often that I really have much need for either, but sometimes there are situations where they present a simple solution.
I’m curious to hear whether you have any opinions or preferences one way or the other.

Modules are VB counterparts to C# static classes. When your class is designed solely for helper functions and extension methods and you don’t want to allow inheritance and instantiation, you use a Module.
By the way, using Module is not really subjective and it’s not deprecated. Indeed you must use a module when it’s appropriate. .NET Framework itself does it many times (System.Linq.Enumerable, for instance). To declare an extension method, it’s required to use modules.
Modules are by no means deprecated and are used heavily in the VB language. It’s the only way for instance to implement an extension method in VB.Net.
There is one huge difference between Modules and Classes with Static Members. Any method defined on a Module is globally accessible as long as the Module is available in the current namespace. In effect a Module allows you to define global methods. This is something that a class with only shared members cannot do.
Here’s a quick example that I use a lot when writing VB code that interops with raw COM interfaces.
Skip code block
Module Interop
Public Function Succeeded(ByVal hr as Integer) As Boolean

End Function
Public Function Failed(ByVal hr As Integer) As Boolean
…
End Function
End Module
Class SomeClass
Sub Foo()
Dim hr = CallSomeHrMethod()
if Succeeded(hr) then
..
End If
End Sub
End Class

8. Or versus OrElse

What's the difference between or and OrElse?

if temp is dbnull.value or temp = 0
produces the error *Operator ‘=’ is not defined for type ‘DBNull’ and type ‘Integer’.**
while this one works like a charm!
if the temp is dbnull.value OrElse temp = 0

OrElse is a short-circuiting operator Or is not.
By the definition of the boolean ‘or’ operator, if the first term is True then the whole is definitely true – so we don’t need to evaluate the second term.
OrElse knows this, so don’t try and evaluate temp = 0 once it’s established that temp Is DBNull.Value
Or doesn’t know this, and will always attempt to evaluate both terms. When temp Is DBNull.Value, it can’t be compared to zero, so it falls over.
You should use… well, whichever one makes sense.

9. Test if an object implements an interface

I have an object parameter and I need to check if the object implements a specified interface in vb.net. How to test this?
Thanks.

Use TYPEOF…IS:
If TypeOf object parameter Is ISpecifiedInterface Then
‘do stuff
End If

10. What’s an option strict and explicit?

I saw this post:
“Typos Just use option strict and explicit please.. during one software development project, which I was on as a consultant, they were getting ridiculous amounts of errors everywhere turned out the developer couldn't spell and would declare variables with incorrect spelling.. no big deal, until you use the correct spelling when you're assigning a value to it and you had option explicit off. Ouch to them”
what is an option strict and explicit anyway? I have googled it up but can’t get the idea (because mostly it’s Visual Basic, I’m doing PHP)

Ans: Option Explicit means that all variables must be declared. See HERE. Without this, you can accidentally declare a new variable just by misspelling another variable name. This is one of those things that cause a lot of grief as you’re trying to debug VB programs and figure out why your program isn’t working properly. In my opinion, this shouldn’t even be an option – it should always be on.
Option Strict “restricts implicit data type conversions to only widening conversions”. See HERE. With this option enabled, you can’t accidentally convert one data type to another that is less precise (e.g. from an Integer to a Byte). Again, an option that should be turned on by default.

11. How do you migrate a large app from Visual Basic 6.0 to VB.NET?

My company makes a monolithic piece of software that our customers use to run their car dealerships. The original application was written in Visual Basic 6.0, and it has grown substantially over the last few years. Until now, there hasn’t really been a business case for switching to the .NET framework. Sure, it’s newer, considerably better at certain things, and when used correctly speeds development time, but there’s nothing we can’t do in Visual Basic 6.0 that we need to be able to do. Getting things done is harder in Visual Basic 6.0, but almost nothing is impossible. Recently though, Microsoft dropped support for Visual Basic 6.0, and it seems obvious to me that switching to a new platform is inevitable.
The way VB.NET works and requires you to think is so fundamentally different (heck, even the way you pass variables into subs has changed), and as far as I can tell, switching to .NET would require a complete re-design and re-write of the application.
My question(s): Have any of you been in this position? Of the tools available to smooth the transition, which ones work and which should be avoided? And how do I sell our customers and my boss on this? As the suits like to say, where’s the ROI?
@Rob Burke:
Boatload of WinForms: Absolutely.
ADO code for DB access: Yes, but all in one easy-to-manage place.
ASP web pages: None. This is strictly a desktop app.
Custom controls: Yes, but all written by us (i.e. no third-party stuff).
Installed base: ~1000 machines.
The last time I called Microsoft tech support (I would have been 16 or 17 at the time), I was having trouble getting the MSDN library to work on my machine (this is back in the days when MSDN wasn’t available online, and the internet connections were dial-up). After having my support case elevated, the “solution” they gave me was to format my hard drive and reinstall everything. Needless to say, I didn’t consider that a solution.

First, I should say that I work for ArtinSoft, so my opinion here is based on what I've seen with our customers. However, my software development experiences prior to ArtinSoft extend further back than a decade and are quite relevant to the topic at hand.
Have I been in this position?
Yes, absolutely and on many occasions. Very seldom have I seen a company approach this hurdle proactively. More often than not, I’ve seen companies and their software applications languish with unsupported technologies that waited too late until the quicksands of technical obsolescence left them few or no choices. And in more than one instance, some have even got themselves in a position where only a complete rewrite will save them. That’s not where you want to be.
How do you sell it to your customers?
I would be honest with your customers… you want to continue to offer a superior product and be able to respond quickly to their needs as the product evolves. The current Visual Basic 6.0 environment is making that more and more difficult. It’s tougher and tougher to find either talented Visual Basic 6.0 developers or talented .NET developers that will tolerate Visual Basic 6.0. And even if you do, that talent is going to get more and more expensive as the talent pool diminishes and job satisfaction dwindles.
Your customers use other applications in the normal course of their lives, and eventually, they are going to notice that your application is growing old and outdated and no longer meets the same expectations of that other day-to-day do.
How do you sell this to your boss?
Since I’m not sure of the exact situation that you find yourself in, here are the opportunities that I’ve contemplated most when considering make such transitions in the past. And you might want to find business and technical leaders within your company to help champion the effort and to help figure out the most appropriate way to sell this in your organization.
1. Competitive advantages/customer perception
I assume that your application is not alone in the car dealership software universe. If yours is the first one to make the great stride forward to .NET, then great. But if it’s the last… is that really where your company wants to be? Is it something that might prevent a customer from renewing their maintenance agreement – assuming you bring in revenue in that way? If you do, then what would be a better way to prove the value of a maintenance agreement than to upgrade the application?
2. Talent pool and retention
I’m not sure if you’ve experienced this phenomenon yet or how your technical workforce is structured but older technologies become more and more expensive, yield less and less innovation and make attracting and retaining talent increasingly difficult to the point where morale can be seriously affected. At this point, .NET talent is very affordable and available. It’s still fun, still hip and has a long and valuable career potential for those that work with it.
3. New features and third-party components
I’m guessing that you guys continue to roll out new features? And I'm guessing that you may have noticed that there are less and less code samples available online in Visual Basic 6.0. There are fewer people responding to the Visual Basic 6.0 forums… unless of course, it’s in relation to .NET. There is less support for Visual Basic 6.0 third-party components and open-source projects. Visual Studio for .NET is a vast improvement over the Visual Basic 6.0 versions. And the .NET language and native libraries may just render some of the third-party components in your application unnecessary.
4. Bug fixing and performance improvements
The tools for performance profiling in .NET are breathtaking compared to what was previously available with Visual Basic 6.0. Managed code is simply easier for people to work with. Debugging in Visual Studio for .NET is amazingly efficient. And sure, lots of improvements with connectivity, exception handling, and memory management to mention only a few.
5. Creates new value.
When all is said and done, do you think that having a .NET application versus a Visual Basic 6.0 application will increase the valuation of your company? Private or publicly held, no matter – your application’s value becomes a serious asset. If accounted for correctly, all of the development costs could be amortized over time as a capital investment. I’m no tax guy but I know that it can really change the equation.
6. Roadmap
Getting to .NET is a fantastic place to be since steps either in the direction of Silverlight and/or moving to the Cloud are so much closer to a reality that it really opens up opportunities. In fact, have you considered such a move? The business cases for that can be mind-blowing. It’s a real paradigm shift that can reduce costs tremendously and take your software to places that your competition could only dream of. Anyhow… I’m getting off-topic without knowing more about your software and your business model.
Of the tools available to smooth the transition, which ones work and which should be avoided?
Except for small applications, I would strongly recommend against a rewrite. Sure, who wouldn’t like an opportunity to refactor. But the objective which can often times get lost in such a migration is just that… to migrate. Refactor and changes in the architecture can always happen later. Those hurdles are far smaller and should really be avoided to minimize risk.
As a user, RS Conley states in another answer, If it is critically important to preserve the behavior of your application or if it is mission-critical then conversion is the only path.
Another user, MarkJ, provided us with a link to a post by Microsoft Eric Nelson, Visual Basic 6

where it says that many rewrites were abandoned due to the unexpected overwhelming complexity. We've heard about lots of failed rewrite attempts; some of them came to us as customers after deciding to go for a rewrite first.
Here's a white paper is written by a colleague of mine on this very subject:

Automatic Migration vs Manual Rewrite

Don’t try to enhance the functionality of the application until the move to .NET is complete. It is easy to let the scope of the project runaway from you. It’s tempting while you’ve got the patient on the table to do some other overdue preventative care but resist the temptations. A .NET migration is not for the faint of heart.
You should look for a tool that will preserve your business logic. That will convert as many third-party components to their .NET equivalent as possible. Depending on what coding standards were in places when your application was originally written and how well the standards were followed thereafter, it’s best to find a tool that will maintain the class structure of your application so that your existing developers don’t need to relearn how to navigate through the code. This can save a lot of time getting back to the business at hand. Please bear in mind as well that if the original application is poorly written, then the code that results from an automatic migration might not be ideal. What's the expression, garbage in, garbage out?
Either way, let me know if I can be of any further assistance. Hopefully, my comments have provided some useful insight.

12. How should I cast in VB.NET?

Are all of these equal? Under what circumstances should I choose each over the others?

1.ToString()
2.CStr(var)
3.CType(var, String)
4.DirectCast(var, String)
EDIT: Suggestion from NOTMYSELF…
5.TryCast(var, String)

Those are all slightly different and generally have acceptable usage.
TOSTRING()is going to give you the string representation of an object, regardless of what type it is. Use this if var is not a string already.
CSTR(var)is the VB string, cast operator. I’m not a VB guy, so I would suggest avoiding it, but it’s not really going to hurt anything. I think it is basically the same as CType.
CTYPE(var, String)will convert the given type into a string, using any provided conversion operators.
DIRECTCAST(var, String)is used to up-cast an object into a string. If you know that an object variable is, in fact, a string, use this. This is the same as (string)var in C#.
TRYCAST(as mentioned by @NotMyself) is like DirectCast, but it will return Nothing if the variable can’t be converted into a string, rather than throwing an exception. This is the same as var as a string in C#. The TryCast page on MSDN has a good comparison, too.

13. VB.NET Empty String Array

How can I create an empty one-dimensional string array?

The array you created by Dim s(0) As String IS NOT EMPTY
In VB.Net, the subscript you use in the array is an index of the last element. VB.Net by default starts indexing at 0, so you have an array that already has one element.
You should instead try using System.Collections.Specialized.StringCollection or (even better) System.Collections.Generic.List(Of String). They amount to pretty much the same thing as an array of strings, except they load better for adding and removing items. And let’s be honest: you’ll rarely create an empty string array without wanting to add at least one element to it.
If you really want an empty string array, declare it like this:
Dim s As String()
or
Dim t() As String

14. Should I always use the AndAlso and OrElse operators?

Is there ever a circumstance in which I would not want to use the ANDALSO operator rather than the AND operator? …or in which I would not want to use the OR ELSE operator rather than the OR operator?

From MSDN:
Short-Circuiting Trade-Offs
Short-circuiting can improve performance by not evaluating an expression that cannot alter the result of the logical operation. However, if that expression performs additional actions, short-circuiting skips those actions. For example, if the expression includes a call to a Function procedure, that procedure is not called if the expression is short-circuited, and any additional code contained in the Function does not run. If your program logic depends on any of that additional code, you should probably avoid short-circuiting operators.
Sure: if you want to make sure that both sides of the expression are evaluated. This might be the case if, for example, both sides are method calls that return booleans as a result of some other operation.
But in general, you should AndAlso/OrElse whenever you would use &&/|| in C/C++/C#, which of course is the vast majority of the time.

15. Unhandled Exception handler in a .Net Windows Service

Is it possible to use an UnhandledException Handler in a Windows Service?
Normally I would use a custom built Exception Handling Component that does logging, phone home, etc. This component adds a handler to System.AppDomain.CurrentDomain.UnhandledException but as far as I can tell this doesn't achieve anything win a Windows Service so I end up with this pattern in my 2 (or 4) Service entry points:

Protected Overrides Sub OnStart(ByVal args() As String)
‘ Add code here to start your service. This method should set things
‘ in motion so your service can do its work.
Try
MyServiceComponent.Start()
Catch ex As Exception
‘call into our exception handler
MyExceptionHandlingComponent.ManuallyHandleException (ex)
‘zero is the default ExitCode for a successfull exit, so if we set it to non-zero
ExitCode = -1
‘So, we use Environment.Exit, it seems to be the most appropriate thing to use
‘we pass an exit code here as well, just in case.
System.Environment.Exit(-1)
End Try
End Sub


Is there a way my Custom Exception Handling component can deal with this better so I don’t have to fill my OnStart with messy exception handling plumbing?

Ok, I've done a little more research into this now. When you create a windows service in .Net, you create a class that inherits from System.ServiceProcess.ServiceBase (In VB this is hidden in the .Designer.vb file). You then override the OnStart and OnStop function, and OnPause and OnContinue if you choose to. These methods are invoked from within the base class so I did a little poking around with reflector. OnStart is invoked by a method in System.ServiceProcess.ServiceBase called ServiceQueuedMainCallback. The version on my machine “System.ServiceProcess, Version=2.0.0.0” decompiles like this:

Private Sub ServiceQueuedMainCallback(ByVal state As Object)
Dim args As String() = DirectCast(state, String())
Try
Me.OnStart(args)
Me.WriteEventLogEntry(Res.GetString(“StartSuccessful”))
Me.status.checkPoint = 0
Me.status.waitHint = 0
Me.status.currentState = 4
Catch exception As Exception
Me.WriteEventLogEntry(Res.GetString(“StartFailed”,NewObject(){ exception.ToString }), EventLogEntryType.Error)
Me.status.currentState = 1
Catch obj1 As Object
Me.WriteEventLogEntry(Res.GetString(“StartFailed”,NewObject() { String.Empty }), EventLogEntryType.Error)
Me.status.currentState = 1
End Try
Me.startCompletedSignal.Set
End Sub


So because Me.OnStart(args) is called from within the Try portion of a Try-Catch block I assume that anything that happens within the OnStart method is effectively wrapped by that Try-Catch block and therefore any exceptions that occur aren’t technically unhandled as they are actually handled in the ServiceQueuedMainCallback Try Catch. So CurrentDomain.UnhandledException never actually happens at least during the startup routine. The other 3 entry points (OnStop, OnPause, and OnContinue) are all called from the base class in a similar way.
So I think that explains why my Exception Handling component cant catch UnhandledException on Start and Stop, but I'm not sure if it explains why timers that are set up in OnStart cant cause an UnhandledException when they fire.

16. Combining Enums

Is there a way to combine Enums in VB.net?

I believe what you want is a flag-type enum.
You need to add the Flags attribute to the top of the enum, and then you can combine enums with the ‘Or’ keyword.
Like this:
_

Enum CombinationEnums As Integer
HasButton = 1
TitleBar = 2
ReadOnly = 4
ETC = 8
End Enum

Note: The numbers to the right are always twice as big (powers of 2) – this is needed to be able to separate the individual flags that have been set.
Combine the desired flags using the Or keyword:

Dim settings As CombinationEnums
settings = CombinationEnums.TitleBar Or CombinationEnums.Readonly
This sets TitleBar and Readonly into the enum
To check what’s been set:
If (settings And CombinationEnums.TitleBar) = CombinationEnums.TitleBar Then
Window.TitleBar = True
End If

17. How do you get a string from a MemoryStream?

If I am given a MemoryStream that I know has been populated with a String, how do I get aString back out?

Using a StreamReader to convert the MemoryStream to a String.
Skip code block
_

Public Function ReadAll(ByVal memStream As MemoryStream) As String
‘ Reset the stream otherwise you will just get an empty string.
‘ Remember the position so we can restore it later.
Dim pos = memStream.Position
memStream.Position = 0
Dim reader As New StreamReader(memStream)Dim str = reader.ReadToEnd()
‘ Reset the position so that subsequent writes are correct.
memStream.Position = pos
Return str
End Function

18. Simple way to parse a person’s name into its component parts?

A lot of contact management programs do this – you type in a name (e.g., “John W. Smith”) and it automatically breaks it up internally into:
1. First name: John
2. Middle name: W.
3.Last name: Smith
Likewise, it figures out things like “Mrs. Jane W. Smith” and “Dr. John Doe, Jr.” correctly as well (assuming you allow for fields like “prefix” and “suffix” in names).
I assume this is a fairly common thing that people would want to do… so the question is… how would you do it? Is there a simple algorithm for this? Maybe a regular expression?
I’m after a .NET solution, but I’m not picky.
Update: I appreciate that there is no simple solution for this that covers ALL edge cases and cultures… but let’s say for the sake of argument that you need the name in pieces (filling out forms – as in, say, tax or other government forms – is one case where you are bound to enter the name into fixed fields, whether you like it or not), but you don’t necessarily want to force the user to enter their name into discrete fields (less typing = easier for novice users).
You’d want to have the program “guess” (as best it can) on what’s first, middle, last, etc. If you can, look at how Microsoft Outlook does this for contacts – it lets you type in the name, but if you need to clarify, there’s an extra little window you can open. I’d do the same thing – give the user the window in case they want to enter the name in discrete pieces – but allow for entering the name in one box and doing a “best guess” that covers most common names.

I know this is old and might be answered somewhere I couldn’t find already, but since I couldn’t find anything that works for me, this is what I came up with which I think works a lot like Google Contacts and Microsoft Outlook. It doesn’t handle edge cases well, but for a good CRM type app, the user can always be asked to resolve those (in my app I actually have separate fields all the time, but I need this for the data import from another app that only has one field):
You probably don’t need to do anything fancy really. Something like this should work.

Skip code block
Name = Name.Trim();
arrNames = Name.Split(‘ ‘);
if (arrNames.Length > 0) {
GivenName = arrNames[0];
}
if (arrNames.Length > 1) {
FamilyName = arrNames[arrNames.Length – 1];
}
if (arrNames.Length > 2) {
MiddleName = string.Join(” “, arrNames, 1, arrNames.Length – 2);
}


You may also want to check for titles first.

19. Does XSLT have a Split() function?

I have a string in a node and I’d like to split the string on ‘?’ and return the last item in the array.
For example, in the block below:

/newpage.aspx?
Link text
I’d like to split the someNode value.
Edit: Here’s the VB.Net that I use to load the Xsl for my Asp.Net page:
Skip code block
Dim xslDocPath As String = HttpContext.Current.Server.MapPath(“~/App_Data/someXslt.xsl”)
Dim myXsltSettings As New XsltSettings()
Dim myXMLResolver As New XmlUrlResolver()
myXsltSettings.EnableScript = True
myXsltSettings.EnableDocumentFunction = True
myXslDoc = New XslCompiledTransform(False)
myXslDoc.Load(xslDocPath, myXsltSettings, myXMLResolver)
Dim myStringBuilder As New StringBuilder()
Dim myXmlWriter As XmlWriter = Nothing
Dim myXmlWriterSettings As New XmlWriterSettings()
myXmlWriterSettings.ConformanceLevel = ConformanceLevel.Auto
myXmlWriterSettings.Indent = True
myXmlWriterSettings.OmitXmlDeclaration = True
myXmlWriter = XmlWriter.Create(myStringBuilder, myXmlWriterSettings)
myXslDoc.Transform(xmlDoc, argumentList, myXmlWriter)
Return myStringBuilder.ToString()


Update: here’s AN EXAMPLE OF SPLITTING XML ON A PARTICULAR NODE

Use a recursive method:
Skip code block

Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
VB.NET TrainingApr 20 to May 05View Details
VB.NET TrainingApr 23 to May 08View Details
VB.NET TrainingApr 27 to May 12View Details
VB.NET TrainingApr 30 to May 15View Details
Last updated: 02 Jan 2024
About Author

Ravindra Savaram is a Technical Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.

read more
Recommended Courses

1 / 15