Reflection, Custom Attributes, Inheritance Advice Needed

L

Lee

I need to implement a custom ToString method for derived classes.

The method should return a string that is the result of concatenating the
results of a ToString on each of the fields in the class. Individual fields
can specify a custom attribute [Format=string] to allow for custom
formatting of values.

I think I know enough to implement this but if someone already has a sample
of something similar I would appreciate it.

My questions are these:

1. Once I create the method, how do I share it?
2. Can I put this in a base class and inherit this implementation?
3. Would inheritance be easier if the method name was not ToString but
perhaps Format?
4. What must I do to insure the fields are concatenated in the order they
are specified in the source?

TIA

Lee
 
C

Charles Calvert

I need to implement a custom ToString method for derived classes.

The method should return a string that is the result of concatenating the
results of a ToString on each of the fields in the class. Individual fields
can specify a custom attribute [Format=string] to allow for custom
formatting of values.

I think I know enough to implement this but if someone already has a sample
of something similar I would appreciate it.

My questions are these:

1. Once I create the method, how do I share it?

What do you mean by "share"? You can make it public so that any class
with an instance of your derived class can access it.
2. Can I put this in a base class and inherit this implementation?

Yes, but remember that C# only supports single inheritance, so you
can't do something convenient like stick in in a utility class and
then inherit it whereever you need it.
3. Would inheritance be easier if the method name was not ToString but
perhaps Format?

Probably not.
4. What must I do to insure the fields are concatenated in the order they
are specified in the source?

That I'm not sure about.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top