Skip to content

Commit 34a664d

Browse files
committed
Added partial class for field providing serialization and deserializatino logic
1 parent 7354456 commit 34a664d

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
using System.Diagnostics.CodeAnalysis;
2+
3+
namespace Codebreaker.ViewModels.Models;
4+
public partial class Field : IParsable<Field>
5+
{
6+
public static Field Parse(string s, IFormatProvider? provider = null) =>
7+
s?.Split(';', StringSplitOptions.RemoveEmptyEntries) switch
8+
{
9+
[string shape, string color] => new() { Shape = shape, Color = color },
10+
[string color] => new() { Color = color },
11+
_ => throw new FormatException()
12+
};
13+
14+
public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, [MaybeNullWhen(false)] out Field result)
15+
{
16+
result = s?.Split(';', StringSplitOptions.RemoveEmptyEntries) switch
17+
{
18+
[string shape, string color] => new() { Shape = shape, Color = color },
19+
[string color] => new() { Color = color },
20+
_ => null
21+
};
22+
23+
return result is not null;
24+
}
25+
26+
public static IEnumerable<Field> Parse(IEnumerable<string> strings, IFormatProvider? provider = null) =>
27+
strings.Select(s => Parse(s, provider));
28+
29+
public static bool TryParse([NotNullWhen(true)] IEnumerable<string> strings, IFormatProvider? provider, [MaybeNullWhen(false)] out IEnumerable<Field> result)
30+
{
31+
List<Field> tempResult = [];
32+
33+
foreach (var s in strings)
34+
{
35+
if (!TryParse(s, provider, out var partialResult))
36+
{
37+
result = null;
38+
return false;
39+
}
40+
41+
tempResult.Add(partialResult);
42+
}
43+
44+
result = tempResult;
45+
return true;
46+
}
47+
48+
public string Serialize() =>
49+
Shape is not null
50+
? $"{Shape};{Color}"
51+
: Color;
52+
53+
public string ToString(string? format, IFormatProvider? formatProvider) =>
54+
Serialize();
55+
}

0 commit comments

Comments
 (0)