mid in C#

M

Mr. X.

In VB.NET it's mid.
In C# it's SubString.
But in VB.NET I could exceed the length of the string, and in C# I cannot.

I.e
In VB.NET :
dim s as String;
....
s = "abcdefg";

mid(s, 4,6) returns "defg"
mid(s, 6, 3) returns ""

In C#
s.SubString(3, 6) throws an exception.
s.SubString(5, 3) throws an exception.

Are there any alternatives ?

Thanks :)
 
R

Rick Lones

Mr. X. said:
In VB.NET it's mid.
In C# it's SubString.
But in VB.NET I could exceed the length of the string, and in C# I cannot.

I.e In VB.NET :
dim s as String;
...
s = "abcdefg";

mid(s, 4,6) returns "defg"
mid(s, 6, 3) returns ""

In C#
s.SubString(3, 6) throws an exception.
s.SubString(5, 3) throws an exception.

Are there any alternatives ?

You mean other than actually checking the string length ahead of time or else
being prepared to catch the error and fix things up later? Not that I am aware
of. You could write your own substring function which emulates the desired VB
functionality, of course.

Personally I don't much care for the way VB handles this - it just feels sloppy
to me. The overly-forgiving approach can cover up logic errors in the program
and make you think things are fine when they are maybe not fine at all.

HTH,
-rick-
 
H

Harlan Messinger

Mr. X. said:
In VB.NET it's mid.
In C# it's SubString.
But in VB.NET I could exceed the length of the string, and in C# I cannot.

I.e In VB.NET :
dim s as String;
...
s = "abcdefg";

mid(s, 4,6) returns "defg"
mid(s, 6, 3) returns ""

In C#
s.SubString(3, 6) throws an exception.
s.SubString(5, 3) throws an exception.

Are there any alternatives ?

Yes, in VB.NET you can stop trying to get it to return characters that
aren't there and letting it give you something different from what you
asked for without telling you it's an error!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top