Alphonse Prakash
Alphonse Prakash

Reputation: 840

What is the difference between String.Substring and Mid?

I am really confused between Mid and Substring in VB.NET. Can anyone help me understand the difference with the help of a program? It will be really appreciated.

Upvotes: 1

Views: 3377

Answers (2)

jmoreno
jmoreno

Reputation: 13561

The biggest difference is that Mid doesn't throw any exceptions, while substring will throw if any of your indexes are out of range.

   Dim s = "this".Substring(100, 5000) ' this throws "ArgumentOutOfRange" exception
   Dim str = Mid("This", 100, 5000) ' string will equal string.empty

This makes Mid more convenient in some circumstances, and if you're already using Microsoft.VisualBasic (which is not just a legacy namespace, it's even available in .net core 7) from a previous project or some other need, I wouldn't recommend changing.

If you just don't like VB for some reason, you could create an extension method and make it behave however you like.

Upvotes: 0

Caius Jard
Caius Jard

Reputation: 74605

You can read the documentation for Mid and for Substring

The biggest difference arises from Mid being a legacy adapter function intended either to help VB6 code work if pasted into a vb.net project, or to provide VB6 programmers with some familiar functionality while they switch to using the modern .NET equivalent (Substring)

As a legacy function, Mid adopts the VB6 notions of strings being one-based indexing, rather than zero based (used by nearly everything else .NET) so anything you Mid should have a start parameter that is 1 greater than anything you Substring

Mid("Hellow World",1,5) 'returns Hello
Substring("Hellow World",0,5) 'returns Hello

Substring has a corollary, Remove, which removes chars after a certain point like Left used to. Ditching Left/Mid/Right in favour of Substring/Remove makes it easier to understand what to use/what will happen if the string passed in is in a right-to-left language

Upvotes: 5

Related Questions