Tim Hibbard

Software Architect for EnGraph software
posts - 615, comments - 676, trackbacks - 469

My Links

News



Add to Google




Twitter












Tag Cloud

Article Categories

Archives

Post Categories

Image Galleries

EnGraph Blogs

Links

Other

Roll

Extension Method - String.ToFixedLength

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: , ,

Print | posted on Tuesday, January 29, 2008 11:09 AM | Filed Under [ .NET ]

Feedback

Gravatar

# re: Extension Method - String.ToFixedLength

Aren't you missing a check for null before you access s? Assigning s to rv also seems unnecessary to me.
1/29/2008 12:10 PM | EddieV
Gravatar

# re: Extension Method - String.ToFixedLength

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.
1/29/2008 12:46 PM | Tim Hibbard
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 

Powered by: