user2043401
user2043401

Reputation: 1

Why the output textbox doesn't show the return value my function gives?

I intend to show the results in the textbox. My code is like this:

private void run_Click(object sender, EventArgs e)
{
    GeneticAlgorithm MyGeneticAlgorithm = new GeneticAlgorithm();
    GeneticAlgorithm.GAoutput ShowResult = MyGeneticAlgorithm.GA();

    string output;

    output = ShowResult;

    this.Output.Text = output;
}

class GeneticAlgorithm
{
    public void reset()
    {
        MessageBox.Show("fine");
    }
    public void Initial()
    {
        MessageBox.Show("Good");
    }
    public class GAoutput
    {
        public string Generation;
    }
    public GAoutput GA()
    {
        GAoutput OneGeneration = new GAoutput();
        OneGeneration.Generation = "bad";
        return OneGeneration;
    }
}

after running, it gives me results as: WindowsFormsApplication1.GeneticAlgorithm+GAoutput

Anyone can help me? thank you so much!

Upvotes: 0

Views: 142

Answers (2)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107498

Your ShowResult variable is not a string, so when you assigned it to one, .NET implicitly converted it into a string. Since there was no ToString() method, it gave you the generic type definition string instead ("WindowsFormsApplication1.GeneticAlgorithm+GAoutput").

It looks like you want to output the Generation field, which is a string, so just change:

output = ShowResult;

to

output = ShowResult.Generation;

and it should start working.

Also, if you aren't planning on doing much else to get a new Generation, you could really shorten up that code, all the way down to:

this.Output.Text = (new GeneticAlgorithm()).GA().Generation;

You might also want to think about keeping a local instance of GeneticAlgorithm so you don't have to keep creating new instances.

Upvotes: 2

Matthew Watson
Matthew Watson

Reputation: 109547

You must decide what string to return for instances of those classes.

Then override the ToString() method for each of those classes to return the appropriate string.

Upvotes: 0

Related Questions