.Equals and == Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RefValDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int val1 = 5;
            int val2 = 5;
            Console.WriteLine(val1==val2);
            Console.WriteLine(val1.Equals(val2));
            object str1 = new string(new char[] { 's', 'h', 'i', 'p', 'r', 'a' });
            object str2 = new string(new char[] { 's', 'h', 'i', 'p', 'r', 'a' }); 
            Console.WriteLine(str1==str2);
            Console.WriteLine(str1.Equals(str2));

            StringBuilder sb1 = new StringBuilder();
            sb1.Append("hello");
            StringBuilder sb2 = new StringBuilder();
            sb2.Append("hello");
            Console.WriteLine(sb1==sb2);
            Console.WriteLine(sb1.Equals(sb2));

            Customer c1 = new Customer()
            { FirstName = "Croma", LastName = "Campus" };
            Customer c2 = new Customer()
            { FirstName = "Croma", LastName = "Campus" };
            Console.WriteLine(c1==c2);
            Console.WriteLine(c1.Equals(c2));
            //Console.WriteLine(c1.GetHashCode());
            //Console.WriteLine(c2.GetHashCode());
            Console.ReadLine();
        }
    }
    class Customer
    {
        object obj = new object();
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public override bool Equals(object obj)
        {
            Customer obj1 = obj as Customer;
            return this.FirstName.Equals(obj1.FirstName) 
                && this.LastName.Equals(obj1.LastName);
        }
        public override int GetHashCode()
        {
            return FirstName.GetHashCode() ^ LastName.GetHashCode();
        }
    }
}


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.