I want to know what exactly happens inside when we declare a variable, like this:
string tr;
string tr = null;
While debugging, I noticed for both values that it was showing null only. But when using ref tr
without initializing null
it will give error while the second line doesn't.
Please help me to know about it in depth
An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .
str() turns whatever is in the parenthesis into a string! For example, if you had a variable, eggs, which was equivalent to 15, and you wanted it to be a string, you would enter: str(eggs)
NET prior to version 2.0, "" creates an object while string. Empty creates no objectref, which makes string.
Use the Null String in JavaWhen assigning the null to the string variable, the reference variable does not refer to any memory location in a heap. The null string means no string at all. It does not have a length because it's not a string at all.
Your first statement is just declaration and your second statement is Declaration + Initialization.
string tr; // Just Declaration
string tr=null; //Declaration + Initialization.
You may get compile time errors if you try to use tr
with just declaration. (first case) for example:
string tr; // Just Declaration
if (tr == "") //Use of unassigned local variable
{
}
Same error will be generated for ref
keyword, which requires the field to be explicitly assigned something (Declaration + Initialization). With out
keyword though, you can use just declaration, but the method would be responsible for making sure that some value is assigned to the out
parameter.
While debugging, I noticed for both values that it was showing null only
That's right because string
is a reference type and the default value for all reference types is null
.
But C# compiler doesn't allow the use of uninitialized variables.
Your first example is just a variable declaration. But your second one is variable initialization.
That's why if you write;
string tr;
Console.WriteLine(tr);
you get compiler error like;
Use of unassigned local variable 'tr'
From ref (C# Reference)
An argument that is passed to a ref parameter must be initialized before it is passed.
Although variables passed as out
arguments don't have to be initialized before being passed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With