Implementing IFormattable To Create Customizable ToString Options in C#

  Рет қаралды 9,354

IAmTimCorey

IAmTimCorey

2 ай бұрын

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...
Patreon: / iamtimcorey
Mailing List: signup.iamtimcorey.com/

Пікірлер: 55
@jannickbreunis
@jannickbreunis 2 ай бұрын
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 2 ай бұрын
I'm glad.
@sulmarpl
@sulmarpl 2 ай бұрын
Thank you Tim. I'm pleasantly surprised. An elegant solution at your fingers.
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
You are welcome.
@lyudmilpetrov79
@lyudmilpetrov79 2 ай бұрын
Thanks Tim for sharing and all the best
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
You are welcome.
@mmbow7484
@mmbow7484 2 ай бұрын
Thank you for this video.
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
You are welcome.
@alialshreef2874
@alialshreef2874 2 ай бұрын
Thanks Tim.
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
You are welcome.
@brendanalexander6053
@brendanalexander6053 2 ай бұрын
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 2 ай бұрын
Thanks for sharing!
@putte954
@putte954 2 ай бұрын
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.
@webluke
@webluke 2 ай бұрын
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 2 ай бұрын
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.
@lorenzogaruglieri7046
@lorenzogaruglieri7046 2 ай бұрын
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 2 ай бұрын
No, I just use dark mode and I have the built-in option of colorizing the curly braces turned on.
@lorenzogaruglieri7046
@lorenzogaruglieri7046 2 ай бұрын
many thx @@IAmTimCorey
@MEGAFOXTERRIER
@MEGAFOXTERRIER 2 ай бұрын
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 2 ай бұрын
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 2 ай бұрын
@@IAmTimCorey Just did! Thanks for letting me know about the suggestions site!
@hugebug4ever
@hugebug4ever Ай бұрын
helpful!
@IAmTimCorey
@IAmTimCorey Ай бұрын
I am glad.
@TheNoar12
@TheNoar12 2 ай бұрын
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 2 ай бұрын
Yes, you can use the /// comments to add documentation.
@pertyslick6171
@pertyslick6171 2 ай бұрын
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 2 ай бұрын
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 2 ай бұрын
@@IAmTimCorey Thank you for the response. I appreciate your time.
@bdnzor
@bdnzor 2 ай бұрын
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 2 ай бұрын
Stay tuned...😉
@harrisonwell1719
@harrisonwell1719 Ай бұрын
Hi Tim, are you still updating the C# master course?
@IAmTimCorey
@IAmTimCorey Ай бұрын
I am.
@lyudmilpetrov79
@lyudmilpetrov79 2 ай бұрын
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 2 ай бұрын
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 2 ай бұрын
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
@sanampakuwal
@sanampakuwal 2 ай бұрын
Please create a one making in use of IFormatProvider
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
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/
@holger_p
@holger_p 2 ай бұрын
The meaning of the formatProvider stays unhandled ? It's just there, cause the interface is defined this way ?
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
We did not use it in this video, yes. And yes, it is part of the interface definition.
@NorbertOlah
@NorbertOlah 2 ай бұрын
maybe I'd do this token thing with string replace or regex. easier to read. (however, the for loop maybe performs better)
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
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 2 ай бұрын
What about regex though?
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
Regex wouldn't solve the issue any better, plus it would be more expensive.
@SanderEvers
@SanderEvers 2 ай бұрын
In your second example you could just remove the entire if statement. It would still return the same.
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
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 2 ай бұрын
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 2 ай бұрын
@@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 2 ай бұрын
@@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-ly8iq6lm7o 2 ай бұрын
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 2 ай бұрын
Because spaces aren’t always a separator. For example, TCorey (FLL) is valid. Also, M. would be an unknown operator, but a common selection.
Why Can't I Get A Job As A Software Developer?
34:04
IAmTimCorey
Рет қаралды 9 М.
АВДА КЕДАВРАААААА😂
00:11
Romanov BY
Рет қаралды 8 МЛН
GADGETS VS HACKS || Random Useful Tools For your child #hacks #gadgets
00:35
How to open a can? 🤪 lifehack
00:25
Mr.Clabik - Friends
Рет қаралды 9 МЛН
Dependency Injection Updates in .NET - Keyed Implementations
8:31
Collection Expressions in .NET 8
6:34
IAmTimCorey
Рет қаралды 12 М.
Access DevCon 2024 - You Can REALLY Do All That With Forms?
50:49
Karl Donaubauer
Рет қаралды 481
What Are Some Major Mistakes Developers Make in Their Career?
37:32
Старейшая нерешённая задача [Veritasium]
30:08
Master C# Interfaces in 12 Minutes - Beginner Tutorial
11:37
tutorialsEU - C#
Рет қаралды 13 М.
What is Span in C# and why you should be using it
15:15
Nick Chapsas
Рет қаралды 244 М.
Make Your LINQ Up to 10x Faster!
11:08
Nick Chapsas
Рет қаралды 51 М.
Every New Feature Added in C# 12
14:19
Nick Chapsas
Рет қаралды 145 М.
Properties were getting even cleaner in C# 11
8:12
Nick Chapsas
Рет қаралды 56 М.
АВДА КЕДАВРАААААА😂
00:11
Romanov BY
Рет қаралды 8 МЛН