Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of casting into "object" type?

I have found code on a website which is as follows.

 string a = "xx";
 string b = "xx";
 string c = "x";
 string d = String.Intern(c + c);

 Console.WriteLine((object)a == (object)b); // True
 Console.WriteLine((object)a == (object)d); // True

Here, what is the purpose of casting into object type again since a,b,d are itself the objects of string?

like image 255
babybob Avatar asked Jul 02 '16 09:07

babybob


People also ask

What is the purpose of casting an object to another type?

Type casting is a way of converting data from one data type to another data type. This process of data conversion is also known as type conversion or type coercion. In Java, we can cast both reference and primitive data types. By using casting, data can not be changed but only the data type is changed.

What is object type casting?

Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind or Object, and the process of conversion from one type to another is called Type Casting. Before diving into the typecasting process, let's understand data types in Java.

Why is it sometimes necessary to cast an object to another type in our code?

Casting a variable to a data type basically is telling the compiler "Trust me, I know what I'm doing." In the case of casting an "Object" to "Book", you are assuring the compiler that the object is, in fact, a Book and to proceed accordingly. It also as the effect of forcing you to believe you know what you are doing.

What is the point of casting?

Casting is most often used for making complex shapes that would be otherwise difficult or uneconomical to make by other methods. Heavy equipment like machine tool beds, ships' propellers, etc. can be cast easily in the required size, rather than fabricating by joining several small pieces.


2 Answers

The C# compiler will try to get all constant strings at compile time. This is called string interning. So after the code generated a and b are references to the same string which contains "xx".

You can check this by comparing their references (casting them to object and do the equality check or use object.ReferenceEquals). Keep in mind that == operator for strings compare their values not their references.

Another thing to mention is that strings are immutable in .NET.

string a = "xx";
string b = "x" + "x"; // String interning here
string c = string.Join("", new[] { "x", "x" }); // No interning here because it is evaluated at runtime

Console.WriteLine((object)a == (object)b); // True. Reference check
Console.WriteLine(a == b); // True. Value check

Console.WriteLine((object)a == c); //False. Reference check. Described below
Console.WriteLine(a == c); // True. Value check

So why is Console.WriteLine((object)a == c); doing a reference check?? Because the compiler will choose the == operator on object which checks for reference equality.


So the whole point of casting to object in your question is to check if string interning works or not. Assuming that there is no interning happen at compile time.

 string a = "xx";
 string b = "xx";
 string c = "x";
 string d = String.Intern(c + c);

Then Console.WriteLine((object)a == (object)b); would print "False", because a and b are references for two different string in memory, both of which look like "xx".

like image 198
Hamid Pourjam Avatar answered Oct 17 '22 20:10

Hamid Pourjam


An addition to the provided answer: string (C# Reference)

The System.String class is an immutable reference type provided in the .NET framework class library. This class creates a new string object internally for any string manipulation action. The contents of objects of this type do not change, although the syntax makes it appear as if contents can be changed. In addition, string is used as hash table key for the computation of hash values to avoid the risk of corrupting the hash data structure.

Example:

string a = "hello";
string b = "h";

// Append to contents of 'b'
b += "ello";
// When you set the variable's b value to "hello", 
// this would result in changing the pointer
// to the object in the HEAP the variable "a" is already pointing to
// Result would be: (reference of a == reference of b) --> TRUE
// b = "hello"; 

Console.WriteLine(a == b);                       // value comparison
Console.WriteLine((object)a == (object)b);       // reference comparison
Console.WriteLine (object.ReferenceEquals(a,b)); // reference comparison without casting

Result:

True
False
False

Explanation:

This will create a new object:

string a = "hello";

This will create another object:

string b = "h"; 

This will create yet another object:

b += "ello";

The following will create a reference to an existing object, more precisely, it will point to the same object the variable "a" points to → "hello".

string c = "hello"; 
Console.WriteLine (object.ReferenceEquals(a,c)); // --> TRUE

Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

like image 27
Legends Avatar answered Oct 17 '22 19:10

Legends