473,396 Members | 2,108 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Formatted object properties with ToString() method

Hi group,

let's say I have a 'Person' class with properties like 'FirstName',
'LastName', 'Birthday' and so on. Now I overload the 'Person' ToString()
method with an implementation ToString(string PlaceholderString) of the
following purpose:

When someone calls ToString("{LastName}, {FirstName}") on a given Person
instance, the expected result is e.g. "Doe, John" for this object, that is:
Any {property placeholder} is replaced by the actual instance value.
Furthermore, the ToString(string PlaceholderString) implementation is
intended to work with arbitrary properties on any class, without knowing the
members before.

I've achieved this with reflection: When ToString(string PlaceholderString)
is called, I loop over the type members to fetch the currently available
member/value pairs. In the same run, I do simple StringBuilder replacements
of requested {property placeholder} values within the user given
PlaceholderString and finally hand the replacement result out.

The whole thing works fine, I'm just asking myself: Is there a
better/faster/more efficient way to do this? Or did I reinvent the wheel and
there is an unknown .NET method with exactly the same function already?

Any hint is greatly appreciated.

Best regards,
Hans
Jun 27 '08 #1
9 2831
The whole thing works fine,
have you tried how expensive this is in a loop? like when doing
databinding? Reflection in general is an expensive proposition that
should be used with care.
I'm just asking myself: Is there a
better/faster/more efficient way to do this?
not with those requirements,

Of course it should be trivial (only a few more keystrokes) to call
String.Format("{0}, {1}") , FirstName, LastName)
>Or did I reinvent the wheel and
there is an unknown .NET method with exactly the same function already?
only the above mentioned String.Format and frankly I do not see the
need of another option

what is superior in your method than using String.Format?
Jun 27 '08 #2
>
what is superior in your method than using String.Format?
I'm going to answer that myself :)

The only advantage is that you can get that string from an external
source (like a DB or a config file)
Jun 27 '08 #3
Reflection in general is an expensive proposition that
should be used with care.
There are ways around this performance hit in the general case...

In this /specific/ case, I suspect the formatting etc will eat a
comparable amount of CPU, so I won't bother posting the details - but it
can be done ;-p More for things like bulk export/import...

Marc
Jun 27 '08 #4
You name it - this is exactly one of our use cases where we'd have external,
user created XML/HTML templates with content like "<div>Hello {Salutation}
{LastName}, ...</div>"!
I want to send them through the mentioned ToString() overload without caring
about the actual members of the target class.

Yes, I know that reflection is expensive. Therefore I wondered if there may
be an optimized way to get this kind of instance self-information for my
purpose.

Regards,
Hans
"Ignacio Machin ( .NET/ C# MVP )" <ig************@gmail.comschrieb im
Newsbeitrag
news:32**********************************@w1g2000p rd.googlegroups.com...

what is superior in your method than using String.Format?

I'm going to answer that myself :)

The only advantage is that you can get that string from an external
source (like a DB or a config file)

Jun 27 '08 #5
I'm going to answer that myself :)
>
The only advantage is that you can get that string from an external
source (like a DB or a config file)
Another one: localization.
When a translator gets "To {0} {1}" he has no clue what the heck this is all
about. "To {firstName} {lastName}" is self-explanatory.
--
Mihai Nita [Microsoft MVP, Visual C++]
http://www.mihai-nita.net
------------------------------------------
Replace _year_ with _ to get the real email
Jun 27 '08 #6
Hans-Jürgen Philippi wrote:
Hi group,

let's say I have a 'Person' class with properties like 'FirstName',
'LastName', 'Birthday' and so on. Now I overload the 'Person' ToString()
method with an implementation ToString(string PlaceholderString) of the
following purpose:

When someone calls ToString("{LastName}, {FirstName}") on a given Person
instance, the expected result is e.g. "Doe, John" for this object, that is:
Any {property placeholder} is replaced by the actual instance value.
Furthermore, the ToString(string PlaceholderString) implementation is
intended to work with arbitrary properties on any class, without knowing the
members before.

I've achieved this with reflection: When ToString(string PlaceholderString)
is called, I loop over the type members to fetch the currently available
member/value pairs. In the same run, I do simple StringBuilder replacements
of requested {property placeholder} values within the user given
PlaceholderString and finally hand the replacement result out.

The whole thing works fine, I'm just asking myself: Is there a
better/faster/more efficient way to do this? Or did I reinvent the wheel and
there is an unknown .NET method with exactly the same function already?

Any hint is greatly appreciated.

Best regards,
Hans
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.

--
Göran Andersson
_____
http://www.guffa.com
Jun 27 '08 #7
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" <gu***@guffa.com>:
>
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.


Jun 27 '08 #8
and there will hardly be a much more efficient (=faster, reliable, easy on
resources *and* easy to maintain) way to do this.
Efficiency is tricky to define ;-p

For example, HyperDescriptor is significantly quicker at execution
(especially if you re-use the PropertyDescriptorCollection), but has
to generate a dynamic assembly on the fly, so bigger footprint (not by
much). Identical from a maintenance perspective.

http://www.codeproject.com/KB/cs/Hyp...escriptor.aspx
[this is what I hinted at previously, but didn't post...]

Marc
Jun 27 '08 #9
Hi Marc,
Efficiency is tricky to define ;-p
Yep, definitely true. :-)

For example, HyperDescriptor is significantly quicker at execution
(especially if you re-use the PropertyDescriptorCollection), but has
to generate a dynamic assembly on the fly, so bigger footprint (not by
much). Identical from a maintenance perspective.

http://www.codeproject.com/KB/cs/Hyp...escriptor.aspx
[this is what I hinted at previously, but didn't post...]
Thanks for pointing me to this, I didn't know it before and it looks pretty
interesting. Don't be too modest, doing good things and not speaking about
it! ;-)
Greetings,
Hans
Jun 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Fabian | last post by:
I have a three tier nested array, used to define a map for a javascript game, and can be edited within the web page. Is there a way I can generate a visible copy of this array that I can then c&p...
7
by: Brian Genisio | last post by:
Hi all, Does anyone know of a way in IE to determine the prototype name of an object? For instance, in Mozilla, I can say: junk = document.getElementById("myID"); alert(junk.toString());
54
by: tshad | last post by:
I have a function: function SalaryDisplay(me) { var salaryMinLabel = document.getElementById("SalaryMin"); salaryMinLabel.value = 200; alert("after setting salaryMinLabel = " +...
16
by: sneill | last post by:
How is it possible to take the value of a variable (in this case, MODE_CREATE, MODE_UPDATE, etc) and use that as an object property name? In the following example I want 'oIcon' object to have...
6
by: Alex Sedow | last post by:
Example 1 interface I { string ToString(); } public class C : I { public void f() {
7
by: Martin Robins | last post by:
I am currently looking to be able to read information from Active Directory into a data warehouse using a C# solution. I have been able to access the active directory, and I have been able to return...
2
by: JSheble | last post by:
I have a method in my class that needs to return formatted XML, with the carriage returns, linefeeds, and tabs... However, when I return oXml.OuterXml, the Xml is not formatted... Every example...
4
by: Brandon Miller | last post by:
All, I have an existing business object (VB.Net) which returns user IDs for our locations in our regions. One of the properties objReg.Manager returns the manager's user id (integer) for a given...
12
by: Andrew Poulos | last post by:
With the following code I can't understand why this.num keeps incrementing each time I create a new instance of Foo. For each instance I'm expecting this.num to alert as 1 but keeps incrementing. ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.