C# struct equality

In this chapter you will learn:

  1. Object Identity vs. Value Equality
  2. Value type equality (default behavior)
  3. override Equals method

Object Identity vs. Value Equality

To compare two struct values, use the ValueType.Equals method. Because all structs implicitly inherit from System.ValueType. You call the method directly on your object:


using System;/* w  w  w. j  av  a 2 s . c o m*/

public struct Person
{
    public string Name;
    public int Age;
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

public class Application
{
    static void Main()
    {

        Person p1 = new Person("Jack", 75);
        Person p2;
        p2.Name = "Jack";
        p2.Age = 75;

        if (p2.Equals(p1))
            Console.WriteLine("p2 and p1 have the same values.");

    }
}

The output:

Value type equality (default behavior)


using System;/*from  ww  w .java2 s  .  co  m*/
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Security.Cryptography;

struct Car
{
    public string Make;
    public string Model;
    public uint Year;

    public Car(string make, string model, uint year)
    {
        Make = make;
        Model = model;
        Year = year;
    }
}

public class MainClass
{
    public static void Main()
    {
        Car c1 = new Car("BMW", "330Ci", 2001);
        Car c2 = new Car("BMW", "330Ci", 2001);
        Console.WriteLine(c1.Equals(c2)); // Prints 'true'

    }

}

The code above generates the following result.

override Equals method


using System;//from w w  w .j av a2 s . c o  m
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Security.Cryptography;

struct Car
{
    public string Make;
    public string Model;
    public uint Year;

    public Car(string make, string model, uint year)
    {
        Make = make;
        Model = model;
        Year = year;
    }

    public bool Equals(Car c)
    {
        return c.Make == this.Make &&
            c.Model == this.Model &&
            c.Year == this.Year;
    }

    public override bool Equals(object obj)
    {
        if (obj is Car)
            return Equals((Car)obj);
        return false;
    }
}

public class MainClass
{
    public static void Main()
    {
        Car c1 = new Car("A", "4", 2005);
        Car c2 = new Car("A", "4", 2005);
        Console.WriteLine(c1.Equals(c2)); // Prints 'true'
    }

}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to create generic struct
Home »
  C# Tutorial »
    C# Types »
      C# Struct
C# Structs
C# Struct Instances vs. Class Instances
C# struct Constructor
C# struct equality
C# Generic struct