Dynamically assign values to class instance properties / Indexing class instance properties

I have a class like:
c#
public class MyClass {
public string StringProperty { get; set; }
public int IntProperty { get; set; }
public bool BoolProperty { get; set; }

private MyClass() {}

public static MyClass FromData(Dictionary<string, object?> data) {
MyClass newInstance = new MyClass();
foreach (var (key, val) in data) {

// Do some type checking, and then
// something like: newInstance[key] = (cast)val;

}
return newInstance;
}
}
c#
public class MyClass {
public string StringProperty { get; set; }
public int IntProperty { get; set; }
public bool BoolProperty { get; set; }

private MyClass() {}

public static MyClass FromData(Dictionary<string, object?> data) {
MyClass newInstance = new MyClass();
foreach (var (key, val) in data) {

// Do some type checking, and then
// something like: newInstance[key] = (cast)val;

}
return newInstance;
}
}
Assuming I have a dictionary like:
c#
Dictionary<string, object> data = new Dictionary<string, object>(){
{"StringProperty", "My string"},
{"IntProperty", 21},
{"BoolProperty", true}
};
c#
Dictionary<string, object> data = new Dictionary<string, object>(){
{"StringProperty", "My string"},
{"IntProperty", 21},
{"BoolProperty", true}
};
Is it possible to do something like my method FromData? Where if it exists, each property will be assigned the value from the dictionary?
9 Replies
Angius
Angius7mo ago
With reflections maybe
UnemployedNinja
UnemployedNinja7mo ago
Could you explain?
Angius
Angius7mo ago
It kinda smells of bad design tho
UnemployedNinja
UnemployedNinja7mo ago
ehhhh
Angius
Angius7mo ago
As I said, with reflections: https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/reflection-and-attributes/ It's fairly slow and inefficient, it discards the safety of the type system, but that's apparently what you want here Alternatively, you could look into source generators Either finding an existing one, or writing one yourself Or, for a fairly hacky way, you could serialize the dictionary to JSON and deserialize it to a class Which would either use reflections or source generation, depending on how you set it up
UnemployedNinja
UnemployedNinja7mo ago
hmm this seems like a good way tbh 🤔
Angius
Angius7mo ago
In general, though, C# is strictly and statically-typed. Setting properties by string name is far from the norm
DΣX
DΣX7mo ago
Which is then just checking the properties in the class and signing them by string name 😁
UnemployedNinja
UnemployedNinja7mo ago
This is such a hack, but I'm incredibly lazy, and it works so well lol. ty :)
Want results from more Discord servers?
Add your server