Skip to content

Instantly share code, notes, and snippets.

@HaloFour
Created June 29, 2018 20:38
Show Gist options
  • Save HaloFour/3a661fda9a9b1b131c1f65c25652a333 to your computer and use it in GitHub Desktop.
Save HaloFour/3a661fda9a9b1b131c1f65c25652a333 to your computer and use it in GitHub Desktop.
Data Classes, Builder with Assignment Validation
public class LoginResource {
public struct Builder {
private byte _assigned;
private string _username;
private string _password;
public string Username {
get => _username;
set {
_assigned = (byte)(_assigned | 1);
_username = value;
}
}
public string Password {
get => _password;
set {
_assigned = (byte)(_assigned | 2);
_password = value;
}
}
public bool RememberMe { get; set; }
internal byte Assigned => _assigned;
}
public static Builder Init() {
var builder = new Builder();
builder.RememberMe = true;
return builder;
}
private readonly Builder _builder;
public LoginResource(Builder builder) {
byte assigned = builder.Assigned;
if ((assigned & 1) == 0) {
throw new InvalidOperationException($"{nameof(Username)} was not assigned.");
}
if ((assigned & 2) == 0) {
throw new InvalidOperationException($"{nameof(Password)} was not assigned.");
}
_builder = builder;
}
public string Username => _builder.Username;
public string Password => _builder.Password;
public bool RememberMe => _builder.RememberMe;
// other members elided for brevity
}
@CyrusNajmabadi
Copy link

Very cute. I like it :)

@iam3yal
Copy link

iam3yal commented Jul 5, 2018

Pretty, pretty, pretty! me like.

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