I'll have to watch later. Im pretty sure that I know 0 out of 30, lol. Thanks for the free tutorials. They're very much appreciated. Thanks for doing what you do ❤️
Nice video! In literal strings you can use double 'double quotes' to create a single double quote, like @$"My name is""{firstName}""!", which is pretty clean
Good beginners explanation, even I learned a few new things. Let me learn you something: In the comparing strings section when you renamed a few CompareToHelper methods to CompareHelper you can do it quicker by holding the Alt-key and clicking on the first 'T' and dragging the mouse downward selecting the 5 'To's. Then you can delete the selection or replace it with anything you type (it wil get copied 5 times) in short: Vertical selection = alt+mouse
Coming from Python but now working in C# occasionally, this reference is really helpful. I know all the concepts but not their C# syntax. Watching this at 2x speed is a good jump start.
Thanks in a million Corey! Very well explained. This is the nth time that I am watching this again. Great content. Awesome. I couldn't find this explanation--simply put anywhere else. “Great teachers are hard to find”. Grade: A++ 💥
This is a gold mine for any novice. Only 1) literal quote escaping @"This "" is a literal quote" 2) initialize empty strings with a constant and you will not allocate memory var mystr = string.Empty; 3) Over the years I found quotes are pretty inadequate for denoting value boundaries while logging so I use square brackets instead for superior readability. $"Error while downloading [{url}]."
I thoroughly enjoy each and every video I watch. I can't count the things I learned in this video, but by typing along and pausing the video, I have gained some practical knowledge for strings along the way. I will expand on these as I continue to learn. Thanks again for an enlightening couple of hours. I have noticed that sometimes in string interpolation, the space within the curly brackets and the variable/statement gives me an error while trying to use the ternary operator, until I take it out. I can't seem to figure out the pattern consistently.
Thanks Tim, I've been using C# and Net since they first came out but there's always a gem to be found; which is what keeps me playing even your entry-level content. How did I manage to never come across string.Insert ?? - not to mention Remove :) ... my fingers type the substring slice versions on auto-pilot but these are quicker to type, clearer to read, easier to debug and give the compiler a clearer intent so hopefully a better opportunity to optimise, nice.
For string literal, you can do this to embed double quotes (note the two adjacent double quotes): var results = @"This is my ""test"" solution."; Console.WriteLine(results); Granted it starts to get a little ugly for longer strings.
Many thanks for your tutorials, Tim! They are greatly useful! Having listened two dozens of them I noticed I started to say "grab" instead of "take" and to start the phrases with "hey" addressing to my girlfriend )))
I really liked the part for the title casing. The video came just in time. Because I was working on a project where I was parsing a file where everything was lower case and had the _ . I ended up first replacing the _ with a space. Then use the new function from the video to have casing and it worked perfectly.
Thanks for taking so many efforts in sharing this. I found you very dynamic in terms of teaching. It shows the effort you taking in studying as well as sharing the crisp content and topic in your videos. All the topics were interesting but one thing which caught my attention was the use of string interpolation and StringBuilder. In my day to day work I use StringBuilder rarely but would like to use it more frequently not sure about its flexibility compared to string but would like to try for sure
Once again just fine refresher as they say you are the best. Everything worked fine except in two places I had hiccup. First I was not able to do ...CompareToHelper(string testA, string? testB) Visual Studio keep on complaining "The type 'string' must be a non-nullable value type in order to user it as parameter 'T' in the generic type or method 'Nullable' " Yes I changed project XML, anyway I ignored it and went without string testA, string? testB. it worked fine. Second issue happened with replace method I was not able to Replace("works","makes",StringComparison.InvariantCultureIgnoreCase) did not worked, VS complained overload function with 3 parameters is not there. BTW I am using Visual Studio 2017 maybe that has to do something with these problem? Thanks for great video.
I've seen this video before but I just realized something about 36:02. When you say concatenation it's not linear but exponential instead, I think the concept is wrong. You made a loop of 100000 iterations in which you append the i variable. Of course if you run it up until 10000 the last values added to the string are "9999" and "10000". But when you run it up until 100000, you are not factoring by ten, you are appendind until "99999", "100000" etc. The strings you are appendind are larger. That's why it's not linear. To make it an even test you should append the same fix length character on each loop. It's just for consideration. Great videos as usual!
For parsing strings (removing swear words or making sure a file name is safe, or whatever you want) I use regular expressions -> System.Text.RegularExpressions Regex Saves writing many lines of code.
String builder is something I saw online every now and then, but I never looked into why it was used and I am pretty sure I should have used in quite a few places over the years haha.
Thanks for tips especially on string builders and all other string manipulation methods, I never knew string builders can manipulate data very quickly as compared regular strings, and string interpolation and string literals.
A small tip. You can use the Replace also to search for a text and remove it, e.g. testString.Replace("test",""); Thank you for sharing. Most of it I knew, but the Equal thing I did not realize and the Join and Concat have drawn my attention. For comparison, I often use Ordinal versions because they save me from localization trouble. Localization can be very annoying if you want to create software in another language than your local language. (I think the compare is worth a video on its own, there are far more variants)
Note: you can use "range" syntax instead of string.Substring. Example: string str = "abcd"; string a = str[1..]; a will contain "bcd", which is the same as str.Substring(1);
With the StringBuilder, you should probably have included a ToString() within the timer block so both examples end up with a string as output. StartsWith() / EndsWith() accepts a comparison type parameter to not be case sensitive. Wasn't aware of ToTitleCase(). Keep up the good knowledge sharing.
Hi Tim Thanks for putting up this video. I want you to talk about the (DateTime) , and what is the Best practices with saving datetime & timezone info in database when data is dependant on datetime , specially in multi-tenant systems where tenants can use arbitrary timezone. thank you
Great video. I have one tiny remark: capitalization is also culture dependent. fbi to FBI is not guaranteed. In Turkish (tr-tr) you’ll get FBİ for fbi and FBI for fbı.
resultArray = testString.split(" , "); this line is showing syntax error as CS1503 Argument 1: cannot convert from 'string' to 'char' , is it due to .netframework version? mine is 4.6.1
33:41 That's not correct. An uninitialized string is not "en empty string": it is uninitialized, which is an error (CS0165). Even if it was a null object, it would actually not be a problem: Just initialize the object with either =default or =null and the string concatenation will still work. Therefore, the part with "a string with no characters is different then string.Empty" is also not completely right. string.Empty is initialized with "", so can definitely be used here. (It's just that the default initialization of string is not string.Empty, but null) edit: to have a fair comparison, you should have added the test=sb.ToString() evaluation in the stopwatch loop. I mean: what if it did lazy evaluation? The results should be equal (and best compared to check if really so). I know you're right, but in teaching others, details are important. Other thing: for the same reason, string concatenation using + was expensive in the past: for every addition a new string object was created. However, nowadays the compiler is smart enough and will replace the whole expression with pluses by one big concatenation. edit: 1:17:30 please elaborate why you should use "String.Compare" instead of "string.Compare". It seems more a habit/coding style then a real rule. I mean, even MS VS disagrees and gives an IDE style warning IDE0049 "Name can be simplified" from "Use language keywords instead of framework type names for type references (IDE0049)".
Good points. To add more to your first point: A variable is only initialized with its default value when it is a field or property in the scope of a class. If it is a variable within a method, it will not automatically initialize. This is reasonable because there could be scenarios in which you want to define multiple ways to set it. If it is followed up with a if { } else { } statement, in which that variable is set, it will not complain afterwards if it is used. Otherwise its value is not declared. This could be unintentional behavior as well, which sometimes help raise awareness to a logical problem in one's if-else structures. As of fields and properties, they are initialized first (before running the constructor) if their values are set as they are defined. Otherwise it will run the constructor first. And only then it will look which variables have not been set and set them to their default values. When dealing with performance-critical areas, this little detail can result in slight optimizations. In the case of structs this would mean *not* creating an instance of a struct for no reason (struct's default value is an instance created with the parameterless constructor).
Hi and thank you for another amazing video. Is it possible to do a video on how to learn a code base? I mean are there methods and / or tools that you would use to be productive when joining a company? I heard some developers were put on notice when they joined the company, and never recovered from it. The company then just abused them and let them go. Thanks.
@@tomthelestaff-iamtimcorey7597 I am so glad to hear this. I think if anyone can teach this, Tim is that person just b/c he explains all the concerns and surrounding issues and what not. I am so looking forward to this. Thank you so much Tom.
just want to add something, you can also chain the string manipulation method. for example: testString.replace("text1","newText1").replace("text2","newText2");
@@IAmTimCorey the same could be said of escaping quotes when concatenating strings. Don't think it was a valid reason to leave it out of the video though.
Another very helpful video Tim! Looks like the power of these also comes in the combination of functions, e.g. removing specific words by finding the index of the word, then removing x characters. And all this without even mentioning REGEX! Question: When comparing words whilst ignoring case, what are the benefits of InvariantCultureIgnoreCase compared to just using .Lower() on both strings? Faster?
No, sorry. I'm avoiding that in an effort to stay away from misleading people. There are a lot of great things that could come out of Web3, but so far the most common thing to come out of Web3 is unregulated gambling and theft.
I've knew everything but the TitleCase thing. But thanks for that :) I dont really get that nullable feature... string is a reference type under the hood...so it's always nullable.
Yes, but that was a poor implementation of nullable - the compiler never knew if we wanted to allow null. Now with C# 8 and beyond, if we mark a project as nullable, the compiler will not allow us to assign null to a non-nullable string (one without the question mark). This allows us to more easily find errors in our programs. It also allows the system to make suggestions such as doing a null check before using a string.
Use Dapper or EF (which is becoming pretty good) which do it for you. For raw SQL read the MS docs e.g.: docs.microsoft.com / en-us / sql / relational-databases / security / sql-injection
Woohoo 100/100 for me. One thing I like to do is make an extension class for a string type and create a ToTitleCase method that way I can just do myString.ToTitleCase()
You mentioned there where reasons to use String.method(); instead of string.method(); Could you elaborate? I've always heard it was just a different name for the same functionality.
A good reason not to use String instead of string is that String is regular class name and can be overridden by another class named String. However the lowercase "string" is a keyword and cannot mean anything other than System.String
Thanks for the video Tim! Very nice! Are you planning to make more "masterclass" videos about basics of C#? I think that's a very good idea. :) A lot of these I've tried out for my self already. Join method, surprisingly, was something new for me. I've created csv files in the past... a lot of them. I wonder why I never used it before :D Also, never used string builder yet nor equality checks. I know about them but I guess I never had need to use them. Not that I recall at least. Format seems a bit clunky. Love @$ syntax! Very useful.
One thing I struggled with for strings that I did not see covered unfortunately is how to parse out for spacings. I had many cases where I will receive a string that has multiple spaces between words which is wrong. Are there any ways to guarantee that you can send a string to a function and get returned the same string back but guaranteeing that there is only one space between words. Would not matter if the string originally had 10 spaces, 2 or 3, etc. That was one thing i was hoping to see since its very common in the business world. Especially if parsing from websites.
One way is to use Split to cut your string at the spaces with the StringSplitOptions.RemoveEmptyEntries parameter and use Join with one space as separator : string newString = string.Join(' ', originalString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
A small nitpick on 13:40 is that string literals is the general category of strings. By that I mean that everything that is enclosed in double quotes is a string literal. String literals are further separated in 2 categories the typical/regular string literals and the verbatim string literals. The verbatim string literals are those that have a @ before the quotes(what is shown in the video) and do not allow for escaped characters/they perceive the escape character as just the character '\'. So theoretically the accurate definition of what you showed is "verbatim strings" and string literals is the general category. Am I wrong? Also on what I use and know. I knew all of those expect from Title case, which I think is pretty useless. Insert and Replace I knew, but they are pretty useless since I have never used them. I have never used .Equals on strings since this is the 1 thing I really hate from java nor have I used the compare since you do not tend to compare strings, but if you do you can use the typical operators >, =,
Yes, mostly correct. Technically, the “test” string is a quoted string literal. learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#quoted-string-literals
@@IAmTimCorey Interesting I did not know of that definition. Until now I used regular string literals, which seems to be wrong, but in the end of the day we just say strings for everything 😅. On a serious note, I should probably read the official definitions. Thanks for the link.
I am getting an error while using relational operator in switch case or using nullable string. I have tried what Tim has done, editing the project file and still the issue persist. It has something related to the version of C# language which is set to be 7.3 and it is demanding me to upgrade to 8.0. How to do that? Is anyone else getting the same error?
Hi TimThanks for posing this video I was looking for a video to remove escape characters from a text when extract into a csv file. Currently I’m using replace func like text.replace(“ ”,string.empty)so that text fits into a single cell . Just wondering is there any better way of doing.
You could do text.Replace(Environment.NewLine, string.Empty).. This does " " for non-Unix platforms, or " " for Unix platforms without ever having to think about it again :) - docs.microsoft.com/en-us/dotnet/api/system.environment.newline?view=net-5.0 CsvHelper is wonderful for working with .csv files too
Testing matches test unless you figure out more of a filter. The space at the end is a good option. You could try to filter on test and reject those that have an ing but then you would also get tests and testimony and others.
@@IAmTimCorey - I think this works, if (list.Contains("test") == true), but in the end what I'm really after is comparing two lists and finding any exact strings that match. I'll be looking at that tomorrow. Maybe you have another video for that. Thanks.
Since C#8, you can choose to have everything non nullable by default, in which case you have to explicitly state where you want to have a nullable object.
0:00 - Intro
1:10 - Demo console app
4:17 - String to lower case
5:03 - String to upper case
5:21 - Title case
8:37 - String as an array of characters
10:47 - Escape characters
13:24 - String Literal
14:47 - String Concatenation / appending strings:
16:55 - Format()
18:21 - String Interpolation
21:46 - String Concatenation performance
23:19 - Interpolation and Literal
27:47 - String memory and time usage with Concatenation
37:27 - String memory and time usage with StringBuilder
41:30 - Converting Array to String: Concat()
43:09 - Converting Array to String: Join()
44:08 - Converting String to Array: Split()
47:08 - Remove String whitespace: Trim()
50:26 - Padding a String: Pad()
54:34 - Searching methods: StartsWith()
57:46 - Searching methods: EndsWith()
59:37 - Searching methods: Contains()
1:01:18 - Searching methods: IndexOf()
1:04:11 - Searching methods: LastIndexOf()
1:08:30 - Allow nullable Strings in your application
1:10:40 - Comparing Strings: CompareTo() / allows one string to be null
1:16:56 - Comparing Strings: String.CompareTo() / allows both strings to be null
1:20:24 - Comparing String Equality: Equals() and ==
1:29:30 - Retrieve part of a String: Substring();
1:32:40 - Replace part of a String: Replace();
1:37:08 - Insert text in a String: Insert();
1:39:11 - Remove text form a String: Remove();
1:41:40 - Summary and concluding remarks
Thank you!
Thanks 🙏🏾
@@farfaraway2212 Thanks for feedback!
Pn
I'll have to watch later. Im pretty sure that I know 0 out of 30, lol. Thanks for the free tutorials. They're very much appreciated. Thanks for doing what you do ❤️
You are most welcome.
I knew all of these, but this was a very good refresher. It reminded me to use StringBuilder and string interpolation more often.
Great!
As usual another informative video. Great work. Even at my ripe old age of 70 trying to learn something new I could follow along.
Thanks!
I learnt about 3 new methods:
Compare, Insert, Remove
Thanks for the amazing content Mr, Corey
Great!
Thanks Tim. This was a great well structured lesson. Straight to the point. Why can't CS classes be more like this.
Thank you!
I read about StringBuilder being faster but seeing it in action really makes you appreciate it.
Great!
Nice video! In literal strings you can use double 'double quotes' to create a single double quote, like @$"My name is""{firstName}""!", which is pretty clean
Yes, that works, although I'm personally not a fan because of how messy it can get (kind of like the double slashes for a file path).
Good beginners explanation, even I learned a few new things.
Let me learn you something: In the comparing strings section when you renamed a few CompareToHelper methods to CompareHelper you can do it quicker by holding the Alt-key and clicking on the first 'T' and dragging the mouse downward selecting the 5 'To's. Then you can delete the selection or replace it with anything you type (it wil get copied 5 times)
in short: Vertical selection = alt+mouse
Coming from Python but now working in C# occasionally, this reference is really helpful. I know all the concepts but not their C# syntax. Watching this at 2x speed is a good jump start.
I am glad it was helpful.
Thanks in a million Corey! Very well explained. This is the nth time that I am watching this again. Great content. Awesome. I couldn't find this explanation--simply put anywhere else. “Great teachers are hard to find”. Grade: A++ 💥
You are welcome.
Nice to brush up on...do you have a kind of followup video talking about Raw strings on the one hand, and Span slicing on the other hand?
No, I do not.
This is a gold mine for any novice. Only
1) literal quote escaping @"This "" is a literal quote"
2) initialize empty strings with a constant and you will not allocate memory var mystr = string.Empty;
3) Over the years I found quotes are pretty inadequate for denoting value boundaries while logging so I use square brackets instead for superior readability. $"Error while downloading [{url}]."
Thanks for sharing.
string.Empty isn’t a constant, it’s is a read only field. You still still allocate memory but it will be in the string interned memory pool
Thanks Tim, I have been using this on a work project this week. Very helpful and timely. Regards, Fred
Excellent! Thanks for looking to Tim to build your skills.
I thoroughly enjoy each and every video I watch. I can't count the things I learned in this video, but by typing along and pausing the video, I have gained some practical knowledge for strings along the way. I will expand on these as I continue to learn. Thanks again for an enlightening couple of hours. I have noticed that sometimes in string interpolation, the space within the curly brackets and the variable/statement gives me an error while trying to use the ternary operator, until I take it out. I can't seem to figure out the pattern consistently.
Thanks for learning with Tim. Keep practicing!
Gracias! voy a investigar el stringbuiler, parece una herramienta optimizada. Thanks from Argentina!
Thanks for watching and good luck with that.
Thanks Tim, I've been using C# and Net since they first came out but there's always a gem to be found; which is what keeps me playing even your entry-level content. How did I manage to never come across string.Insert ?? - not to mention Remove :) ... my fingers type the substring slice versions on auto-pilot but these are quicker to type, clearer to read, easier to debug and give the compiler a clearer intent so hopefully a better opportunity to optimise, nice.
Excellent! I am glad it was helpful.
I am kind of new to C# and this video helped me I learned some new ways, the one I personally think of as the most useful would be the Split
I am glad it was helpful.
I hadn't used remove before. My favorite was the while loop checking if indexOf > -1. That will end up being very useful. Thank you.
I am glad it was helpful.
For string literal, you can do this to embed double quotes (note the two adjacent double quotes):
var results = @"This is my ""test"" solution.";
Console.WriteLine(results);
Granted it starts to get a little ugly for longer strings.
Yep, and I agree that it gets ugly quick.
@@IAmTimCorey especially if you say it out loud ;). "quote Thing one quote quote thing in quotes quote quote quote." Aaaaaaaaargh!
@@charlesstacyharrisiii2593 Can I quote you on that? 😀
Was just coming to comment this...
That PadLeft() was really helpful for me. It was exactly what I needed right now.
Thanks for trusting Tim to help build your skills.
Thank you Tim, another great video, it worths its length in gold.
You are welcome.
Thank you for enlightening us. It was well appreciated. Keep teaching us!
Thanks for trusting Tim with your time!
Thanks Tim, this was an excellent refresher on Strings
You are welcome.
Thanks for what you are doing Tim. God Bless You
Thank you for supporting him.
You're a living legend man. Thank you for everything !
I appreciate the kind words.
Many thanks for your tutorials, Tim! They are greatly useful! Having listened two dozens of them I noticed I started to say "grab" instead of "take" and to start the phrases with "hey" addressing to my girlfriend )))
🙂
Me - enjoying life
IAmTim - Here's 2 hours of stuff you didn't know you should know.
I know!
@@tomthelestaff-iamtimcorey7597 Every single minute of this video makes me throw-up more when I have to write something in Python.
@@azgan123 How about sharing some constructive feedback. What is it that concerns you? How can we do better?
I really liked the part for the title casing. The video came just in time. Because I was working on a project where I was parsing a file where everything was lower case and had the _ . I ended up first replacing the _ with a space. Then use the new function from the video to have casing and it worked perfectly.
Glad to hear that, Thanks for sharing.
Thanks for taking so many efforts in sharing this. I found you very dynamic in terms of teaching. It shows the effort you taking in studying as well as sharing the crisp content and topic in your videos. All the topics were interesting but one thing which caught my attention was the use of string interpolation and StringBuilder. In my day to day work I use StringBuilder rarely but would like to use it more frequently not sure about its flexibility compared to string but would like to try for sure
StringBuilder can be expensive for small jobs but is essential for larger ones, so you just need to find the balance on when to use it.
Thank you Tim, This video is very helpful and clear.
You are welcome.
Once again just fine refresher as they say you are the best. Everything worked fine except in two places I had hiccup. First I was not able to do ...CompareToHelper(string testA, string? testB) Visual Studio keep on complaining "The type 'string' must be a non-nullable value type in order to user it as parameter 'T' in the generic type or method 'Nullable' " Yes I changed project XML, anyway I ignored it and went without string testA, string? testB. it worked fine. Second issue happened with replace method I was not able to Replace("works","makes",StringComparison.InvariantCultureIgnoreCase) did not worked, VS complained overload function with 3 parameters is not there.
BTW I am using Visual Studio 2017 maybe that has to do something with these problem?
Thanks for great video.
Just WOW! That was just a "long => short (;d)" video on how to manipulate strings... Thanks that very useful!
Glad it was helpful!
like always you are the best Tim .
Thanks!
This will be helpful for the junior devs I know there was only the 1 I didn't remember. Good content Tim.
I’m glad it helped.
I've seen this video before but I just realized something about 36:02. When you say concatenation it's not linear but exponential instead, I think the concept is wrong. You made a loop of 100000 iterations in which you append the i variable. Of course if you run it up until 10000 the last values added to the string are "9999" and "10000". But when you run it up until 100000, you are not factoring by ten, you are appendind until "99999", "100000" etc. The strings you are appendind are larger. That's why it's not linear. To make it an even test you should append the same fix length character on each loop. It's just for consideration. Great videos as usual!
Best video out there. Thanks for making this wonderful video.
You are welcome.
For parsing strings (removing swear words or making sure a file
name is safe, or whatever you want) I use regular expressions -> System.Text.RegularExpressions Regex
Saves writing many lines of code.
Thanks for sharing!
Thanks a lot for your videos! But I'm just don't get why there are way too small views and likes?
Your work deserves more
Keep sharing and that number will grow.
String builder is something I saw online every now and then, but I never looked into why it was used and I am pretty sure I should have used in quite a few places over the years haha.
I'm glad you learned something.
Thanks for tips especially on string builders and all other string manipulation methods, I never knew string builders can manipulate data very quickly as compared regular strings, and string interpolation and string literals.
Thanks for trusting Tim to be a part of your learning journey
I too wasnt aware of title case. Will come in handy for code-gen of database table column names!
Great!
Thank you kindly for sharing!
Greentings from Brazil!
You are welcome.
@@IAmTimCorey Again, thank you! This is the best video I finded on YT!
Thanks on the source code this means a lot to us 😁
You are welcome.
I learned a number of things but didn't keep track. Stringbuilder was an eye opener though.
I'm glad it was helpful.
Thanks Tim for all your awesome videos and training content on TH-cam! I have learned quite a bit from watching your videos.
You are most welcome. Thanks for watching.
Hi, I am the first one to comment ♥️♥️♥️😍😍😍 I leaned many and many things from your channel. Thanks for being in our life.
You are welcome.
Thank you, Tim.
Thank you!
God bless you sir. This is awesome
Thank you!
A small tip. You can use the Replace also to search for a text and remove it, e.g. testString.Replace("test","");
Thank you for sharing. Most of it I knew, but the Equal thing I did not realize and the Join and Concat have drawn my attention. For comparison, I often use Ordinal versions because they save me from localization trouble. Localization can be very annoying if you want to create software in another language than your local language. (I think the compare is worth a video on its own, there are far more variants)
Thanks for the tips
Another great resource for strings is the Nuget package Humanizer.
Thanks for the suggestion.
Note: you can use "range" syntax instead of string.Substring. Example:
string str = "abcd";
string a = str[1..];
a will contain "bcd", which is the same as str.Substring(1);
Thanks for sharing.
With the StringBuilder, you should probably have included a ToString() within the timer block so both examples end up with a string as output.
StartsWith() / EndsWith() accepts a comparison type parameter to not be case sensitive.
Wasn't aware of ToTitleCase().
Keep up the good knowledge sharing.
Thanks!
What a perfect video. Thanks.
You're very welcome!
Great video, as always!
Thanks!
Hi Tim Thanks for putting up this video. I want you to talk about the (DateTime) , and what is the Best practices with saving datetime & timezone info in database when data is dependant on datetime , specially in multi-tenant systems where tenants can use arbitrary timezone.
thank you
We appreciate the suggestion and I have added it to Tim's list for consideration.
In my experience, the solution is to always use UTC for all your stored data. Convert to (and from) the user's time zone as needed.
Thanks, your videio was bery helpful, hope this is will help me understand c# better.
You are welcome.
@@IAmTimCorey Do you have similar video on arrays?.
Great video. I have one tiny remark: capitalization is also culture dependent. fbi to FBI is not guaranteed. In Turkish (tr-tr) you’ll get FBİ for fbi and FBI for fbı.
Correct, which is something I touch on in this video.
resultArray = testString.split(" , ");
this line is showing syntax error as CS1503 Argument 1: cannot convert from 'string' to 'char' , is it due to .netframework version? mine is 4.6.1
Nope. If you are splitting on multiple characters, you need to use double quotes. Single quotes identify a char, which has to be one character.
33:41 That's not correct. An uninitialized string is not "en empty string": it is uninitialized, which is an error (CS0165). Even if it was a null object, it would actually not be a problem: Just initialize the object with either =default or =null and the string concatenation will still work. Therefore, the part with "a string with no characters is different then string.Empty" is also not completely right. string.Empty is initialized with "", so can definitely be used here. (It's just that the default initialization of string is not string.Empty, but null)
edit: to have a fair comparison, you should have added the test=sb.ToString() evaluation in the stopwatch loop. I mean: what if it did lazy evaluation? The results should be equal (and best compared to check if really so).
I know you're right, but in teaching others, details are important.
Other thing: for the same reason, string concatenation using + was expensive in the past: for every addition a new string object was created. However, nowadays the compiler is smart enough and will replace the whole expression with pluses by one big concatenation.
edit: 1:17:30 please elaborate why you should use "String.Compare" instead of "string.Compare". It seems more a habit/coding style then a real rule. I mean, even MS VS disagrees and gives an IDE style warning IDE0049 "Name can be simplified" from "Use language keywords instead of framework type names for type references (IDE0049)".
Good points. To add more to your first point: A variable is only initialized with its default value when it is a field or property in the scope of a class. If it is a variable within a method, it will not automatically initialize. This is reasonable because there could be scenarios in which you want to define multiple ways to set it. If it is followed up with a if { } else { } statement, in which that variable is set, it will not complain afterwards if it is used. Otherwise its value is not declared. This could be unintentional behavior as well, which sometimes help raise awareness to a logical problem in one's if-else structures.
As of fields and properties, they are initialized first (before running the constructor) if their values are set as they are defined. Otherwise it will run the constructor first. And only then it will look which variables have not been set and set them to their default values. When dealing with performance-critical areas, this little detail can result in slight optimizations. In the case of structs this would mean *not* creating an instance of a struct for no reason (struct's default value is an instance created with the parameterless constructor).
Substringing using rangeindex is now also possible, very handy when you want a part from the end of the string.
Thanks for sharing the tip!
Thank you for an amazing as always video. Speaking of text though, are you ever going to do a video or a course about Regex?
It is on the list. Not sure when I will get to it, but it is a priority.
@@IAmTimCorey Wow, I am buying this on the day one.
New? Combining Interpolation and Literal - $@. I've rarely used a "compare", so seeing how to write the Helpers was nice too.
Thanks for your trust in Tim.
Thank you for great lesson!
Thanks for trusting Tim.
It would be interesting to see a video about attributes and how to create/process them
Thank you. I have added this to Tim's list of possible future topics.
Hi and thank you for another amazing video. Is it possible to do a video on how to learn a code base? I mean are there methods and / or tools that you would use to be productive when joining a company? I heard some developers were put on notice when they joined the company, and never recovered from it. The company then just abused them and let them go. Thanks.
I really like this idea for a video. I placed it on Tim's list of viewer suggested topics.
@@tomthelestaff-iamtimcorey7597 I am so glad to hear this. I think if anyone can teach this, Tim is that person just b/c he explains all the concerns and surrounding issues and what not. I am so looking forward to this. Thank you so much Tom.
@@Greatfulone Just to be clear, its on a list that is very long so no promise if he will even get to it, but we can hope!
@@tomthelestaff-iamtimcorey7597 sure. I know he is very busy.
Some other interesting functionalities of Split:
var input = "123 45 67 ";
var splits = input.Split(" ");//["123", "45", "", "", "", "67", "", "", "", ""]
splits = input.Split(" ", 2);//["123","45 67 "]
splits = input.Split(" ", StringSplitOptions.RemoveEmptyEntries);// => ["123", "45", "67" ]
splits = input.Split(" ", StringSplitOptions.TrimEntries);// => ["123", "45", "", "", "", "67", "", "", "", ""]
splits = input.Split(" ", 2, StringSplitOptions.TrimEntries);// => ["123", "45 67" ]
and some about Char
Char.IsLetter, Char.IsDigit, Char.IsLetterOrDigit
sample: dotnetfiddle.net/MKbs3A
just want to add something, you can also chain the string manipulation method.
for example: testString.replace("text1","newText1").replace("text2","newText2");
Yep, you can since each returns a string.
In string literals you can escape quotes by using double quotes:
var foo = @"bla ""bla"" bla ";
Yep, that works, although I'm not a fan just because of how hard it is to get them right.
@@IAmTimCorey the same could be said of escaping quotes when concatenating strings. Don't think it was a valid reason to leave it out of the video though.
Great job 👍
Thanks!
Another very helpful video Tim! Looks like the power of these also comes in the combination of functions, e.g. removing specific words by finding the index of the word, then removing x characters.
And all this without even mentioning REGEX!
Question: When comparing words whilst ignoring case, what are the benefits of InvariantCultureIgnoreCase compared to just using .Lower() on both strings? Faster?
super time. i had interview in 4 days :-P
All the best!
Amazing. Thank you very much!
I wish you would make a video of an app using C# on a blockchain like Elrond for example. Would you ever?
No, sorry. I'm avoiding that in an effort to stay away from misleading people. There are a lot of great things that could come out of Web3, but so far the most common thing to come out of Web3 is unregulated gambling and theft.
Thank you so much.
You are welcome.
Excellent. Thank you!
You're very welcome!
can t thank you enough, God bless you.
You are very welcome.
Nice video for refreshing my knowledge. Is it possible to make a Tuples or ValueTuples video?
Topic suggestion noted and have added to Tim's list of viewer requests, thanks.
I've knew everything but the TitleCase thing. But thanks for that :)
I dont really get that nullable feature... string is a reference type under the hood...so it's always nullable.
Yes, but that was a poor implementation of nullable - the compiler never knew if we wanted to allow null. Now with C# 8 and beyond, if we mark a project as nullable, the compiler will not allow us to assign null to a non-nullable string (one without the question mark). This allows us to more easily find errors in our programs. It also allows the system to make suggestions such as doing a null check before using a string.
this is a great video
Thank you!
What is the best way for string sanitization when taking user input and passing them as parameters in a sql statement?
Use a parameterized sql statement.
Use Dapper or EF (which is becoming pretty good) which do it for you. For raw SQL read the MS docs e.g.: docs.microsoft.com / en-us / sql / relational-databases / security / sql-injection
Great Job!
Thanks!
Woohoo 100/100 for me. One thing I like to do is make an extension class for a string type and create a ToTitleCase method that way I can just do myString.ToTitleCase()
Interesting. Thanks for sharing.
I did not know that you could combine '$' for string interpolation and the '@' for string literals. 👍🏼
I am glad you learned something new.
You mentioned there where reasons to use String.method(); instead of string.method(); Could you elaborate? I've always heard it was just a different name for the same functionality.
It is. All c# built in types get converted to CLI types. So string -> String , int -> Int32
A good reason not to use String instead of string is that String is regular class name and can be overridden by another class named String. However the lowercase "string" is a keyword and cannot mean anything other than System.String
Thanks for the video Tim! Very nice! Are you planning to make more "masterclass" videos about basics of C#?
I think that's a very good idea. :)
A lot of these I've tried out for my self already.
Join method, surprisingly, was something new for me. I've created csv files in the past... a lot of them. I wonder why I never used it before :D
Also, never used string builder yet nor equality checks. I know about them but I guess I never had need to use them. Not that I recall at least.
Format seems a bit clunky.
Love @$ syntax! Very useful.
Kind sir. We have not heard from you lately. Hope all is well. Please drop us a note at Help@iamtimcorey.com when you get a chance.
super as usual!
Thanks!
I feel piece of completeness piece 😌
Great!
Thanks Sir!!!
Thank you, sir!
Realy nice content.
A video on the subject: Squirrel for Windows in .net5. Would also be nice. :-)
Thanks for the suggestion. I have added it to Tim's list of possible future topics.
Thanks
Thank you!
Thanks!
You are welcome.
One thing I struggled with for strings that I did not see covered unfortunately is how to parse out for spacings. I had many cases where I will receive a string that has multiple spaces between words which is wrong. Are there any ways to guarantee that you can send a string to a function and get returned the same string back but guaranteeing that there is only one space between words. Would not matter if the string originally had 10 spaces, 2 or 3, etc. That was one thing i was hoping to see since its very common in the business world. Especially if parsing from websites.
One way is to use Split to cut your string at the spaces with the StringSplitOptions.RemoveEmptyEntries parameter and use Join with one space as separator :
string newString = string.Join(' ', originalString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
A small nitpick on 13:40 is that string literals is the general category of strings. By that I mean that everything that is enclosed in double quotes is a string literal. String literals are further separated in 2 categories the typical/regular string literals and the verbatim string literals. The verbatim string literals are those that have a @ before the quotes(what is shown in the video) and do not allow for escaped characters/they perceive the escape character as just the character '\'. So theoretically the accurate definition of what you showed is "verbatim strings" and string literals is the general category. Am I wrong?
Also on what I use and know. I knew all of those expect from Title case, which I think is pretty useless. Insert and Replace I knew, but they are pretty useless since I have never used them. I have never used .Equals on strings since this is the 1 thing I really hate from java nor have I used the compare since you do not tend to compare strings, but if you do you can use the typical operators >, =,
Yes, mostly correct. Technically, the “test” string is a quoted string literal. learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#quoted-string-literals
@@IAmTimCorey Interesting I did not know of that definition. Until now I used regular string literals, which seems to be wrong, but in the end of the day we just say strings for everything 😅. On a serious note, I should probably read the official definitions. Thanks for the link.
Hello Corey, can u explain me how do I Replace more similar char in a text to a symbol? Like maybe A, ZS, H, K, L in all words to + symbol?
I am getting an error while using relational operator in switch case or using nullable string.
I have tried what Tim has done, editing the project file and still the issue persist.
It has something related to the version of C# language which is set to be 7.3 and it is demanding me to upgrade to 8.0.
How to do that? Is anyone else getting the same error?
Hello Everyone! Can anyone tell me if the String violates the Single Responsibility Principle? And explain why? Thank you!
can substring be done inversely? from right to left?
Hi TimThanks for posing this video I was looking for a video to remove escape characters from a text when extract into a csv file. Currently I’m using replace func like text.replace(“
”,string.empty)so that text fits into a single cell . Just wondering is there any better way of doing.
You could do text.Replace(Environment.NewLine, string.Empty).. This does "
" for non-Unix platforms, or "
" for Unix platforms without ever having to think about it again :) - docs.microsoft.com/en-us/dotnet/api/system.environment.newline?view=net-5.0
CsvHelper is wonderful for working with .csv files too
what if you only want to find "test" and not "testing" - and without adding the space?
Testing matches test unless you figure out more of a filter. The space at the end is a good option. You could try to filter on test and reject those that have an ing but then you would also get tests and testimony and others.
@@IAmTimCorey - I think this works, if (list.Contains("test") == true), but in the end what I'm really after is comparing two lists and finding any exact strings that match. I'll be looking at that tomorrow. Maybe you have another video for that. Thanks.
isn't string by default nullable?
Since C#8, you can choose to have everything non nullable by default, in which case you have to explicitly state where you want to have a nullable object.