Implementing IFormattable To Create Customizable ToString Options in C#

The ToString method allows you to determine what the string representation of your object is going to be. For instance, you might override the ToString method to return a user's full name from a Person model. However, what if you want to allow for multiple different ToString options.
DateTime allows this by passing in a formatting string. We can do the same using the IFormattable interface provided by .NET. In this video, we will look at how to implement the IFormattable interface, as well as how to parse complex custom formatting strings.
Full Training Courses: IAmTimCorey.com
Source Code: leadmagnets.app/?Resource=IFo...
Mailing List: signup.iamtimcorey.com/

Пікірлер: 55

  • @jannickbreunis
    @jannickbreunis3 ай бұрын

    I recognize the steps you're going through, moving the upper to top and using the second ToString() inside the first ToString(). You taught me well!

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    I'm glad.

  • @sulmarpl
    @sulmarpl3 ай бұрын

    Thank you Tim. I'm pleasantly surprised. An elegant solution at your fingers.

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    You are welcome.

  • @lyudmilpetrov79
    @lyudmilpetrov793 ай бұрын

    Thanks Tim for sharing and all the best

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    You are welcome.

  • @Mmbow
    @Mmbow3 ай бұрын

    Thank you for this video.

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    You are welcome.

  • @putte954
    @putte9543 ай бұрын

    Great video, are you planning to make a video to add the tooltip/docstring information for the IDE?

  • @IAmTimCorey

    @IAmTimCorey

    2 ай бұрын

    Maybe, depending on interest.

  • @brendanalexander6053
    @brendanalexander60533 ай бұрын

    Good vid. I would probably create a value object to help remember the format type strings because for sure I will forget what set as the magic format strings. Example: MyPersonStringFormat.General.Value == “G”

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    Thanks for sharing!

  • @alialshreef2874
    @alialshreef28743 ай бұрын

    Thanks Tim.

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    You are welcome.

  • @webluke
    @webluke3 ай бұрын

    Lots of good stuff in this video! Is it good to add a break on the switch statements, even though you return? Also, wouldn't it be ok to not include the if statement checking if null or G since that should be handled on the default?

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    I've done it in the past just to follow the same pattern, but no, the break is not needed and doesn't add any value if you return from inside the case/default in your switch statement. As for not including the if statement, yes, I could have done that.

  • @MEGAFOXTERRIER
    @MEGAFOXTERRIER3 ай бұрын

    Hey Tim, by any chance do you think you could please make a video on Filter attributes for ASP NET Core Web API: ActionFilterAttribute ExceptionFilterAttribute ResultFilterAttribute FormatFilterAttribute ServiceFilterAttribute TypeFilterAttribute I'd really appreciate it! Thanks for all your content, keep up the great work!

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @MEGAFOXTERRIER

    @MEGAFOXTERRIER

    3 ай бұрын

    @@IAmTimCorey Just did! Thanks for letting me know about the suggestions site!

  • @lorenzogaruglieri7046
    @lorenzogaruglieri70463 ай бұрын

    Hi Tim, Your code color setup is gorgeous. Especially the separation of parentheses and braces. Is there any special setup around to set all those colors or does it have to be set manually? Thanks in advance Lorenzo

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    No, I just use dark mode and I have the built-in option of colorizing the curly braces turned on.

  • @lorenzogaruglieri7046

    @lorenzogaruglieri7046

    3 ай бұрын

    many thx @@IAmTimCorey

  • @TheNoar12
    @TheNoar123 ай бұрын

    Thanks for this video. I have a question. When we do a ToString() on a DateTime for example intellisense prompt us with a list of usable "token" with their meaning. Is there a way to document the code to offer such display of the user of our class (in an equivalent manner we can do to write an inline documentation by using /// on top of class element)?

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    Yes, you can use the /// comments to add documentation.

  • @bdnzor
    @bdnzor3 ай бұрын

    Hey Tim, Did you say a while back the monthly pass is being fixed up to possibly be open a lot more often? Would be handy, always opens when I can't afford it.

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    Stay tuned...😉

  • @pertyslick6171
    @pertyslick61713 ай бұрын

    Hi Tim, this was a great video. I have a question though. In the case of a format like "FF MM LL" how would you handle the middle name if it were a null value? The obvious answer is to insert nothing for the middle name in the final result, but then you would also have a double space in between the first and last names. Should/would this toString typically be expected to handle that?

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    If I were to clean this up for a rock-solid production setup, I would put checks around null values. I might even throw an exception if they asked for a middle name and it was null. It all depends on the situation. But yes, I would do something. There might be a case for removing the extra space if the middle name was null. I would also be doing null checks and length checks to be sure that someone didn't put in an empty string. Otherwise, we would get an exception when asking for the first character (which might be ok as well, but it is something to consider).

  • @pertyslick6171

    @pertyslick6171

    3 ай бұрын

    @@IAmTimCorey Thank you for the response. I appreciate your time.

  • @hugebug4ever
    @hugebug4ever2 ай бұрын

    helpful!

  • @IAmTimCorey

    @IAmTimCorey

    2 ай бұрын

    I am glad.

  • @holger_p
    @holger_p3 ай бұрын

    The meaning of the formatProvider stays unhandled ? It's just there, cause the interface is defined this way ?

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    We did not use it in this video, yes. And yes, it is part of the interface definition.

  • @sanampakuwal
    @sanampakuwal3 ай бұрын

    Please create a one making in use of IFormatProvider

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @lyudmilpetrov79
    @lyudmilpetrov793 ай бұрын

    Question, is it going to be faster to use Replace where "FF" replace with full name and after that "F" replace with first letter and then move onto Last name and so on, by the away presentation is excellent all the best

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    No, because that will not work correctly. Imagine the first name is Larry and a last name of Peters. Now you do a FF replacement and put Larry in its place. Everything looks fine until you do the replacement for L. Because Larry is already in the string, you will get Parry instead. You have to go in order from left to right, replacing one token at a time.

  • @lyudmilpetrov79

    @lyudmilpetrov79

    3 ай бұрын

    I meant replacing the pattern for example "LL F" should yield first letter of last name and full name of first name, and if you replace your letter requirements with numbers for example F = 1 L = 2, M(for middle = 3) and so on Title = 4. then the in the code the pattern is becoming from "LL F" = "22 1" and then the just start replacing the doubles first 22 with, but anyway just thinking aloud @@IAmTimCorey

  • @harrisonwell1719
    @harrisonwell17192 ай бұрын

    Hi Tim, are you still updating the C# master course?

  • @IAmTimCorey

    @IAmTimCorey

    2 ай бұрын

    I am.

  • 3 ай бұрын

    maybe I'd do this token thing with string replace or regex. easier to read. (however, the for loop maybe performs better)

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    No, because that will not work correctly. Imagine the first name is Larry and a last name of Peters. Now you do a FF replacement and put Larry in its place. Everything looks fine until you do the replacement for L. Because Larry is already in the string, you will get Parry instead. You have to go in order from left to right, replacing one token at a time.

  • @brettr8263

    @brettr8263

    3 ай бұрын

    What about regex though?

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    Regex wouldn't solve the issue any better, plus it would be more expensive.

  • @SanderEvers
    @SanderEvers3 ай бұрын

    In your second example you could just remove the entire if statement. It would still return the same.

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    Technically yes, I could have done that. I like seeing the null/G handled specifically, but I could have put that in the switch.

  • @Assgier

    @Assgier

    3 ай бұрын

    I would at least refactor out the default format into a specific method so that it can be reused on both lines. But organizing the code is beyond the purpose of this video.

  • @SanderEvers

    @SanderEvers

    3 ай бұрын

    @@IAmTimCorey Handling the null/G separately is nice, but it goes against two best practices: 1. If and Switch should not be used on the same variable. Since you have format == "G" and switch(format) that goes against the best practice. 2. You should never return the same result twice. Which you do with the return "{FirstName} {LastName}". So you could have done a "format = string.IsNullOrWhiteSpace(format) ? "G" : format.ToUpper() or just leave it as format?.ToUpper in the switch statement. Because less variables > better.

  • @SanderEvers

    @SanderEvers

    3 ай бұрын

    @@Assgier The purpose of the video is to help people learn how to use IFormattable correctly. I made a .NET fiddle with my example, which I also commented but that sadly got deleted.

  • @user-ly8iq6lm7o
    @user-ly8iq6lm7o3 ай бұрын

    Why not just split the format string into its tokens, i.e. void Main() { string format = "T FF M LL"; var tokens = format.Split(' '); var person = new Person() { Title = "Mr.", FirstName = "Tim", MiddleName = "NotTelling", LastName = "Corey" }; StringBuilder output = new StringBuilder(); foreach(var token in tokens) { switch(token) { case "T": output.Append(person.Title); break; case "F": output.Append(person.FirstName[0]); break; case "FF": output.Append(person.FirstName); break; case "L": output.Append(person.LastName[0]); break; case "LL": output.Append(person.LastName); break; case "M": output.Append(person.MiddleName[0]); break; case "MM": output.Append(person.MiddleName); break; } output. Append(" "); } output. Dump(); } Mr. Tim N Corey is output This will reduce the processing substantially.

  • @IAmTimCorey

    @IAmTimCorey

    3 ай бұрын

    Because spaces aren’t always a separator. For example, TCorey (FLL) is valid. Also, M. would be an unknown operator, but a common selection.

Келесі