VB.NET Interview Questions

vb.net Interview Questions

Q. What is Metadata?

Metadata is termed as “Data about content of the data” and it is found in the catalog of libraries. Practically, it is used at back side of book to see the necessary topic.

Q. What is the difference between VB and VB.Net?

Following are the differences between VB and VB.Net:

Platform dependent Platform Independent
VB is backward compatible VB.Net is not backward compatible
Interpreted Compiler Language
Exception Handling by ‘On Error…..Goto’ Exception Handling by ‘Try….Catch’
Cannot develop multi-threaded applications Can develop multi thread applications

Q. What is the difference between C# and VB.Net?

Following table gives differences between C# and VB.Net:

VB.Net C#
Optional Parameters are accepted Optional Parameters are not accepted
Not case sensitive Case Sensitive
Nothing is used to release unmanaged resources ‘Using’ is used to release unmanaged resources
Support of Both structured and unstructured error handling Unstructured error handling

Q. What is namespace?

A namespace is an organized way of representing Class, Structures and interfaces present in .NET language. Namespaces are hierarchically structured index of a class library, available to all .NET Languages. 

Q. Which namespace are used for accessing the data?

System.Data namespace is used for accessing and managing data from the required data source. This namespace deals only with the data from the specified database. 

Q. What is JIT?

JIT is termed as Just in Time compiler which is used as a part of runtime execution environment. There are three types of JIT and they are:

  • Pre-JIT – Compiles at the time of deployment of an application
  • Econo-JIT – Compiles called methods at runtime
  • Normal JIT – Compiles called methods at runtime and they get compiled first time when called

Q. What is an assembly and its use?

An assembly is one of the elements of a .NET application and it termed as a primary unit of all .NET applications. This assembly can be either DLL or executable file.

Q. What is strong name in .NET assembly?

Strong Name is an important feature of .Net and it is used to identify shared assembly uniquely. Strong name has solved the problem of creating different object with same name and it can be assigned with the help of Sn.exe.

Q. What are the different types of assembly?

There are two types of assembly –

  • Private – A private assembly is normally used by a single application and it is stored in application’s directory.
  • Public – A public assembly or shared assembly is stored in Global Assembly Cache(GAC) which can be shared by many applications

Q. What is the difference between Namespace and Assembly?

Assembly is physical grouping of all units and Namespace logically groups classes. Namespace can have multiple assemblies.

Q. What is INTERNAL keyword in .Net Framework?

INTERNAL keyword is one of the access specifier which will be visible in a given assembly i.e. in a DLL file. This forms a single binary component and it is visible throughout the assembly. 

Q. What are Option Strict and Option Explicit?

.Net generally allows implicit conversion of any data types. In order to avoid data loss during data type conversion, Option Strict keyword is used and it ensures compile time notification of these types of conversions.

Option Explicit is the keyword used in a file to explicitly declare all variables using declare keywords like Dim, Private, Public or Protected. If undeclared variable name persists, an error occurs at compile time.

Q. What is the use of New Keyword?

New keyword is used with the constructor in which it can be used as a modifier or an operator. When it is used as a modifier, it hides inherited member from the base class member. When it is used as an operator, it creates an object to invoke constructors.

1 Dim frm As New Form1 frm.show()

Q. What is ReDim keyword and its use?

Redim keyword is exclusively used for arrays and it is used to change the size of one or more dimensions of an array that has been already declared. Redim can free up or add elements to an array whenever required.


3Dim intArray(7, 7) As IntegerReDim Preserve intArray(7, 8)

ReDim intArray(7, 7)

Q. What is jagged array in VB.Net?

Jagged array is nothing but an array of arrays. Each entry in the array is another array that can hold any number of items.

Q. What is Manifest?

A Manifest is a text file that is used to store metadata information of .NET assemblies. File type of Manifest can be saved as a type PE. Assembly Name, Version, Culture and key token can be saved as a Manifest.

