when to use var keyword and when to use data type itself
Hello guys, can someone explain when should I use the
var
keyword and when should I use the actual data type pls.18 Replies
I was trying to use the
string
keyword to take user input like the following:
string name = Console.ReadLine();
But the Console.Readline has been underlined by the IDE indicating a warnimg that it can return a null value. When we change the string
to var
, it doesn't do that though.
I read upon that a bit and what I read it that var expect nullable data types, like string?
var
is a way to avoid writing the type out explicitly when it can be inferred from the right hand side of the assignment
see this meme $varConsole.ReadLine()
returns a string?
, so your IDE will warn you that trying to assign its return value to a variable of type string
could result in a null value in a non-nullable variable
if you were to type string? name = Console.ReadLine()
, the warning would go away
var name = Console.ReadLine()
results in the exact same thing, you just don't have to type string?
Yeah, I also read that string is expected to be non-nullable but the thing is, it is a referenced type, can't it be assigned to null ?
Using only var when required in my code won't make my code less readable ?
pre C# 8, yes, and post C# 8, still technically yes, but if you're using nullable reference types, you shouldn't be assigning null to non-nullable types
I always use var tbh
If I'm curious what type it is, I can hover over it and the IDE will tell me
you should generally use var everywhere you can
ok got it, thanks guys !
sometimes it's better for readability to specify the type, or necessary when the type can't be inferred from the right hand side, but other than that, var all the way
by the way is there a reason for that? I know it results in less typing but any other reason ?
pretty much that, less typing for you and less text for any readers of your code
why use much word when few word do trick
like imagine
second one is easier for both you and a reader
yep I see
yeah true
Also, visual alignment, helps you scan the code faster.
vs
The names of the variables are one under another
yeah I see
noted, thanks 👍
The disadvantage of not using var can be the wrong type being returned even though it may be compatible, especially when using nullable types for example string and string?, var will always hold the correct type.