Comment by eterm
20 hours ago
Yes, you can have two different record types which both wrap a string value.
As a (bad) trivial example, you could wrap reading a file in this kind of monstrosity:
var fileResult = Helpers.ReadFile(@"c:\temp\test.txt");
Console.WriteLine("Extracted:");
Console.WriteLine(Helpers.ExtractString(fileResult));
public record FileRead(string value);
public record FileError(string value);
public union FileResult(FileError, FileRead);
public static class Helpers
{
public static FileResult ReadFile(string fileName)
{
try
{
var fileResult = System.IO.File.ReadAllText(fileName);
return new FileRead(fileResult);
}
catch (Exception ex)
{
return new FileError(ex.Message);
}
}
public static string ExtractString(FileResult result)
{
return result switch
{
FileError err => $"An Error occured: {err.value}",
FileRead content => content.value,
_ => throw new NotImplementedException()
};
}
}
Now, such an example would be an odd way to do things ( particuarly because we're not actually avoiding the try/catch inside ), but you get the point. Both FileRead(string value) and FileError(string value) wrap strings in the same way, but are different record types, and the union FileResult ties them back together in a way where you can tell which you have.
It's more useful implemented a level deeper, so that the exception is never raised and caught, because exceptions aren't particularly cheap in .NET.
No comments yet
Contribute on Hacker News ↗