TL;DR
- Branch from an up-to-date main, make small atomic commits, and write pull request descriptions that explain the why rather than the what.
- Keep feature branches current with
git fetchandgit rebase origin/mainto resolve conflicts locally before opening or merging a PR.- Safely recover from common mistakes using stash, soft reset, and commit amending without rewriting shared history.
Level: Beginner · Prerequisites: A working Git installation, a GitHub account, and basic terminal navigation; Thinking Like a Programmer introduces the workflow context · Reading time: 10 min
Friday, 16:40. You finished the overdue-reminder feature, committed on main because that is where the clone left you, and pushed. Git rejected the push: “updates were rejected because the remote contains work that you do not have locally”. A blog post said git push --force fixes that. It did. It also deleted the three commits your colleague pushed that morning.
Or the quieter version: you pulled, and the editor filled with <<<<<<< HEAD and >>>>>>> lines in a file you did not even touch. You closed it, reopened it, and the lines were still there.
Git has a reputation for this. The fix is not to memorize fifty commands. It is a small daily routine plus knowing which command undoes what. This article covers both, with the exact commands in the order you will need them.
What you will be able to do after this
- Work on a branch, commit in small steps, and open a pull request
- Keep a branch current with
mainusing fetch and rebase without losing work - Resolve a merge conflict line by line and know which side is yours
- Undo an unstaged change, a staged change, a local commit, and a pushed commit
- Keep secrets and build output out of the repository for good
Clone and make a branch
| |
Branch names follow type/ticket-short-description: feature/123-overdue-reminders, bugfix/140-null-due-date, chore/update-serilog. The ticket number lets anyone find the “why”; the words let them find the branch. git switch -c is the modern command; git checkout -b does the same and you will see it in older documentation.
Never commit on main directly. Most teams block it with a branch policy, but build the habit even where they do not.
Commit small, with messages that say why
| |
A good commit is one logical change: “Add Invoice record and overdue filter”, then “Build reminder message per customer”, then “Add tests for the grace period boundary”. Three commits a reviewer can read one by one beat one commit called “wip” with forty files.
Message rules that survive every team: imperative mood (“Add”, not “Added”), about 70 characters at most on the first line, and the ticket number somewhere if your tool does not link it automatically.
Push and open a pull request
| |
The first push prints a link to open a pull request (PR). GitHub, Azure DevOps, and GitLab all do this. A PR is a request for a review and a merge. Write three things in the description: what changed, why, and how to test it. Then request a reviewer. If the team has continuous integration (CI), the build runs automatically; fix it before asking for anyone’s time.
Keep your branch up to date
While you worked, main moved. Before you ask for review, and whenever the PR page says the branch is out of date, bring those changes in:
| |
Rebase rewrites your branch’s commits, so the push needs force. --force-with-lease refuses if the remote branch has moved since you last fetched it, which is exactly the protection the Friday-afternoon story needed. Plain --force has no such check. Because git fetch updates what Git compares against, add --force-if-includes (Git 2.30 or later): it also refuses when the remote has commits you fetched but never integrated into your branch. Never force-push main, and never rebase a branch other people also commit to; for shared branches, use git merge origin/main instead.
The PR itself is merged through the web UI, usually with “squash and merge” so main gets one clean commit per PR.
Resolve a conflict without guessing
Suppose main now contains this line in OverdueInvoiceFinder.cs, because a colleague changed the grace period to 7:
| |
Your branch changed the same line to 5 and added a comment above it. The rebase stops:
| |
Open the file:
| |
During a rebase, the top half (HEAD) is main’s version and the bottom half is your commit being replayed. This is the opposite of a merge, where HEAD is your branch. When in doubt, check the commit hash after >>>>>>>; it is yours.
Decide what is right. Here the answer is to ask the colleague, because two people changed the same business rule in the same week. Say the agreed value is 7 and the comment is still useful. Edit the file so only the final content remains, with no markers:
| |
Then:
| |
Build and run the tests before pushing. Git only checks that the text merged, not that the code compiles.
Undo the right thing
| You want to | Command |
|---|---|
| Throw away edits to a file (not staged) | git restore src/File.cs |
| Unstage a file but keep the edits | git restore --staged src/File.cs |
| Undo the last commit, keep the changes staged (not pushed yet) | git reset --soft HEAD~1 |
| Undo a commit that is already pushed | git revert <sha> |
Move a commit you made on main (not pushed) to a branch | git switch -c <branch>, then git branch -f main origin/main |
| Find a commit you lost after a reset or rebase | git reflog |
| |
reset --soft is for commits only you have; it rewrites history. The switch -c plus branch -f pair is the clean way out of the Friday story once the push is rejected: your work moves to a branch, and local main goes back to the last version you fetched. revert is for anything already pushed; it adds a new commit and nobody’s clone breaks. reflog is the safety net: Git keeps commits around for weeks even after you reset past them, and reflog lists where HEAD has been so you can go back.
git reset --hard discards uncommitted changes with no recovery. Run git status first, every time.
Park work with stash
Someone needs a hotfix reviewed and you are mid-change with code that does not compile:
| |
Stashes are local and easy to forget. If a stash is older than a day, turn it into a commit on a branch instead.
Ignore build output and fix line endings
Run this once in a new repository before the first commit:
| |
If bin and obj were already committed, .gitignore does not remove them:
| |
Line endings: Windows uses CRLF (carriage return plus line feed), macOS and Linux use LF, and a mixed team sees every line of a file marked as changed. Put the rule in the repository rather than in each person’s config, as a .gitattributes file:
| |
text=auto makes Git store LF in the repository and check out the platform’s native ending. In an existing repository, run git add --renormalize . once after adding the file and commit the result. If you cannot change the repository, git config --global core.autocrlf true on Windows and core.autocrlf input on macOS or Linux gets you most of the way.
Never commit a secret
The classic is appsettings.Development.json with a real connection string, or an API key pasted in “just to test”. Once pushed, it is in history forever, and bots scan public repositories within minutes.
Keep secrets out of the repository with user secrets during development:
| |
The values live in your user profile, not in the repository, and when the app runs in the Development environment IConfiguration reads them like any other setting. On servers, use environment variables or a vault.
If you did commit a secret:
- Rotate it first. Change the password, revoke the key. Deleting the file in a new commit does nothing; the old commit still contains it.
- Then decide with the team whether to rewrite history. Tools such as
git filter-repocan remove the file from every commit, but every clone has to be re-created afterwards and open PRs break. For a secret that has already been rotated, many teams leave history alone.
Common mistakes
- Committing on
mainbecause that is where the clone left you. Rungit branch --show-currentbefore the first commit of the day, and ask for a branch policy that blocks direct pushes. git push --forceto “fix” a rejected push. It overwrites other people’s commits. Fetch and rebase instead, and use--force-with-leaseonly on your own branch.- Resolving a conflict by keeping your side without reading the other. The other side is a colleague’s intentional change. Read both, ask if unsure.
- Forgetting to build after resolving. Git merged text, not code; a conflict resolved “successfully” can still fail to compile.
- One giant commit at the end of the week. Reviewers cannot follow it and
revertbecomes all-or-nothing. Commit per logical step. - A month-old stash holding the only copy of a feature. Stashes are easy to lose; commit on a branch instead.
- Connection strings in
appsettings.Development.json. Use user secrets, and add the file pattern to.gitignoreif your team keeps per-developer settings files.
Checklist
- On a branch named
type/ticket-description, never onmain git statusis clean except for what you mean to commit- Each commit is one logical change with an imperative message
git fetchandgit rebase origin/mainbefore asking for review--force-with-lease, never--force, and only on your own branch- Conflicts resolved, solution builds, tests pass, then push
.gitignorefromdotnet new gitignoreand.gitattributeswithtext=autocommitted- No passwords, keys, or connection strings in any tracked file
What’s next
Part 2 of the series starts with “C# Types in Practice: Value vs Reference, decimal vs double, and Nullable”, the first of the C# articles and the one that explains why an order total should never be a double. The habits from this article apply to every code sample from here on: branch, commit small, open a PR.
This article is part of Zero to Full-Stack .NET. Previous: Thinking Like a Programmer: Turning a Vague Request Into Working Code. Next in the series: C# Types in Practice: Value vs Reference, decimal vs double, and Nullable (coming soon).
Get the next articles by email: subscribe to the newsletter.
How this article was made: drafted with AI assistance, then reviewed by Softinbit Technology before publishing.
