tri_inn

tri_inn

  • NA
  • 1.2k
  • 232.9k

C#: How to compare variables by value and reference type

May 9 2017 4:15 AM
i have a small confusion that when we compare like == or equal function then both does the same job. u have a very basic question here.
 
see my program full code
  1. int x = 1000;  
  2. int y = 1000;  
  3.   
  4. if (x == y)  
  5. Console.WriteLine("Value is same");  
  6. else  
  7. Console.WriteLine("Value is not same");  
  8.   
  9. if (x.Equals(y))  
  10. Console.WriteLine("Value is same");  
  11. else  
  12. Console.WriteLine("Value is not same");  
  13.   
  14. if (object.ReferenceEquals(x,y))  
  15. Console.WriteLine("ref is same");  
  16. else  
  17. Console.WriteLine("ref is not same");  
  18.   
  19.   
  20. string s1 = "Hello";  
  21. string s2 = "Hello";  
  22.   
  23. if (s1 == s2)  
  24. Console.WriteLine("Value is same");  
  25. else  
  26. Console.WriteLine("Value is not same");  
  27.   
  28. if (s1.Equals(s2))  
  29. Console.WriteLine("Value is same");  
  30. else  
  31. Console.WriteLine("Value is not same");  
  32.   
  33. if (object.ReferenceEquals(s1, s2))  
  34. Console.WriteLine("ref is same");  
  35. else  
  36. Console.WriteLine("ref is not same"); 

i know that this kind of checking if (x == y) is based on value but when i use Equals function then i saw Equals is also work like == operator....am i right ?

how to check the reference ?
  1. if (object.ReferenceEquals(x,y))  
  2. Console.WriteLine("ref is same");  
  3. else  
  4. Console.WriteLine("ref is not same"); 
i saw in this case else portion execute........why because different memory is allocated for x and y ?
see more for string reference check

  1. if (object.ReferenceEquals(s1, s2))  
  2. Console.WriteLine("ref is same");  
  3. else  
  4. Console.WriteLine("ref is not same"); 
in this scenario s1 and s2 ref found same which is not clear to me because s1 and s2 ref should be different because two are different variable so how s1 and s2 reference check become same?

i like to know what are the best process to know value and reference is same or not whatever data type we use may be string or integer or float etc. please some one help me to understand this.
 

one guy said string in dotnet is interned. what is the meaning of In .NET strings are interned ? interned or internal is same ?

please discuss with a example just to clarify the meaning of string is interned in dotnet.
 
thanks
 

Answers (4)