Generally speaking, don't.
It's possible, but in most cases it's a bad idea. I assume you are using a database of some form, and if so then you will find the capability built into the DB: duplicating that is a recipe for real problems once software gets into production. For a DB, see the SQL IDENTITY field:
IDENTITY (Property) (Transact-SQL)[
^]