Ā© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
14 replies
UnemployedNinja

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

I have a class like:
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;
  }
}
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:
Dictionary<string, object> data = new Dictionary<string, object>(){
  {"StringProperty", "My string"},
  {"IntProperty", 21},
  {"BoolProperty", true}
};
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
FromData
?

Where if it exists, each property will be assigned the value from the dictionary?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

āœ… IndexOutOfRangeException when trying to set class properties to reader return values
C#CC# / help
3y ago
āœ… Class instance reference
C#CC# / help
11mo ago
ā” class instance creation
C#CC# / help
4y ago
Properties referencing their class
C#CC# / help
12mo ago