How to calculate the molarity of a gas?
Molarity is defined as "moles of solute per volume of solution", which implies that the system is in the liquid state.

As such, molarity is undefined for anything in a gaseous state -- there is no solute/solvent distinction in the gas phase.

You can define the concentration of a gas, though, and that calculation would be exactly the one you've described: placing $X$ moles of a gas in a container of volume $V$ yields a concentration $C=X/V$, with units of, e.g., $\pu{mol\over dm^3}$.

Note that while these units might look the same as the units of molarity, they are different. In this concentration value, the volume is the volume of the container; in a molarity value, the volume is the volume of the solution.