Q. What are all the differences between Dispose and Finalize()?

Finalize method is called by Garbage collector which helps us to make free of unmanaged resources. There are some other resources like window handles, database connections are handled by iDisposable interface.

Dispose method is handled by IDisposable interface to explicitly release unused resources. Dsipose can be called even if other references to the object are alive.

Q. What is Garbage Collection?

Garbage collection is also known as automatic memory management, which is used for automatic recycling of dynamically allocated memory. Garbage collection is performed by Garbage collector which will recycle memory if it is proven that memory will be unused.

Q. What are the types of generations in garbage collector?

There are three types of generations in garbage collector.

Generation 0 – This identifies a newly created object that has been never marked for collection.

Generation 1 – This identifies an object which has been marked as collection but not removed.

Generation 2 – This identifies an object that has survived more than one sweep of the Garbage collector.

Q. What is the use of Option explicit?

Variable must be compulsorily declared when the Option Explicit is termed as ON. If it is OFF, variables can be used without declaration.

Q. What is the difference between System.String and System.StringBuilder classes?

System.string class is non-updatable and it will create new string object instead of updating the same. But updation in the same string object is possible for String. Stringbuilder class. So, the operation on string builder is faster and efficient than the string class.

Q. What is the difference between int and int32?

Int32 represent 32-bit signed integer whereas int is not a keyword used in VB.Net. 

Q. What is hashtable?

Hashtable is set to be items with key and value pairs. Keys are referred as indexes and quick search can be performed for values by searching through the keys.

Q. What are nested classes?

A class that can be declared within the scope of another class. These classes are considered within the scope of the enclosed class and are available within that class or scope.

Q. What is Enumerator?

An Enumerator or Enum is a value type with a set of constants given to the set of the list. Enumeration is used when definition is required for more than one number.

Q. What is Delegate?

A delegate is defined as an object that can refer to a method. Whenever a delegate is assigned to a method, it behaves exactly like that method.


1 public delegate int performaddition(int z, int b);

Q. What is Globalization?

Globalization is nothing but making the application  Internationalize and localizing the application to other languages or cultures. Culture is nothing but a combination of Language(English) and the location like US or UK.

Q. What is the difference between Dataset and Datareader?

DataReader Dataset
Datareader has read only access to the data and it is set to be forward only. Dataset can hold more than one table from the same data source. It even stores relationships between tables.
Datareader cannot persist contents as it is read only Dataset can persist contents
Datareader is connected architecture Dataset is disconnected architecture

Q. What is the difference between value and reference types?

Value types directly store the data and it is allocated to stack. Reference type store a reference to the value’s memory address and are allocated to heap.

Q. What is TRACE in VB.Net?

TRACE allows the user to view how the code has been executed in detail. This tells how the code is working.

Q. What is Authentication and Authorization?

Authentication is the process of obtaining credentials from the users and verifying the user’s identity. Authorization is the process of giving access to the authenticated resources. Authentication leads to Authorization.

Q. What are the types of Authentication?

There are three types of Authentication and they are –

  • Windows Authentication
  • Forms Authentication
  • Passport Authentication

Q. What is Global Assembly Cache (GAC)?

GAC is used where shared .NET assembly resides. It is used in the following criteria:

  • If .Net assembly has special security requirements
  • If .Net application has to be shared with other applications

Q. What is CLR?

    CLR is abbreviated as Common Language Runtime and it forms heart of the .NET framework. It is the responsibility of runtime to take care of the code execution of the program. CLR takes care of the following:

  • Garbage Collection
  • Code Verification
  • Code Access Security
  • IL (Intermediate Language)

Q. What is CTS?

CTS is Common Type System which is used to communicate smoothly between the languages. For example, if VB has Integer data type and C++ has long data type and these data types are not compatible.

In order to be compatible, CTS can be used as an interface between two languages.

Q. What is CLS?

