Let set $S=\{1,2,3,4\}.$
Now see the mapping from $S$ to $S.$
For $f$ to be onto every element of codomain must be mapped by every element in domain.
Since, cardinality is same for both domain and codomain, we can not have mapping like $f(1)=1, f(2)=1$ because if it happened then at least one element remain unmapped in codomain, which result in $f$ being not onto but it is given that $f$ is onto. So every element in codomain has exactly one element in domain. Thus $f$ must be an one-to-one function.
NOTE: If $S$ is infinite then this result may not be true.