Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created November 16, 2022 23:28
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 dcomartin/dd0d923644437daabe3ffe7fba04ec56 to your computer and use it in GitHub Desktop.
Save dcomartin/dd0d923644437daabe3ffe7fba04ec56 to your computer and use it in GitHub Desktop.
public readonly record struct Username
{
private string Value { get; }
public Username(string value)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException(nameof(value));
}
Value = value;
}
public override string ToString()
{
if (Value == null)
{
throw new InvalidCastException("Cannot create default Username");
}
return Value;
}
}
@dcomartin
Copy link
Author

Interesting idea. Is the if (Value==null) { ... } check in ToString() not needed since it is guarded from being null in the constructor?

Curious on why the check is in ToString().

Because you can do default(Username) in which Value will be null.

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