Common Language Specification is a subset of CTS and it is used to unite all languages in to one umbrella. This extends to support all the .NET language into one unit.

Q. What is Managed code?

Managed Code is used to run inside the CLR environment and it is called as .NET run time. All Intermediate Language (IL) are set to be Managed code.

Q. What is serialization in .Net?

Serialization is defined as a process of converting an object to stream of bytes. This is used mainly to transport objects.

Q. How many languages are supported by .Net?

Following are the languages supported by VB.Net:

  • C#
  • Net
  • Perl

Q. What is the difference between Convert.tostring and i.tostring method?

Convert.tostring handles Null and i.tostring does not handle null.

Q. What are the two main parts of .NET?

They are – Common Language Runtime (CLR) and .NET Framework class library.

Q. What is the difference between thread and process?

Thread is used to execute more than one program at a time.  Whereas, Process executes single program at a time.

Q. What is strong typing and weak typing?

Strong type is checking the types of variables at compile time and weak type is checking the types of system as late as possible which is nothing but run time.

Q. How many .NET languages can a single .NET DLL contain?

Only one language will be supported by one DLL.

Q. What is the class that allows an element to be accessed using Unique key?

Hash table is the collection class that allows an element to be accessed using Unique key.

Q. What is Code Security?

.NET framework provides security features to secure code from unauthorized users. There are two types of security in .NET:

  • Role based security – Authorizes User
  • Code access security – Protects system resources from unauthorized calls

Q. Which DLL Is used for Microsoft .NET run time?

Mscoree.dll is used for Microsoft .NET runtime DLL.

Q. How many classes a DLL can contain?

Unlimited number of classes can be present in a DLL.

Q. How can we store decimal data in .NET?

BinaryWriter is used to store decimal data in .NET.

Q. What is deep copy?

Deep copy is nothing but creating a new object and then copying the non-static fields of the current object to new object. 

Q. What is the difference between And and AndAlso in VB.net?

In VB.Net, what is the difference between And and AndAlso? Which should I use?

A: The And operator evaluates both sides, where AndAlso only evaluates the right side if 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: http://www.panopticoncentral.net/2003/08/18/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.

Q. Integer.Parse VS. CInt

Basically, I have been using both Integer.Parse and CInt in most of my daily programming task, but I’m a little bit confused of 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?

A: 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 a 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 circuting unecessary 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.

Q. 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.

Beside from 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) ” & _
”    )”

A: 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#!

Q. 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 lieing 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
End Select

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

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

Select Case 2
Case 0,1
Case 2 To 3
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 because 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 an poorly designed one (which is equivalent to a series of If..Then..Else statements) is an O(n) operation.

Q. What is the use of shared variable in vb.net?

A: 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 aninstance 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()

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:


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

Q. 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

i = Convert.ToInt32(b)

End Sub

I know what it prints (check revision history or run it yourself to see). I’m interested in the “why”.

EDIT: (Just a joke :) You can get 0 too…

Int32.TryParse(“True”, i)

A: 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 which does not use Visual Basic semantics. Instead, it returns the underlying BCL representation for a true boolean value which is 1.

Q. 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 left over 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 opinion or preferences one way or the other.

A: 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 aModule 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 useModules.

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

Q. Or versus OrElse

Whats 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 temp is dbnull.value OrElse temp = 0

A: 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 doesn’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.

Q. 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?


A: Use TypeOf…Is:

If TypeOf objectParameter Is ISpecifiedInterface Then
‘do stuff
End If

Q. 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 couldnt spell and would declare variables with incorrect spelling.. no big deal, until you use the correct spelling when youre 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)

A: 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.

Q. 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.

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 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.

A: First, I should say that I work for ArtinSoft, so my opinion here is based on what Ive 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 quick sands 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 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 does.

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 want 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?

  1. 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.

  1. New features and third-party components

