Overloading and Arrays

G

Guest

I have some custom types and have overloaded the tostring method so i can print it out and get a description of the contenet of the object for debugging purposes not just the default type
however when i have an array of the objects it just uses the type, so where do i overload the tostring for an array of objects

e

class myTyp

public string name

public override string ToString(

return "{" + base.ToString() + "} " + name



myType x = new myType()
x.name = "test"

myType[] y = new myType[10]

//... set name for each on

Console.Writeline(x.ToString())
Console.Writeline(y.ToString())

---
output
{myType} tes
myType[

how can i alter the 2nd tostring output?
 
N

n!

Console.Writeline(x.ToString());
Console.Writeline(y.ToString());

You are calling 'ToString()' on the array itself rather than your class
'myType'.

myType x = new myType();
x.name = "test";

myType[] y = new myType[] { x };

Console.WriteLine( x.ToString() );
Console.WriteLine( y[ 0 ].ToString() );

Should give you the correct output.

n!
 
G

Guest

im calling it on the array as at runtime i dnt know if anything is an object or an array of objects so i want to overload the tostring on the array so it will print out the indevidual objects for me so i dnt have to check what it is
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

You could inherit from Array and override the ToString() method,
unfortunally only the compiler can do that, so you cannot change the default
behavior of it

What you can do is use another object to store the collectoin of objects,
you can use for example ArrayList or a Strong typed collection , all you
have to do is override the ToString() method to whatever you need.


Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Spike said:
im calling it on the array as at runtime i dnt know if anything is an
object or an array of objects so i want to overload the tostring on the
array so it will print out the indevidual objects for me so i dnt have to
check what it is
 

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