Re: Formatted object properties with ToString() method

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Hi Göran,

the way you use a regular expression to derive a format string is nice. But
doing it like this, you need to know the class properties at design time and
have to maintain a lookup array as well as a custom fitting String.Format()
method by hand - where I wanted an approach to have ToString(string
PlaceholderString) generally working even in derived classes with completely
new, unforeseen members!
Maybe I mix my implementation with your code to create the props and
String.Format() args arrays dynamically via reflection and benefit from the
cool Regex appeal. ;-)

Well, it appears like reflection is the tradeoff for the flexibility I need
and there will hardly be a much more efficient (=faster, reliable, easy on
resources *and* easy to maintain) way to do this.

Thanks for your input,
Hans


"Göran Andersson" <guffa@xxxxxxxxx>:

How about this:

string[] props = new string[] { "FirstName", "LastName", "Birthday" };
string format = Regex.Replace(PlaceHolderString, @"\{(\w+)\}",
delegate(Match m) { for (int i = 0; i < props.Length; i++) if
(m.Groups[1].Value == props[i]) return "{" + i.ToString() + "}"; return
m.Value; });
return string.Format(format, FirstName, LastName, Birthday);

Just add the names of the properties in the array and in the Format call.



.



Relevant Pages

  • Re: Class question. Where am I going wrong?
    ... public $row5 = &new row; ... Why are creating so many properties instead an array of them? ... on objects and I am losing my mind:) What is the reasoning behind why ... default class properties only being a string, number, or array? ...
    (comp.lang.php)
  • libintl.h not found
    ... cisco_ios.l:76: warning: Array size smaller than format string size ...
    (comp.unix.bsd.openbsd.misc)
  • Re: Class question. Where am I going wrong?
    ... public $row5 = &new row; ... class since this code errors. ... I dont know why I am not using an array. ... default class properties only being a string, number, or array? ...
    (comp.lang.php)
  • Re: MSHFlexgrid displayed value
    ... data, one for my array, and one for the grid, which means using double the ... >> get the format string, and display the value to the user. ...
    (microsoft.public.vb.controls)
  • Re: Faster way of making long string?
    ... I tested your suggestion with a format string for 16 numbers by modifying ... v: array of TVarRec; ... {set up a value capable of being passed to FormatBuf's sarray of const ... > puts the converted chars into that. ...
    (alt.comp.lang.borland-delphi)