We introduce the class of partition-balanced families of codes, and show how to exploit their combinatorial invariants to obtain upper and lower bounds on the number of codes that have a prescribed property. In particular, we derive precise asymptotic estimates on the density functions of several classes of codes that are extremal with respect to minimum distance, covering radius, and maximality. The techniques developed in this paper apply to various distance functions, including the Hamming and the rank metric distances. Applications of our results show that, unlike the Fqm -linear MRD codes, the Fq-linear MRD codes are not dense in the family of codes of the same dimension. More precisely, we show that the density of Fq-linear MRD codes in F n×m q in the set of all matrix codes of the same dimension is asymptotically at most 1/2, both as q → +∞ and as m → +∞. We also prove that MDS and Fqm -linear MRD codes are dense in the family of maximal codes. Although there does not exist a direct analogue of the redundancy bound for the covering radius of Fq-linear rank metric codes, we show that a similar bound is satisfied by a uniformly random matrix code with high probability. In particular, we prove that codes meeting this bound are dense. Finally, we compute the average weight distribution of linear codes in the rank metric, and other parameters that generalize the total weight of a linear code.2010 Mathematics Subject Classification. 05A16, 11T71.