0

I am building a small console app that will get me information out of mongoDb and want it to be as reusable as possible.

I have a method that queries the db and returns data as a type of IMongoQueryable<T> because this is coming from a console application, I want the args to include the class \ type thats going to be passed in.

However in the code below I get error:

CS0118 'typeArgument' is a variable but is used like a type

on code GetDetails<typeArgument>(connectionString, db, collection)

void Main()
{
    var connectionString = "connectionString";
    var db = "dbName";
    var collection = "CollectionName";
    var activityId = 992018;
    string typeName = "Simon.AgentActivityDetails";
    Type typeArgument = Type.GetType(typeName);
    var result = GetDetails<typeArgument>(connectionString, db, collection); //<-- Where clause goes here

}

public IMongoQueryable<T> GetDetails<T>(string connectionString, string db, string collection)
{
    var dbClient = new MongoClient(connectionString);
    IMongoDatabase _mongoDb = dbClient.GetDatabase(db);
    IMongoQueryable<T> result = _mongoDb.GetCollection<T>(collection).AsQueryable();
    return result;
}

First Question, is what I want to do possible? If so, how do I achieve this?

Simon Price
  • 3,011
  • 3
  • 34
  • 98
  • Hi, have you had a look on [this answer](https://stackoverflow.com/a/4667999/8978576) ? – Serhii Sep 13 '22 at 21:32
  • Does this answer your question? [C# use System.Type as Generic parameter](https://stackoverflow.com/questions/4667981/c-sharp-use-system-type-as-generic-parameter) – Charlieface Sep 13 '22 at 21:39
  • You need reflection for this, something like `var result = typeof(YourClass).GetMethod(nameof(GetDetails)).MakeGenericMethod(new[]{typeArgument}).Invoke(this, new[]{connectionString, db, collection})` – Charlieface Sep 13 '22 at 21:41
  • @Serhii, no, I had not come across that one – Simon Price Sep 14 '22 at 07:48
  • @Charlieface, the codeblock you mention in your comment doesnt help either, because the `typeof(yourclass)` is this bit Im having having issue with using, and get an instance of an object is not set to an object exception – Simon Price Sep 14 '22 at 07:49
  • `typeof` cannot return null. `YourClass` here refers to the class containing the `GetDetails` method. You may need `typeof(YourClass).GetMethod(nameof(GetDetails), BindingFlags.Instance | BindingFlags.NonPublic)....` if it's a private method – Charlieface Sep 14 '22 at 09:37
  • its not private – Simon Price Sep 14 '22 at 10:34

0 Answers0