Skip to content

Instantly share code, notes, and snippets.

@MelbourneDeveloper
Created April 29, 2021 23:36
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 MelbourneDeveloper/1e7d892212d078c3dafc7d757aae41a4 to your computer and use it in GitHub Desktop.
Save MelbourneDeveloper/1e7d892212d078c3dafc7d757aae41a4 to your computer and use it in GitHub Desktop.
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