Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# Intermediate C# System.Object Object.ToString

Remco de Wilde
Remco de Wilde
9,864 Points

Add a ToString method to the VocabularyWord class that returns the word. Don't understand the question

I don't understand what has to be build?

VocabularyWord.cs
using System;
namespace Treehouse.CodeChallenges
{
    class VocabularyWord
    {
        public string Word { get; private set; }

        public VocabularyWord(string word)
        {
            Word = word;
        }
        public string VocabularyWordToString(string word)
        {
            Word = word.ToString();
            return Word;
        }
    }
}

4 Answers

using System;
namespace Treehouse.CodeChallenges
{
    class VocabularyWord
    {
        public string Word { get; private set; }

        public VocabularyWord(string word)
        {
            Word = word;
        }
        public string ToString()
        {
            return Word;
        }
    }
}

So you can do

VocabularyWord word = new VocabularyWord("House");
string vocab = word.ToString()   //Will return "House" so vocab = "House"

The ToString() method is usually overidden in your classes since it is defined in the Object class.

So a correct way to define a ToString() method would be

public override string ToString()
{
    return Word;
}
using System;
namespace Treehouse.CodeChallenges
{
    class VocabularyWord
    {
        public string Word { get; private set; }

        public VocabularyWord(string word)
        {
            Word = word;
        }
        public override string ToString()
        {
            return Word;
        }
    }
}

Ā“Ā“Ā“
Andrew Winkler
Andrew Winkler
37,739 Points

https://msdn.microsoft.com/en-us/library/system.object.tostring(v=vs.110).aspx

I don't really get this.. It already returns a string type value. Why do we need to override it??

The syntax on the MSDN page is:

public virtual string ToString()
Remco de Wilde
Remco de Wilde
9,864 Points

Oke i understand the function of override, but why override string?

I mean the function of this to string method.

You are not overriding string. string is just the return type of the ToString() method. You are overriding ToString() of the Object class.