Skip to content

Instantly share code, notes, and snippets.

@HaloFour
Last active June 28, 2018 11:41
Show Gist options
  • Save HaloFour/66c582deac779464371381410b66f80f to your computer and use it in GitHub Desktop.
Save HaloFour/66c582deac779464371381410b66f80f to your computer and use it in GitHub Desktop.
Data Classes
using System;
using System.Collections.Generic;
/*
* public data class LoginResource
* {
* public string Username { get; }
* public string Password { get; }
* public bool RememberMe { get; } = true;
* }
*/
public sealed class LoginResource : IEquatable<LoginResource> {
public struct Builder
{
public string Username;
public string Password;
public bool RememberMe;
}
public static void Init(ref Builder builder)
{
builder.RememberMe = true;
}
private readonly Builder _builder;
public LoginResource(Builder builder) => _builder = builder;
public string Username => _builder.Username;
public string Password => _builder.Password;
public bool RememberMe => _builder.RememberMe;
public override bool Equals(object obj)
{
return Equals(obj as LoginResource);
}
public bool Equals(LoginResource that)
{
if (that is null) return false;
var eq1 = EqualityComparer<string>.Default;
return eq1.Equals(Username, that.Username)
&& eq1.Equals(this.Password, that.Password)
&& this.RememberMe == that.RememberMe;
}
public override int GetHashCode()
{
var eq1 = EqualityComparer<string>.Default;
var hashCode = -736459255;
hashCode = hashCode * -1521134295 + eq1.GetHashCode(Username);
hashCode = hashCode * -1521134295 + eq1.GetHashCode(Password);
hashCode = hashCode * -1521134295 + RememberMe.GetHashCode();
return hashCode;
}
public override string ToString()
{
return $"{{{nameof(Username)} = {Username}, {nameof(Password)} = {Password}, {nameof(RememberMe)} = {RememberMe}}}";
}
public static bool operator ==(LoginResource x, LoginResource y) {
return x is LoginResource @this && @this.Equals(x);
}
public static bool operator !=(LoginResource x, LoginResource y) {
return !(x == y);
}
}
@agocke
Copy link

agocke commented Jun 28, 2018

Won't this copy the builder on the stack for the constructor call? Can you add an example?

@amis92
Copy link

amis92 commented Jun 28, 2018

    public static bool operator ==(LoginResource x, LoginResource y) {
        return x is LoginResource @this && @this.Equals(x); // <- also probably should be: @this.Equals(y)
    }

Isn't that going to return false for both-null case?

public static void ValidateEqualsOperator()
{
    LoginResource x = null, y = null;
    Assert.True(x == y); // throws
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment