Tuesday, 7 November 2017

Diffenence Between string str=""; and string str1=string.Empty; in C#.

Whenever we declare string str=""; then it will create a new object. But whenever we declare string str1=string.Empty then it will create no object which makes string.Empty more efficient. However, string.Empty is a read-only field whereas "" is a compile time Constant.
So, string str1=string.Empty is the most prefered way of Writing the code. But string.Empty can't use inside Switch Case Statement because as it is a read-only so it will generate error.

string str = "";
switch(str)
{
    case string.Empty: // Error: A constant value is expected. 
        break;

    case "":
        break;

}

0 comments:

Post a Comment