0

I am trying to generalize some builder repetative method calls. I have some entities and trying to achieve call standard methods if they have implemented some if the interfaces. Here is what I am trying to achieve in code:

void MainMethod(){
  ...
  HandleStandards<MyClass>(builder);
  ...
}

void HandleStandards<T>(..builder..) where T: class, IEntity
{
  // of course my problem is with here. because T is not suitable to pass to other methods

  if(T is IIdentifiable){
    HandleIdentifiable<T>(builder);
  }
  if(T is ITrackable){
    HandleTrackable<T>(builder);
  }
}

void HandleIdentifiable<T>(..builder..) where T: class, IEntity, IIdentifiable
{
  ...
}

void HandleTrackable<T>(..builder..) where T: class, IEntity, ITrackable
{
  ...
}

Is there a way to type check a generic type and pass it to another generic method?

darcane
  • 473
  • 3
  • 14

1 Answers1

1

You can do this, using some reflection magic, or alternatively, if your HandleStandards has a parameter that is of type T you'd be able to do it a lot easier. So first, let's look at how to do it if builder is of type T:

void HandleStandards<T>(T builder) where T: class, IEntity
{
    if (builder is IIdentifiable identifiable)
    {
        HandleIdentifiable(identifiable)
    }

    // You'd go on like this
}

If you don't have a parameter of type T we'll have to use some reflection magic to do it, but it's not a lot, here it is:

void Handle Standards<T>() where T : class, IEntity
{
    if (typeof(T).IsAssignableTo(typeof(IIdentifiable)))
    {
        // You'll probably have to use some BindingFlags
        // Here I'm assuming that 'HandleIdentifiable' is private and static
        // https://learn.microsoft.com/en-us/dotnet/api/system.reflection.bindingflags?view=net-6.0
        var method = typeof(TypeContainingTheseMethods).GetMethod(
            nameof(HandleIdentifiable),
            BindingFlags.NonPublic | BindingFlags.Static
        );

        // If the method is *not* static, you'll need to pass the instance
        // on which to call the method on as the first parameter instead of null
        // Plus any additional parameters you may have inside the object array
        // in the same order as the method declares them
        method.MakeGenericMethod(typeof(IIdentifiable))
           .Invoke(null, new object[] { builder });
    }
}
MindSwipe
  • 7,193
  • 24
  • 47
  • Thank you! Unfortunately, `builder` is nothing related with generic type. Hence, I don't have a generic typed parameter and my other handlers are not static. I will give it a try with reflection. – darcane Nov 25 '21 at 11:27
  • [Here](https://dotnetfiddle.net/9q0JW6)'s the example I worked up to solve your problem, take a look if you need some implementation details – MindSwipe Nov 25 '21 at 11:30
  • Thank you for the solution. I tested it on my case and it worked. – darcane Nov 25 '21 at 11:41