Advertisement
stefanpu

Compare two objects

Feb 17th, 2013
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.26 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApplication1
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             object x = 1;
  13.             object y = 1;
  14.  
  15.             //Everything is fine here
  16.             //This also means that every type that inherits object has the "Equals method"
  17.             //See: http://msdn.microsoft.com/en-us/library/ms173149.aspx
  18.             Console.WriteLine(x.Equals(y));
  19.  
  20.             SimpleClass firstObject = new SimpleClass(1);
  21.             SimpleClass secondOBject = new SimpleClass(1);
  22.  
  23.             //Value and reference types are compared differently.
  24.             //Reference types actually call the "ReferenceEquals" method.
  25.             //This method checks if the two variables refer to the same given object.
  26.             //See: http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx
  27.             Console.WriteLine("Simple Class objects equal?: " + firstObject.Equals(secondOBject));
  28.  
  29.             //If in the console we input the properties of the two objects, we might enter the same
  30.             //properties but have different objects.
  31.            
  32.            
  33.             //What if we want to say if 1 is bigger than 2 or not.
  34.             y = 2;
  35.  
  36.             //I. Using an operator
  37.             //Compile time error. Operators are not implemented for the object type
  38.             //That means that in the general case they or not implemented for the derived
  39.             //types too
  40.             //Console.WriteLine(x<y);
  41.  
  42.             //II. Using the "CompareTo method"
  43.             //Too bad. The IComparable interface is not implemented for the object type
  44.             //That means that in the general case it is not implemented for the derived types too
  45.             //Console.WriteLine(x.CompareTo(y));
  46.  
  47.             //If two types are different no compile time error with the "Equals" method
  48.             Console.WriteLine(y.Equals(firstObject));
  49.             Console.WriteLine(firstObject.Equals(y));
  50.  
  51.            
  52.         }
  53.  
  54.         class SimpleClass
  55.         {
  56.             public int Value {get;set;}
  57.  
  58.             public SimpleClass(int value)
  59.             {
  60.                 Value = value;
  61.             }
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement