Created
December 14, 2023 20:05
-
-
Save jamescurran/8ed9ad531d799e17091bd30f19cb9d83 to your computer and use it in GitHub Desktop.
Update an object to one of two values, taken from a string
This file contains hidden or 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
| public static void UpdateFromText<T>(this T target, string changes, bool trueCase = true) | |
| where T : class | |
| { | |
| var propsTarget = target.GetType().GetProperties(); | |
| var parts = changes.Split('='); | |
| if (parts.Length != 2) | |
| throw new ArgumentOutOfRangeException(parts[0], $"{parts[0]} is not a property of the target"); | |
| var pT = propsTarget.FirstOrDefault(t => t.Name == parts[0]); | |
| if (pT == null) | |
| throw new ArgumentOutOfRangeException(parts[0], $"{parts[0]} is not a property of the target"); | |
| try | |
| { | |
| var options = parts[1].Split('|'); | |
| if (!trueCase && options.Length <= 1) return; | |
| var newVal = options[trueCase ? 0 : 1]; | |
| if (newVal == "null") | |
| { | |
| pT.SetValue(target, null); | |
| } | |
| else | |
| { | |
| var targetType = pT.PropertyType.Name == "Nullable`1" | |
| ? pT.PropertyType.GenericTypeArguments[0] | |
| : pT.PropertyType; | |
| object value = Convert.ChangeType(newVal, targetType); | |
| pT.SetValue(target, value); | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| throw new ArgumentOutOfRangeException( | |
| $"{parts[1]} is not assignable to {pT.PropertyType.Name} (Property {parts[0]})", ex); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment