Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generics - possible to create a method with n Generic types..?

I don't think this is possible but here goes...

I want to add method that can handle n numer of generics. for example :

bool<T> MyMethod() where T: Isomething
{
}

will work for one type

bool<T,K> MyMethod() where T: Isomething
{
}

will work for two types

Is there a way to work with n types - e.g.

bool<T[]> MyMethod() where T: Isomething
{
}

the reason I want to do this is to implement a static nhibernate helper method which can load from multiple assemblies - right now it works great for one assembly. My current method is as shown below:

        public static ISessionFactory GetMySqlSessionFactory<T>(string connectionString, bool BuildSchema)
    {
        //configuring is meant to be costly so just do it once for each db and store statically
        if (!AllFactories.ContainsKey(connectionString))
        {
            var configuration =
            Fluently.Configure()
            .Database(MySQLConfiguration.Standard
                      .ConnectionString(connectionString)
                      .ShowSql() //for development/debug only..
                      .UseOuterJoin()
                      .QuerySubstitutions("true 1, false 0, yes 'Y', no 'N'"))
            .Mappings(m =>
                      {
                          m.FluentMappings.AddFromAssemblyOf<T>();
                          m.AutoMappings.Add(AutoMap.AssemblyOf<T>().Conventions.Add<CascadeAll>);
                      })
            .ExposeConfiguration(cfg =>
                                 {
                                     new SchemaExport(cfg)
                                     .Create(BuildSchema, BuildSchema);
                                 });
            AllFactories[connectionString] = configuration.BuildSessionFactory();
        }

        return AllFactories[connectionString];
    }

Where the line: m.FluentMappings.AddFromAssemblyOf(), I would like to add multiple types e.g.

foreach(T in T[]){
   m.FluentMappings.AddFromAssemblyOf<T>()

}

Obviously this couldn't work I'm not completely dumb but I am not so hot on generics - can someone confirm that this isn't possible :-) ..? What would be the most elegant way of achieving this effect in your opinion..?

like image 889
Mark D Avatar asked Sep 15 '10 11:09

Mark D


1 Answers

No - the arity of generic types and methods is fixed on a per-type/method basis.

That's why there are all the different Action<...>, Func<...> and Tuple<...> types in the framework.

Occasionally that's a shame, but it gets in the way relatively rarely, and I suspect all kinds of things would be a lot more complicated with variable arity.

like image 164
Jon Skeet Avatar answered Sep 28 '22 15:09

Jon Skeet