Geeks With Blogs


Add to Google

Tim Hibbard CEO for EnGraph software

This very simple extension method makes a string a fixed length.  It appends whitespace to a string that is shorter than required or strips characters to a string to is longer than requested.

See ScottGu blog post for a brush up (or intro) on extension methods.


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ParaPlan.Extensions { public static class StringHelper { public static string ToFixedLength(this string s, int width) { string rv = s; if (s.Length > width) { rv = s.Remove(width); } else { int neededWhiteSpace = width - s.Length; rv = s + new string(char.Parse(" "), neededWhiteSpace); } return rv; } } }



Technorati tags: , ,
Posted on Tuesday, January 29, 2008 11:09 AM .NET | Back to top

Comments on this post: Extension Method - String.ToFixedLength

# re: Extension Method - String.ToFixedLength
Requesting Gravatar...
Aren't you missing a check for null before you access s? Assigning s to rv also seems unnecessary to me.
Left by EddieV on Jan 29, 2008 12:10 PM

# re: Extension Method - String.ToFixedLength
Requesting Gravatar...
EddieV - calling any method on a null string will throw a null ref exception. Why should I trap that exception? The calling code needs to handle that exception. I don't know what that code wants to do with a null value. Plus, if I did handle the exception, what should I do with it? Swallow it? Initialize it to an empty string? It is not my place to decide what to do.

It is my personal preference to create a return value variable (rv). I feel that it makes the code cleaner.
Left by Tim Hibbard on Jan 29, 2008 12:46 PM

Your comment:
 (will show your gravatar)

Copyright © Tim Hibbard | Powered by: