MGBrown.com Hunk

MGBlog

Saturday, 12 August 2006

Mon, 14 Aug 2006 - 09:00am (GMT+1)
Comments

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


It's quite poor that MS doen't support this simple method in a low level implementation...

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!

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 = "0123";

string sMyString;

sMyString = sMySourceString.Substring(0,iMyLen);

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

Add Your Comment

Your Name:
Harry Potter
Your homepage URL (optional):  
http://www.mgbrown.com
Title:*
Comment:*
Copy code into box:
 
* HTML tags not supported