© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
31 replies
Tofaa

Help using generics and maps

I've been trying to make a basic listener consumer system for a Minecraft server implementation im making in c# from scratch. I come from a java background so c# is fairly similar but im stuck on trying to make a generic map of an unknown type at runtime.

private final Map<Class<? extends ClientPacket>, PacketConsumer>[] listeners = new Map[5];

public <T extends ClientPacket> void setListener(@NotNull ConnectionState state, @NotNull Class<T> packetClass, @NotNull PacketConsumer<T> consumer) {
        this.listeners[state.ordinal()].put(packetClass, consumer);
    }
@FunctionalInterface
public interface PacketConsumer<T extends ClientPacket> {
  void consume(T packet, PlayerConnection connection);
}
private final Map<Class<? extends ClientPacket>, PacketConsumer>[] listeners = new Map[5];

public <T extends ClientPacket> void setListener(@NotNull ConnectionState state, @NotNull Class<T> packetClass, @NotNull PacketConsumer<T> consumer) {
        this.listeners[state.ordinal()].put(packetClass, consumer);
    }
@FunctionalInterface
public interface PacketConsumer<T extends ClientPacket> {
  void consume(T packet, PlayerConnection connection);
}


I'm trying to rewrite this to c#.

I have
    private readonly ConcurrentDictionary<Type, Action<IClientPacket, Connection>>[] _listeners = [];
    public void SetListener<T>(ConnectionState state, Type type, Action<T, Connection> listener) where T : IClientPacket
    {
        var dict = _listeners[(int)state];
        dict[type] = listener; // cannot set this because its not IClientPacket, but rather T
    }
    private readonly ConcurrentDictionary<Type, Action<IClientPacket, Connection>>[] _listeners = [];
    public void SetListener<T>(ConnectionState state, Type type, Action<T, Connection> listener) where T : IClientPacket
    {
        var dict = _listeners[(int)state];
        dict[type] = listener; // cannot set this because its not IClientPacket, but rather T
    }

Any help would be fantastic, thank you :D
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Help with Generics
C#CC# / help
2y ago
✅ Enum and generics
C#CC# / help
3y ago
❔ Reflections and generics
C#CC# / help
4y ago
❔ Generics and nullable types
C#CC# / help
3y ago