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 trialRemco de Wilde
9,864 PointsAdd 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?
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
Alexander La Bianca
15,959 Pointsusing 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;
}
i6ze5srftzgi8o5iu46z5etr
6,931 Pointsusing 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
37,739 Pointshttps://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
9,864 PointsOke i understand the function of override, but why override string?
I mean the function of this to string method.
Alexander La Bianca
15,959 PointsYou are not overriding string. string is just the return type of the ToString() method. You are overriding ToString() of the Object class.