MGBrown.com

C# equivalent of VB’s Left function

It really bugs me that C# does not have an equivalent of VB’s Left function. I know I could be using text.Substring(0,length) but this has the rather annoying feature of throwing an exception if the string is shorter than the length parameter. In 99.999999% of cases what I actually want it to do is return as much as it can instead.

Anyway here is my equivalent:

public static string Left(string text, int length)
{
    if (length < 0)
        throw new ArgumentOutOfRangeException("length", length, "length must be > 0");
    else if (length == 0 || text.Length == 0)
        return "";
    else if (text.Length <= length)
        return text;
    else
        return text.Substring(0, length);
}

Comments

Re: C# equivalent of VB’s Left function

This is simple, 3 lines of code:
----------------------------------------------

int iMyLen = 5 //Or whatever length you want...

string sMyString;

sMyString = sMyString.Substring(0,iMyLen);

--------------------------------------------------
Happy Lefting!

Comment from mertman@diningmall.com at Wednesday, 01 August 2007 10:02PM (GMT+00)

Re: C# equivalent of VB’s Left function

Mertman,

You seem to have missed the wole point of the post? Substring throws an exception if the string's length is less than that passed as a parameter! So the following code throws an exception:

int iMyLen = 5; //Or whatever length you want...

string sMySourceString = &quot;0123&quot;;

string sMyString;

sMyString = sMySourceString.Substring(0,iMyLen);

Comment from Martin Brown at Friday, 03 August 2007 05:03PM (GMT+00)

Re: C# equivalent of VB’s Left function

I am going mad... maybe if so then please delete this ... and call me a crazy foo ..

but I thought left meant start from some point in the string you want to go left from (not right) why are you starting from 0 ... this is not left ... this is substring

Comment from Harry Potter at Wednesday, 25 August 2010 09:59PM (GMT+00)

Sorry, this post is no longer accepting comments.