Skip to content

Instantly share code, notes, and snippets.

@agc93
Created April 12, 2019 01:55
Show Gist options
  • Save agc93/3e0492125dc0e8ef39777a1d3d1ea99f to your computer and use it in GitHub Desktop.
Save agc93/3e0492125dc0e8ef39777a1d3d1ea99f to your computer and use it in GitHub Desktop.
Strongly Typed ID snippet file for VS Code
{
"strongly-typed-id": {
"prefix": "typedid",
"scope": "csharp",
"body": [
"[JsonConverter(typeof(${1:TypedId}JsonConverter))]",
" [TypeConverter(typeof(${1:TypedId}TypeConverter))]",
" public readonly struct ${1:TypedId} : IComparable<${1:TypedId}>, IEquatable<${1:TypedId}>",
" {",
" public Guid Value { get; }",
"",
" public ${1:TypedId}(Guid value)",
" {",
" Value = value;",
" }",
"",
" public static ${1:TypedId} New() => new ${1:TypedId}(Guid.NewGuid());",
" public static ${1:TypedId} Empty { get; } = new ${1:TypedId}(Guid.Empty);",
"",
" public bool Equals(${1:TypedId} other) => this.Value.Equals(other.Value);",
" public int CompareTo(${1:TypedId} other) => Value.CompareTo(other.Value);",
"",
" public override bool Equals(object obj)",
" {",
" if (ReferenceEquals(null, obj)) return false;",
" return obj is ${1:TypedId} other && Equals(other);",
" }",
"",
" public override int GetHashCode() => Value.GetHashCode();",
"",
" public override string ToString() => Value.ToString();",
" public static bool operator ==(${1:TypedId} a, ${1:TypedId} b) => a.CompareTo(b) == 0;",
" public static bool operator !=(${1:TypedId} a, ${1:TypedId} b) => !(a == b);",
"",
" class ${1:TypedId}JsonConverter : JsonConverter",
" {",
" public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)",
" {",
" var id = (${1:TypedId})value;",
" serializer.Serialize(writer, id.Value);",
" }",
"",
" public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)",
" {",
" var guid = serializer.Deserialize<Guid>(reader);",
" return new ${1:TypedId}(guid);",
" }",
"",
" public override bool CanConvert(Type objectType)",
" {",
" return objectType == typeof(${1:TypedId});",
" }",
" }",
"",
" class ${1:TypedId}TypeConverter : TypeConverter",
" {",
" public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)",
" {",
" return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);",
" }",
"",
" public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)",
" {",
" var stringValue = value as string;",
" if (!string.IsNullOrEmpty(stringValue)",
" && Guid.TryParse(stringValue, out var guid))",
" {",
" return new ${1:TypedId}(guid);",
" }",
"",
" return base.ConvertFrom(context, culture, value);",
"",
" }",
" }",
" }"
],
"description": "Create a strongly typed ID struct"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment