Skip to content

Ignoring Properties and Fields

Michael Brown edited this page May 22, 2019 · 4 revisions

To ignore properties/fields for a diff there are several options. You can do so explicitly, or using decoration by attributes. If you want to perform the opposite by only performing a diff on specified properties see Diff Only Specified Properties

Explicit property ignores using lambda syntax:

var object1 = new MyComplexObject(1, "A string", true);
var object2 = new MyComplexObject(1, "A different string", true);
// ignore the Name property
var diff = object1.Diff(object2, x => x.Id, x => x.Name);
Assert.AreEqual(diff.Count, 0);

public class MyComplexObject
{
  public int Id { get; }
  public string Name { get; }
  public bool IsEnabled { get; }
}

You can also pass a list of property/field names by string:

var object1 = new MyComplexObject(1, "A string", new Location(49.282730, -123.120735));
var object2 = new MyComplexObject(1, "A different string", new Location(40.712776, -74.005974));
// ignore the Name and Location properties by name
var diff = object1.Diff(object2, "Name", "Location");
Assert.AreEqual(diff.Count, 0);

public class MyComplexObject
{
  public int Id { get; }
  public string Name { get; }
  public Location Location { get; }
}
public class Location
{
  public double Latitude { get; }
  public double Longitude { get; }
}

Ignoring by the full path to a property/field:

var object1 = new MyComplexObject(1, "A string", new Location(49.282730, -123.120735));
var object2 = new MyComplexObject(1, "A different string", new Location(40.712776, -123.120735));
// ignore the Name and Location.Latitude property specifically by path
var diff = object1.Diff(object2, ".Name", ".Location.Latitude");
Assert.AreEqual(diff.Count, 0);

public class MyComplexObject
{
  public int Id { get; }
  public string Name { get; }
  public Location Location { get; }
}
public class Location
{
  public double Latitude { get; }
  public double Longitude { get; }
}

Ignoring by attribute is supported by any of these attributes: [IgnoreDataMember], [NonSerializable], [JsonIgnore]

var object1 = new MyComplexObject(1, "A string");
var object2 = new MyComplexObject(1, "A different string");
var diff = object1.Diff(object2);
Assert.AreEqual(diff.Count, 0);

public class MyComplexObject
{
  public int Id { get; }
  [IgnoreDataMember]
  public string Name { get; }
}

Disabling attribute ignores

It may be desired to ignore attributes when performing a diff, especially in scenarios with pre-existing attributes put in place for other reasons. To disable ignore attributes from being checked:

var object1 = new MyComplexObject(1, "A string");
var object2 = new MyComplexObject(1, "A different string");
var diff = object1.Diff(object2, options.DisableIgnoreAttributes);
Assert.AreEqual(diff.Count, 1);