Tim Hibbard

Software Architect for EnGraph software


News





Add to Google





My Stats

  • Posts - 593
  • Comments - 446
  • Trackbacks - 507

Twitter












Tag Cloud


Recent Comments


Recent Posts


Article Categories


Archives


Post Categories


Image Galleries


EnGraph Blogs


Links


Other


Roll



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 @ Tuesday, January 29, 2008 11:09 AM | Filed Under [ .NET ]

Comments

Gravatar # re: Extension Method - String.ToFixedLength
Posted by EddieV on 1/29/2008 12:10 PM
Aren't you missing a check for null before you access s? Assigning s to rv also seems unnecessary to me.
Gravatar # re: Extension Method - String.ToFixedLength
Posted by Tim Hibbard on 1/29/2008 12:46 PM
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.
Post a comment





 

Please add 4 and 3 and type the answer here: