There is no logical reason for that to happen, but it actually happens as there is no logical reason for why life in the first place has to exist but it does exist anyway.
I think by gender you are referring to biological sex and not the social identity teenagers use today based on their feelings...
The biological sex is determined by only one thing which is sex, and not sex as in having love with someone but the biological meaning of sex. The sexual cells an organism produces determinate the sex of the organism.
Example:
In humans there are 4 sexes
Male which produces Motile cells(sperm)
Female which produces Oogame cells(eggs)
Sterile which doesn't produce sexual cells
Hermaphrodite which reproducesproduces both motile and oogame cells at different periods during their life.
(true Hermaphrodites that can produce both sperm and ovules at the same time don't exist in humans)
The reason for why there can be only two types of sexual cells is the lung of the cells, the mitochondria has it's own genetic code different from that one of the cell as they evolved separately.
if the mitochondria of the sperm is not compatible with that one of the Egg then they will not fuse, that's why there needs to be at least two types of different sexual cells in which one has the mitochondria to stay alive and the other doesn't as it will fuse with the other anyway.
In case mitochondria didn't have it's own DNA then that could leave space for an infinite amount of different sexual cells on the same specie.
and it could actually happen as evolution doesn't plan for what makes more sense, what is the best and most perfect and efficient.... evolution doesn't have the will to decide. therefore everything that works will evolve even if it doesn't make sense or isn't efficient.
Just look at how stupid the evolution of mayflies was, they live for 4 minutes in which they just reproduce and die then the cycle repeats... this is the proof that evolution isn't based on logic.