I’m guessing that you guys continue to roll out new features? And Im guessing that you may have noticed that there is less and less code samples available online in Visual Basic 6.0. There are less people responding to the Visual Basic 6.0 forums… unless of course it’s in relation to .NET. There are 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.

  1. Bug fixing and performance improvements

The tools for performance profiling in .NET are breath taking 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.

  1. 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.

  1. 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 a reality that it really opens up opportunity. 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 cost tremendously and take your software to places that your competition could only dream off. 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 user RS Conley states in another answer, If it is critically important to preserve the behavior 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 Microsofts Eric Nelson,http://msdn.microsoft.com/en-gb/dd408373.aspx#migrate, where it says that many rewrites were abandoned due to the unexpected overwhelming complexity. Weve heard about lots of failed rewrite attempts; some of them came to us as customers after deciding to go for a rewrite first.

Heres a white paper written by a colleague of mine on this very subject:http://www.artinsoft.com/5-myth-busting-reasons-for-choosing-automatic-migration-vs-manual-rewrite.aspx

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 idea. Whats the expression, garbage in, garbage out?

Either way, let me know if I can be of any further assistance. Hopefully my comments have provide some useful insight.

Q. How should I cast in VB.NET?

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

  • ToString()
  • CStr(var)
  • CType(var, String)
  • DirectCast(var, String)

EDIT: Suggestion from NotMyself

  • TryCast(var, String)

A: Those are all slightly different, and generally have an 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 string in C#. The TryCast page on MSDN has a good comparison, too.

Q. VB.NET Empty String Array

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

A: The array you created by Dim s(0) As String IS NOT EMPTY

In VB.Net, the subscript you use in the array is 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 string, except they’re loads 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()


Dim t() As String

Q 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 theAnd operator? …or in which I would not want to use the OrElse operator rather than the Or operator?

A: 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.

Q. UnhandledException 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 doesnt 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.
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.
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?

A: Ok, Ive 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 vesion on my machine “System.ServiceProcess, Version=” decompiles like this:

Private Sub ServiceQueuedMainCallback(ByVal state As Object)
Dim args As String() = DirectCast(state, String())
Me.status.checkPoint = 0
Me.status.waitHint = 0
Me.status.currentState = 4
Catch exception As Exception
Me.WriteEventLogEntry(Res.GetString(“StartFailed”, New Object() { exception.ToString }), EventLogEntryType.Error)
Me.status.currentState = 1
Catch obj1 As Object
Me.WriteEventLogEntry(Res.GetString(“StartFailed”, New Object() { String.Empty }), EventLogEntryType.Error)
Me.status.currentState = 1
End Try
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 Im not sure if it explains why timers that are setup in OnStart cant cause an UnhandledException when they fire.

Q. Combining Enums

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

A: 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:

<Flags()> _
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

Q. 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?

A: Using a StreamReader to convert the MemoryStream to a String.

Skip code block

<Extension()> _
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

Q. 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:

First name: John
Middle name: W.
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 things 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.

A: I know this is old and might be answers 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 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.

Q. 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:

<xsl:attribute name=”href”>
/newpage.aspx?<xsl:value-of select=”someNode”/>
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

A: Use a recursive method:

Skip code block

<xsl:template name=”output-tokens”>
<xsl:param name=”list” />
<xsl:variable name=”newlist” select=”concat(normalize-space($list), ‘ ‘)” />
<xsl:variable name=”first” select=”substring-before($newlist, ‘ ‘)” />
<xsl:variable name=”remaining” select=”substring-after($newlist, ‘ ‘)” />
<xsl:value-of select=”$first” />
<xsl:if test=”$remaining”>
<xsl:call-template name=”output-tokens”>
<xsl:with-param name=”list” select=”$remaining” />

0 Responses on VB.NET Interview Questions"

Leave a Message

Your email address will not be published. Required fields are marked *

Copy Rights Reserved © Mindmajix.com All rights reserved. Disclaimer.