Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between string str and string str=null

Tags:

c#

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

like image 548
keerti_h Avatar asked Mar 18 '14 14:03

keerti_h


People also ask

What does it mean if a String is null?

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 .

What is the meaning of String str?

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)

What is difference between String empty and String empty?

NET prior to version 2.0, "" creates an object while string. Empty creates no objectref, which makes string.

Can we assign String as null in Java?

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.


2 Answers

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.

like image 143
Habib Avatar answered Oct 14 '22 02:10

Habib


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.

like image 34
Soner Gönül Avatar answered Oct 14 '22 02:10

Soner Gönül