A Little Refactoring: That Ugly Get


I posted for help on converting the newlines ArrayList to an array of String and got a reply that showed how to do it. The trick was the typeof function, which I had forgotten about since C days so long ago. I promised to fix it when I learned a better way and had nothing else to do after dinner, so I decided to clean up the code a bit more. Remember that we had this:

 public String[] Lines { 
get {
// there must be a way to cast this??
String[] textlines = new String[newlines.Count];
for (int i = 0; i < newlines.Count; i++) {
textlines[i] = (String) newlines[i];
}
return textlines;
}
set {
lines = new ArrayList(value);
newlines = lines;
}
}

It s that ugly get of the Lines property that I m trying to fix. Sure enough, this approach works just fine:

 public String[] Lines { 
get {
return (String[]) lines.ToArray(typeof(String));
}
set {
lines = new ArrayList(value);
}

You would think that a reasonable language wouldn t have needed two hints that both say, Hey, this is an array of strings. Still, this is much better.




Extreme Programming Adventures in C#
Javaв„ў EE 5 Tutorial, The (3rd Edition)
ISBN: 735619492
EAN: 2147483647
Year: 2006
Pages: 291

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net