Тёмный

Correct String Initialization in C# 

IAmTimCorey
Подписаться 421 тыс.
Просмотров 32 тыс.
50% 1

How do you properly initialize a string? Should it be null, string.Empty, empty quotes, or default? There is quite a bit of confusion on this topic, so let's look at the different options.
Full Training Courses: IAmTimCorey.com
Mailing List: signup.iamtimc...

Опубликовано:

 

29 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 122   
@chrisspellman5952
@chrisspellman5952 Год назад
I've been using String.Empty for years now. Because I can look at it an know "I 100% meant to put nothing here". If I see quotes, I end up asking myself if something should be there and was forgotten or is pending yet. So for me, it's far more readable with being explicit on intent.
@focl2003
@focl2003 Год назад
I do and think exactly the same.
@IAmTimCorey
@IAmTimCorey Год назад
Thanks for sharing.
@a.porteghali7402
@a.porteghali7402 Год назад
Many thanks for sharing. Its a little irrelevant to this topic, but, this tutorial made me think about "string.IsNullOrEmpty". I am used to using "string.IsNullOrEmpty" in my codes just to make sure I am not facing with an error which has a root in a careless string initialization . I read somewhere, this not a good style of programming. now, I think, I gained a deeper insight into the null string vs empty string.
@IAmTimCorey
@IAmTimCorey Год назад
You should definitely be checking your strings if you are unsure if they have a value. A null value in a place where you did not check first is the cause of a large number of problems.
@AlexanderBunakov
@AlexanderBunakov Год назад
Actually, there is a difference between using double quotes ("") and string.Empty; The IL code generated is different: Using double quotes generates: ldstr "" whereas string.Empty gives: ldsfld string [mscorlib]System.String::Empty Which one is less efficient is hard to say. Something tells me that the latter is less efficient simple because of an additional level of indirection - one for the static class System.String, and one more for the field reference.
@IAmTimCorey
@IAmTimCorey Год назад
What I was saying was that there is no difference in terms of performance. That was the original reason for using string.Empty instead of "".
@benjaminshinar9509
@benjaminshinar9509 Год назад
I also prefer string.empty, as other pointed out - it's explicitly saying that I didn't simply forget to put something there. I even like it in terms of how the IDE colors the two. string.empty is the normal blue color, nothing to see, normal, boring. empty quotes are the scary orange color of "things that I just type and hope to get right". I prefer not to have too many of those. they draw attention to themselves and will take focus away from actual string initialization with real values.
@IAmTimCorey
@IAmTimCorey Год назад
The thing I have an issue with is that string.Empty is another state. So now there is null, string.Empty, and "" and none of them are the equivalent of the others. By avoiding string.Empty, you can still say "value not set" with null and value empty with "".
@kleinalex
@kleinalex Год назад
​@@IAmTimCorey It was already pointed out in another comment by Chris Spellman, but let me repeat it here more clearly: It is another state, because it *represents* a different state. The possible states for strings are: [not a value] (=null), [a value] (="a value"), [an intentionally empty string] (=string.Empty), and [oops, I forgot to set the correct value] (=""). Using the same value for the last two states would imo be a case of thinking I was infallible. Since I am not, I consider "making errors easy to find" one of the most important properties of my code. Therefor, I limit my use of "" for initialization to debug code and unfinished code.
@erichanson5628
@erichanson5628 Год назад
Thanks Tim!
@IAmTimCorey
@IAmTimCorey Год назад
You're welcome!
@salamkuzhiyil
@salamkuzhiyil Год назад
This has been one of my most puzzling parts for a while. Many thanks
@IAmTimCorey
@IAmTimCorey Год назад
You are welcome.
@cyberherbalist
@cyberherbalist Год назад
Very interesting! I've been inconsistent over my career when it came to string initialization. I'd say I mostly used String.Empty, mainly because it had the benefit of being self-documentary. For what that was worth, which was probably not much. I never, ever, initialized a string to null. It was against my religion, I guess. I've been retired since 2016, but still love C# and write the odd utility program now and then.
@News_n_Dine
@News_n_Dine Год назад
"against my religion" good one. I'm just about to start a career in programmer and I don't know how to go about it. Congrats on your retirement
@IAmTimCorey
@IAmTimCorey Год назад
Thanks for sharing.
@chrismcgrath4601
@chrismcgrath4601 Год назад
I agree it's personal preference - but there's two things that I think are worth noting: * string.Empty cannot be used as the value of an optional parameter, you must use "" for that. * Searchability: Yeah, chance of you needing this is low, but if you want to find all instances of empty string, looking for "" can return false positives and string.Empty lets you find all references, and likewise, if you're wanting to find all string literals in a code base, having all empty strings excluded is useful.
@IAmTimCorey
@IAmTimCorey Год назад
Thanks for sharing.
@paulminshall8793
@paulminshall8793 Год назад
You do have to be careful when mapping strings to an Oracle database, since Oracle treats NULL and EMPTY as the same thing.
@IAmTimCorey
@IAmTimCorey Год назад
Yep, good point.
@jasonpricealt7122
@jasonpricealt7122 Год назад
Freaking Oracle and Nulls. They are as infuriating as dates in Oracle sometimes!
@ziadyaacoub2532
@ziadyaacoub2532 Год назад
feels like this could have been a 3 min video
@IAmTimCorey
@IAmTimCorey Год назад
Prove it. 😉
@CH-tv1cy
@CH-tv1cy Год назад
10 second
@Joooooooooooosh
@Joooooooooooosh Год назад
A tweet. 😂
@ChoccyMewk
@ChoccyMewk Год назад
@@Joooooooooooosh now a post 🪦 🐦
@brianviktor8212
@brianviktor8212 Год назад
I prefer string.Empty. I think string.Empty is cleaner, and I also like that you can directly use the same empty string, rather than rely on the compiler to "fix" that for you. I use the same pattern for my own classes too. For example I created a Result class (and Result and Result) for general use as a return value to give information about success state and exceptions (optionally also return values). And when the implementer just wants to return a "success" message, he just has to use "Result.Succeeded". Internally the classes generate a singular static instance of the result that succeeded or failed, so it is provided when possible. In other cases an exception is returned, so there the static instances are not used. It's a neat convention... however I found that I had a slight issue with having to *not* use constructors for Result, only static methods which handle when instantiation was appropriate. There is also Array.Empty as a pendant for arrays, and I may have seen something similar elsewhere too. As of null or default, I prefer null. It's good to know when I am dealing with something nullable or non-nullable in the context of type parameters. I avoid using string str = "" for optional parameters, because 'null' has to mean something, and is supposed to be the opposite of *something*.
@harag9
@harag9 Год назад
I personally prefer string.Empty and been using it a long time. When code reviewing other developers code it's much easier to see than it is to see " " -- See what I did there? Yes there is a space in the quote, which the reviewer could miss. Using string.Empty shows to anyone looking at the code your intention of using an empty string for the value, when " " could have been either mistyped, or maybe they forgot to set it e.g. country = "USA". Yes it's quicker to type "" than it is to type string.Empty, but personally I don't think speed is the issue when I have to spend ages looking for a bug and then find that the string is set to " "... Yes that has happened. I spent more time finding the bug, stepping through code etc than it would have taken the original developer to type string.Empty. Just my 2 pennies worth. The bigger question is - what is the point of ? on the string when strings have always been nullable ? string test1 = null; string? test2 = null; test1 & test2 are both null.
@IAmTimCorey
@IAmTimCorey Год назад
The point of string? is to tell the compiler and the reader that the string is expected to be null. Not doing null checks is one of the biggest causes of bugs in code. By being explicit with whether a string can be null, it allows the compiler to warn you when you aren't doing null checks when you should or to warn you if you are putting a potentially null value into a place where you do not expect a null value to be.
@mgwaiyankyaw427
@mgwaiyankyaw427 Год назад
That's a really good explanation Sir. Wish more video like this. I'm a newbie and your channel help me a lot. Thanks!
@IAmTimCorey
@IAmTimCorey Год назад
You are welcome.
@michelchaghoury9629
@michelchaghoury9629 Год назад
Really usefull, will you be making in the future topics related to microservices using NET ?
@IAmTimCorey
@IAmTimCorey Год назад
Yep.
@nistre14193
@nistre14193 Год назад
This was very insightful, never would have considered the switch-case scenario as I primarily use string.Empty. What about `null!`, `string.Empty`, or `""` when initializing a (non-nullable) string field on a model?
Год назад
If the field is a non-nullable string, you really should initialize it to a proper value, or you will eventually get an unexpected nullref problem later on. The only times I use "null!" are in designer code (i.e. initializing fields in my ViewModel which would require a whole backend DB mock to initialize properly). Otherwise, you are very much defeating the how non-nullable fields is handled today, which is to more or less make sure you always either have an option of null (in which case you have to check for it), or you will *not* have null as an option, because the compiler will make sure of that.
@MulleDK19
@MulleDK19 Год назад
I disagree that it comes down to just preference. What is ""? Is it an empty string, or a string you forgot to fill? Using string.Empty shows clearly that you intended it to be empty.
@IAmTimCorey
@IAmTimCorey Год назад
You are using string.Empty as a substitute for null. Empty is not the same thing as “” so you cannot use it in certain cases, which means you will now need to do additional checks before using your string. That, to me, is an anti-pattern. So if we were going to choose one state over another, I’d recommend “”. That’s why I say it is a preference. You might be ok with doing checks for Empty in addition to null checks. And if you say that you combine those two checks, you are basically agreeing that Empty and null are the same thing.
@tresaidh3y90
@tresaidh3y90 Год назад
Thank you for starting my morning with a quick overview before clocking in!
@IAmTimCorey
@IAmTimCorey Год назад
You are welcome.
@billboroson2412
@billboroson2412 Год назад
I’d bet lots of people watch these videos on their phones but the text is so small I have trouble reading it. There was so much unused space to the right and below Tim’s code, zooming in would have helped.
@IAmTimCorey
@IAmTimCorey Год назад
Thanks for sharing.
@MartinKramer-ff5mt
@MartinKramer-ff5mt 11 месяцев назад
string test5 = null!; Always usefull
@gregaclark2
@gregaclark2 Год назад
Coming from VBA, sticking with ' string1 = "" ' created a lot of clean and reusable evaluations for my solutions (e.g. "if len(string1) = 0 then...." ). This basic functional logic opened a lot of doors for me, and was one of my first personal conventions; instantiating strings = "" was one of the main catalysts that lead me to a real programming career in C#/SQL. One of my oldest, poorly named functions (escapeApostrophes) essentially doubles up apostrophes if they exist (for database reasons), or converts null strings to empty strings - the issue with the name is with how often it is used, I should have named it something much shorter!! :-p
@IAmTimCorey
@IAmTimCorey Год назад
Thanks for sharing.
@tenko1058
@tenko1058 Год назад
I Usually initialize my string with "null"; just to mess with people.
@IAmTimCorey
@IAmTimCorey Год назад
I'm not sure that is messing with them. You are being explicit about what you are doing. That's great!
@Nikolausi26
@Nikolausi26 Год назад
string is a class. Why is the code not: string test = new string("abc")
@IAmTimCorey
@IAmTimCorey Год назад
What value does that add?
@terjes64
@terjes64 Год назад
But what is the difference if we declare string a = null. Between: (if a != null){} and (if a is not null). I like the latter, but heard its not good for strings.
@IAmTimCorey
@IAmTimCorey Год назад
It is just fine to use the latter. It has been optimized to be basically the same.
@jfmarzulli
@jfmarzulli Год назад
Diving into the generated IL would have been great here to show the proof. It would have also been great to dive into the differences and origins of “string” versus “String” in C#/DotNet.
@IAmTimCorey
@IAmTimCorey Год назад
That's too much to cover in 10 minutes or less.
@omaewamoushindeiru1108
@omaewamoushindeiru1108 Год назад
var text = string.Empty i always use this lol
@IAmTimCorey
@IAmTimCorey Год назад
But why?
@rockymarquiss8327
@rockymarquiss8327 Год назад
If I'm understanding you correctly - the the compiler sees that there are two constants "" that it will behind the scenes just create a single constant and only use that single reference throughout?
@IAmTimCorey
@IAmTimCorey Год назад
Yep.
@rockymarquiss8327
@rockymarquiss8327 Год назад
@@IAmTimCorey Is this universal? More specifically - does the complier see test2="" is the same as string.Empty and thus just uses string.Empty - but if it was test2 = "1"; test3="1" does it create a constant "1" and point both test2 and test3 to it?
@HollandHiking
@HollandHiking Год назад
You still may want to explain the difference between string.Empty and String.Empty. Also, you never need to initialize a string explicitly with null, because the compiler will do this for you. So there is still more to say on this topic.
@focl2003
@focl2003 Год назад
Both are the same String or string, and concerning auto initialization it doesn't happen in local variables.
@femisuccess124
@femisuccess124 Год назад
Hi, please, can you do a video on creating AI apps in Blazor that use Pinecone as a database for infinite memory for GPT3
@IAmTimCorey
@IAmTimCorey Год назад
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/ I will say that "infinite memory" isn't really a thing.
@xlerb2286
@xlerb2286 Год назад
I'm glad to hear you not parroting the old, now useless, advice to use string.Empty instead of "". Another thing to consider with initializing strings as to whether you use null or an empty string to represent the concept of "no data present" is, when possible, to consider not creating the object/structure until you have the data present and you can initialize the strings to a meaningful value. Not always possible of course, but when it is it removes the need to check whether the string is null/empty and take a different course of action if so. The more little fiddly bits like that you can get out of your code the happier you'll be ;)
@pluralcloud1756
@pluralcloud1756 Год назад
the C# -- if you included some evaluations-- of IsNullOrEmpty()
@FuadHusni-e6j
@FuadHusni-e6j 11 месяцев назад
Thank you for your explanation!
@IAmTimCorey
@IAmTimCorey 11 месяцев назад
You are welcome.
@SKIDDOW
@SKIDDOW Год назад
Is this also default? string? test6;
@harag9
@harag9 Год назад
yes.
@Tsunami14
@Tsunami14 Год назад
As for String.Empty vs "", my take has always been to use String.Empty wherever you can, since it's platform independent. So, if there's a hypothetical future where a new platform defines empty strings differently (Oracle SQL?), you're already covered. Te save reaso you'd use Environment.Newline. ...Defensive programming, and all that jazz.
@IAmTimCorey
@IAmTimCorey Год назад
I’m not sure that’s really a thing, though.
@nelsonmelendez7250
@nelsonmelendez7250 Год назад
@@IAmTimCorey It's not. It's simply me doing defensive programming "just in case".
@BillBennettTV
@BillBennettTV Год назад
Why did you use string? type. What is question mark character for?
@IAmTimCorey
@IAmTimCorey Год назад
Strings are nullable normally. However, by using the string? syntax, you are indicating to the viewer and the editor (VS) that the string could be null. That means the editor can warn you if you use the string without first doing a null check. If you do not use the question mark, you are saying that the string should not be null. In that case, the editor can validate that you are not ever allowing null to be entered into the string. This is the new way of working with strings in order to better protect our code from null exceptions.
@BillBennettTV
@BillBennettTV Год назад
@@IAmTimCorey Thank you that was very helpful. I'd never seen that documented before.
@IAmTimCorey
@IAmTimCorey Год назад
It is a new feature in .NET 6+: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE--bn4e5xUEeM.html
@CRBarchager
@CRBarchager Год назад
I'm still ambivalent about what to use. On the one hand string test = ""; is recognised in multible c-like languages as as empty string (and for many developers it's easy to understand as it was you've seen the most) but on the other hand string.Empty is more in line with the use of the String.IsNullOrEmpty method. I use them both interchangeably. If I see test = ""; in code I won't change it but if I write new code I tend to use string.Empty.
@IAmTimCorey
@IAmTimCorey Год назад
We have String.IsNullOrWhitespace for "". I'm not sure what string.Empty really brings to the table. Null represents "no value set" and "" represents an empty starter value. String.Empty used to be the more efficient "" but I don't really see the need for it now that it is no longer more efficient. It actually makes us put more checks in our code (or checks that will catch both "" and String.Empty).
@kartingmania6590
@kartingmania6590 Год назад
Thanks Tim. It's given me food for thought, but I'm still unsure about what is the best method. On a similar note, years ago I got into the habit of declaring strings as "String" type, rather than "string". I can't remember what made me do this, though. What are your thoughts on this?
@IAmTimCorey
@IAmTimCorey Год назад
They are basically the same thing (not exactly, but for all normal cases they are). The convention is to use "string" when using it as a type and to use "String" when using it like a class (such as String.Format, String.IsNullOrWhitespace, etc.) Here is a post with more details: stackoverflow.com/a/7077/733798
@s7362454
@s7362454 Год назад
String.empty == "" ? True:false;
@SanderEvers
@SanderEvers Год назад
true
@harag9
@harag9 Год назад
Error, won't compile.
@caoinismyname
@caoinismyname Год назад
@@harag9 hahaha because of the case
@feeldulfo9387
@feeldulfo9387 6 месяцев назад
Is it a good practice to initalize a variable to empty after using in C#?
@IAmTimCorey
@IAmTimCorey 6 месяцев назад
After using them? If you are intending to clear them then yes, that would work.
@feeldulfo9387
@feeldulfo9387 6 месяцев назад
After using them when no longer in use.
@IAmTimCorey
@IAmTimCorey 6 месяцев назад
If it will no longer be used, then don’t do anything to it. The garbage collector will see that it is no longer used and will clean it up (when it is convenient).
@feeldulfo9387
@feeldulfo9387 6 месяцев назад
@@IAmTimCorey Ok thanks!
@farshadmh3350
@farshadmh3350 Год назад
ty so much
@IAmTimCorey
@IAmTimCorey Год назад
You are welcome.
@kamvacewu4579
@kamvacewu4579 Год назад
Thank you very much Tim!!
@IAmTimCorey
@IAmTimCorey Год назад
You are welcome!
@ronwilkins5727
@ronwilkins5727 Год назад
I was taught years ago that using String.Empty for initialization was used to explicitly state an empty string, rather than a "" (double quote) being used and was that empty string an accident and should it have had an actual value
@IAmTimCorey
@IAmTimCorey Год назад
It used to make a slight performance difference. Now it doesn’t, so it should mainly be avoided to avoid code issues.
@mohasahal1771
@mohasahal1771 Год назад
Is there an access path on the horizon? The courses are very good but they are really expensive and one can't do with the free stuff only.
@IAmTimCorey
@IAmTimCorey Год назад
Yep.
@va1iduser682
@va1iduser682 Год назад
In the case of test 2 and 3 its is not a matter of preference IMO if test3 allows more functionality via switch cases. That definately puts it in the "Reasons to use over string.Empty"
@kleinalex
@kleinalex Год назад
I think there is a misunderstanding here: Inside a switch, "" must be used, because only constants are allowed as case values, but this "" will of course match a variable initialized to string.Empty, or becoming an empty string in any way at runtime. So for string initialization (i.e. the topic of the video), it remains a matter of preference (aside from the distinction between accidentally or intentionally empty.)
@va1iduser682
@va1iduser682 Год назад
@@kleinalex There is no misunderstanding but thankyou for the reply, In initialization sure its a matter of preference i guess but for continued use after it seems logical to use "" rather then something that can not be passed into case statements
@emcattaneo
@emcattaneo Год назад
Great video!! Tanks for sharing!
@IAmTimCorey
@IAmTimCorey Год назад
You are welcome.
@darkmalk94
@darkmalk94 Год назад
I don't understand what's the point to initialised a string with null or default. At some point the variable will have a value so it can be initialised with "" or string.empty, doesn't it ? Thank you for the vidéo
@the-niker
@the-niker Год назад
If a string is null, you know it was never assigned a real value. Once you put in an empty string "" as an initial value, you have no idea if it's empty or you assigned a real value that just happens to be an empty string. With null you can do if(myString == null) { ... yep this one's still empty }. It's the same problem as a bool. It's either true or false, right? How can you recognize if the false is the default state or an actual value? Solution is easy, you make it nullable as "bool?" - that makes a tri-state variable true/false/null and null means never assigned/unknown value. This may seem trivial distinction in a code flow of your project but this also applies in APIs where the data are not created by you.
@pw.70
@pw.70 Год назад
Assigning an actual 'default' value to the string makes your code more readable - you _know_ that it's going to have that specific starting value rather than being at the mercy of future platform changes, etc. This is also a specific case when you're defining your strings for use in holding values from databases.
@AlexanderBunakov
@AlexanderBunakov Год назад
Think of this in the context of working with generics. Using default as an initializer is more convenient, since structs and value types can't be null. If you are writing a generic class you use default as initializer, and you always get what you need, which is not the case with null keyword, which cannot be used with structs. In this particular case with strings it really makes no difference which one you use.
@darkmalk94
@darkmalk94 Год назад
​@@the-niker thanks yes that way it make more sense
@MrKarco
@MrKarco Год назад
Thanks Tim :)
@IAmTimCorey
@IAmTimCorey Год назад
You are welcome.
@DoctorKrolic
@DoctorKrolic Год назад
1:00 you can use Alt + up/down arrows to move line up/down. Please use such shortcuts and maybe even sometimes point it out, so you not only teach us the primary topic of the video, but also how to use IDE efficiently
@IAmTimCorey
@IAmTimCorey Год назад
I don’t use that one often (so I forget the key commands sometimes) because it isn’t ideal. Cutting and pasting makes for better formatting often.
@omaewamoushindeiru1108
@omaewamoushindeiru1108 Год назад
using a cursor is better when representing a video
@arnotek
@arnotek Год назад
What if it is a "string?" as opposed to a "string"? Is it recommended to initialize the variable instead just declaring it?
@pavfrang
@pavfrang Год назад
You put a starter value typically always for "string" and a null value for "string?" . This is the most common approach.
@nicholasmciver3646
@nicholasmciver3646 Год назад
"string?" and "string" are the same thing as a "string" is already a nullable type. But it's good to put there for readability if you are expecting to work with nulls
@pavfrang
@pavfrang Год назад
@@nicholasmciver3646 any class is nullable such as string, however if you assign a string to null you get a warning. If you assign to string? null you do not get a warning. string? shows intent of allowing nulls.
@paulminshall8793
@paulminshall8793 Год назад
Strings are reference types, but are immutable, meaning that they behave like value types, as with the primitive types (int, double). I always initialise them, since you never know if the database back end is going to treat null or empty semantically differently.
@IAmTimCorey
@IAmTimCorey Год назад
In that case, you are explicitly allowing nulls so leaving it or initializing with null is fine. Whatever is more understandable.
@maksymbykov
@maksymbykov Год назад
Stupid question but is string nullable by default so that we can write 'string' instead of 'string?' ?
@IAmTimCorey
@IAmTimCorey Год назад
This is a newer convention that is used to communicate intent. Yes, string can be null but by saying string?, you are saying that you expect the string to be null. If you don't add the question mark, you are saying that you do not intend to allow a null value in string. Based upon that, your reader can better understand what to do and the compiler can properly warn you at design time if you are violating your intent. Not properly handling nulls is a large cause of exceptions. This is a way to better reduce those exceptions. Here is a video with more info on it: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE--bn4e5xUEeM.html
@maksymbykov
@maksymbykov Год назад
@@IAmTimCorey thanks a lot!
@اسيرالعلم-ك9ظ
@اسيرالعلم-ك9ظ 6 месяцев назад
I love this Playlist, go ahead 🤍
@IAmTimCorey
@IAmTimCorey 6 месяцев назад
Great!
Далее
Новый вид животных Supertype
00:59
Просмотров 201 тыс.
Редакция. News: 136-я неделя
45:09
Просмотров 1,1 млн
My 10 “Clean” Code Principles (Start These Now)
15:12
How Do I Become a C# Expert?
14:29
Просмотров 27 тыс.
Dependency Injection, The Best Pattern
13:16
Просмотров 825 тыс.
Intro to Tuples in C# In 10 Minutes or Less
9:50
Просмотров 41 тыс.
How To Use Recursion in C#
19:08
Просмотров 8 тыс.
Why is Microsoft Changing C# Syntax So Much?
11:07
Просмотров 35 тыс.
Новый вид животных Supertype
00:59
Просмотров 201 тыс.