Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created Nov 16, 2022
Embed
What would you like to do?
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;
}
}
@jerhon
Copy link

jerhon commented Nov 18, 2022

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().

@dcomartin
Copy link
Author

dcomartin commented Nov 18, 2022

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