Search code examples
c#objectcastinggeneric-collections

How to get or set any arbitrary type of object in C#


I have a class which shall act as a "model provider". Basically this is what it shall do:

The ModelProvider creates several objects, e.g. a Project and a User. The idea here is that from any part of my application I can call the ModelProvider to get the latest User or Project. Furthermore, from any part of the application I shall be able to push an updated User or Project to the ModelProvider.

Short: The ModelProvider shall be the class hosting the latest instances of User and Project.

DRAFT

class ModelProvider {
  private User user;
  private Project project;

  public ModelProvider() {
    this.user = new User();
    this.project = new Project();
  }

  public void SetModel(T model) {
    // If 'model' is of type User, do something like: this.user = model;
    // If 'model' is of type Project, do something like: this.project = model;
  }

  public T GetModel(???) {
    // Return the requested model. Either:
    // return this.user; or
    // return this.project;
  }

}

However I don't know how to actually get and set the requested model. Any help is appreciated :-)


Solution

  • It looks strange what you are trying to do. A potentially better way is to provide designated methods, but that depends on what you are actually trying to achieve:

    • void SetUser(User user)
    • User GetUser()
    • void SetProject(Project project)
    • Project GetProject()