Skip to content

Instantly share code, notes, and snippets.

@dibley1973
Created October 6, 2017 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dibley1973/103ef3131a2e096f9edf2d0a8389a282 to your computer and use it in GitHub Desktop.
Save dibley1973/103ef3131a2e096f9edf2d0a8389a282 to your computer and use it in GitHub Desktop.
A simple visual studio code snippet to create `GetHashCode` member in C#
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Basic GetHashCode Implementation.</Title>
<Shortcut>gethash</Shortcut>
<Description>
Code snippet to create a skeleton implementation
of the the GetHashCode pattern for a class.
</Description>
<Author>Duane Wingett</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>InitialPrime</ID>
<ToolTip>The initial prime number for the GetHasCode implementation.</ToolTip>
<Default>InitialPrime</Default>
</Literal>
<Literal>
<ID>MultiplierPrime</ID>
<ToolTip>The multiplier prime number for the GetHasCode implementation.</ToolTip>
<Default>MultiplierPrime</Default>
</Literal>
<Literal>
<ID>FieldName</ID>
<ToolTip>Name of a field within the class that should be included in the GetHasCode implementation.</ToolTip>
<Default>FileName</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>Returns a hash code for this instance</returns>
public override int GetHashCode()
{
int initialPrimeNumber = $InitialPrime$;
int multiplierPrimeNumber = $MultiplierPrime$;
// Overflow is fine, just wrap
unchecked
{
int hash = initialPrimeNumber;
hash = (hash * multiplierPrimeNumber) + $FieldName$.GetHashCode();
return hash;
}
}
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment