I am trying to iterate through an object's properties and prompt the user to input their value in each iteration. Some of my properties are nullable and with my current code I'm getting an error, specifically where I try to convert the user's input to a property type which is a nullable.
Is there something I can use to make the user input convert to nullable datatype please?
Here is my code:
someClass newObject = new someClass();
foreach(PropertyInfo prop in newObject.GetType().GetProperties()) {
do {
try {
Console.WriteLine($"Enter {prop.Name} for new Object:");
string input = Console.ReadLine();
var convertedInput = Convert.ChangeType(input, prop.PropertyType);
prop.SetValue(newObject, convertedInput);
valid = true;
} catch {
Console.WriteLine($"INVALID INPUT - PLEASE INPUT A VALID {prop.Name} WHICH IS OF TYPE: {prop.PropertyType}");
valid = false;
}
} while (!valid);
}
CodePudding user response:
Use Nullable.GetUnderlyingType() to get the underlying type of a nullable type. If it's not a nullable type, it returns null, so you can check for null and use the actual property type instead. Like this:
var convertedInput = Convert.ChangeType(input,
Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
