Created
April 29, 2021 23:36
-
-
Save MelbourneDeveloper/1e7d892212d078c3dafc7d757aae41a4 to your computer and use it in GitHub Desktop.
String Validator Full
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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