The carbon atom needs to either gain or lose 4 electrons to complete its valence shell. But it is difficult for it to lose 4 electrons as it would require about 6200 joules of energy and for gaining 4 electrons it would require more. So it is preferred thermodynamically to form covalent bonds where electrons are shared. But it should also be kept in mind that some hydrocarbons may exist as ionic compounds with metals. For example, CaC2, which exists as Ca2+ (acetylene ion)2-.