C# ASP.NET MVC Basics Modeling and Presenting Data Creating a Data Model

Rachel Xie
Rachel Xie
5,824 Points

When adding data model, how to add parentheses to a variable?

As in my code, I use "("+Publisher+")" to put parentheses out of Publisher. Is there anything wrong? Or any better way to achieve it? Thank you very much

VideoGame.cs
namespace Treehouse.Models
{
   public class VideoGame
    {
        public int Id {get;set;}
        public string Title {get;set;}
        public string Description {get;set;}
        public string[] Characters {get;set;}
        public string Publisher {get;set;}
        public string DisplayText 
        {
            get{
            return Title + "("+ Publisher+")";
               }
        }
    }
}

1 Answer

andren
andren
28,360 Points

The problem with your solution is more a formatting issue than a code issue, with your code you would end up with a string like "Super Mario 64(Nintendo)" rather than "Super Mario 64 (Nintendo)". Due to the fact that you have not placed any space between the title and starting parenthesis.

You can solve this issue either by adding a new string that just contains a space, like this:

return Title + " " + "("+ Publisher+")";

Or you can just add a space in the starting parenthesis string, like this:

return Title + " ("+ Publisher+")";

As for a better solution, I personally have always preferred string interpolation over string concatenation. With string interpolation you create a formatted string that has placeholders that automatically gets replaced with the contents of variables. In C# the most convenient form of string interpolation in my opinion is using the $ syntax like this:

return $"{Title} ({Publisher})";

The way that works is that you place a $ before a string and then you place {} marks around the names of variables that you want to place in the string, string interpolation is a powerful string formatting feature that can do far more than just place variables in a string, but that is what I usually use it for.

Now my preference for string interpolation is just that, a preference. I'm not claiming it is superior to string concatenation in any way, you should use whatever feels more natural to you. It's also worth noting that most treehouse exercises will probably expect you to use string concatenation for these types of task. So it might not pass your code if you use string interpolation, even if the code is valid due to how picky the code checker can be.

Though in the case of this challenge using string interpolation is accepted as a valid solution

Rachel Xie
Rachel Xie
5,824 Points

Thank you, Andren! The answer is so specific and detailed. I've learned it both practical and theoretical ways.