Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
String Validator Full
using System;
namespace ConsoleApp25
{
class Program
{
static void Main(string[] args)
{
//This throws an exception from the constructor
//var stringValidator = new StringValidator(null);
var stringValidator1 = new StringValidator("First");
var stringValidator2 = stringValidator1 with { InputString = "Second" };
Console.WriteLine(stringValidator2.InputString);
//This throws an exception from the init accessor
//var stringValidator3 = stringValidator1 with { InputString = null };
//Output: Second
}
}
public record StringValidator
{
private string inputString;
public string InputString
{
get => inputString;
init
{
//This init accessor works like the set accessor
ValidateInputString(value);
inputString = value;
}
}
public StringValidator(string inputString)
{
ValidateInputString(inputString);
InputString = inputString;
}
public static void ValidateInputString(string inputString)
{
if (string.IsNullOrEmpty(inputString)) throw new ArgumentNullException(nameof(inputString));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment