Skip to content

Commit

Permalink
Include FontName in Font.GetHashCode (#47674)
Browse files Browse the repository at this point in the history
* Update Font.cs

* Added test for GetHashCode pr #46816

* Added SkipOnTargetFramework as GetHashCode doesn't include font name in .NET Framework and changed FontFamily to SansSarif as per PR #47674. Fixes #44343. Original PR #46816.

* Update FontTests.cs

* Fix test, skip font if name is equal

Co-authored-by: Dan Moseley <danmose@microsoft.com>
Co-authored-by: Santiago Fernandez Madero <safern@microsoft.com>
  • Loading branch information
3 people authored Apr 23, 2021
1 parent 57104c7 commit f39d544
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -254,9 +254,7 @@ public override bool Equals([NotNullWhen(true)] object? obj)
/// </summary>
public override int GetHashCode()
{
return unchecked((int)((((uint)_fontStyle << 13) | ((uint)_fontStyle >> 19)) ^
(((uint)_fontUnit << 26) | ((uint)_fontUnit >> 6)) ^
(((uint)_fontSize << 7) | ((uint)_fontSize >> 25))));
return HashCode.Combine(Name, Style, Size, Unit);
}

/// <summary>
Expand Down
17 changes: 17 additions & 0 deletions src/libraries/System.Drawing.Common/tests/FontTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -978,5 +978,22 @@ private static void VerifyFont(Font font, string expectedName, float expectedEmS
Assert.False(font.IsSystemFont);
Assert.Empty(font.SystemFontName);
}

[ConditionalFact(Helpers.IsDrawingSupported)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "GetHashCode doesn't include font name in .NET Framework")]
public void GetHashCode_DifferentNameSameSizeStyleUnit_HashCodeIsNotSame()
{
using FontFamily family1 = FontFamily.GenericSansSerif;
using var font1 = new Font(family1, 1, FontStyle.Bold, GraphicsUnit.Point);

using FontFamily family2 = FontFamily.GenericMonospace;
using var font2 = new Font(family2, 1, FontStyle.Bold, GraphicsUnit.Point);
// This test depends on machine setup and whether the fonts we use are installed or not.
// If not installed we could get the same font for the two Font families we are testing for.
if (font1.Name.Equals(font2.Name, StringComparison.OrdinalIgnoreCase))
return;

Assert.NotEqual(font1.GetHashCode(), font2.GetHashCode());
}
}
}

0 comments on commit f39d544

Please # to comment.