C # - create and return a generic type of generic type from unidirectional typed methods (or classes)

Here's the script:

Create an instance with several typical types, for example:

var obj = myBuilder
            .Combine<TypeA>()
            .And<TypeB>
            .And<TypeC>
            .Create();

      

I want the obj returned by the Create () function to be typed Combined<TypeA, TypeB, TypeC>

>


I know I can create a generic instance with MakeGenericType

, but how do I combine and return generic types for different methods?

I don't want to return an object from Create()

typecast to client code. I feel it overkill and ugly:

var obj = (Combined<TypeA, TypeB, TypeC>) myBuilder
              .Combine<TypeA>()
              .And<TypeB>
              .And<TypeC>
              .Create();

      

Is it possible?

+3


source to share


2 answers


Currying works for simple type of arguments - type or parameters.

This way you can relatively easily create classes that will do what you want for a particular type in C #. One possible way is to capture types into intermediate classes such as:



   class Captured<T>
   {
      public Captured<T,U> And<U>() { return new Captured<T,U>();}
   }

   class Captured<T,U>
   {
      public Captured<T,U, V> And<V>() { return new Captured<T,U,V>();}
   }

   class Captured<T,U, V>
   {
      public Combined<T,U, V> Build() { return new Combined<T,U,V>();}
   }

      

+3


source


Even though currying works, the code being used creates too many instances in the process, as my work colleague pointed out. The goal is to really get Combined<T,U,V>

, and using multiple intermediate objects seemed heavy. Static classes are an alternative, and to my surprise, nested static classes with generics work just fine, and for this purpose it's pretty elegant. I'm glad we even have a nested class feature in C #. I am posting a sample code for anyone facing a similar issue there.



public static class Combine<T>
{
    public static class With<U>
    {
        public static class And<V>
        {
            public static CombinedType<T, U, V> Create
            {
                get
                {
                    return new CombinedType<T, U, V>();
                }
            }
        }
    }
}
class CombinedType<T, U, V> { }

class TypeA { }
class TypeB { }
class TypeB { }

// client call
var type = Combine<TypeA>.With<TypeB>.And<TypeC>.Create;

      

+1


source







All Articles