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 fetch and git rebase origin/main to 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 main using 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

1
2
3
4
git clone https://github.com/your-org/store.git   # copy the repository and its history
cd store
git switch -c feature/123-overdue-reminders        # create a branch and move to it
git branch --show-current                          # confirm where you are

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

1
2
3
4
5
6
7
git status                                                 # what changed, what is staged
git diff                                                   # the changed lines, not yet staged
git add src/Store.Api/Reminders/OverdueInvoiceFinder.cs    # stage one file
git add -p                                                 # stage hunk by hunk when a file has two unrelated changes
git diff --staged                                          # review exactly what will be committed
git commit -m "Select overdue invoices with a 3-day grace period"
git log --oneline --graph --decorate -10                   # recent history as a tree

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

1
2
git push -u origin feature/123-overdue-reminders   # the first push sets the upstream
git push                                            # every push after that

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:

1
2
3
git fetch origin                                   # download what changed on the server, touch nothing local
git rebase origin/main                             # replay your commits on top of the new main
git push --force-with-lease --force-if-includes    # your branch's history changed, so the push needs force

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:

1
private const int GraceDays = 7;

Your branch changed the same line to 5 and added a comment above it. The rebase stops:

1
2
CONFLICT (content): Merge conflict in src/Store.Api/Reminders/OverdueInvoiceFinder.cs
error: could not apply 4f2c1a9... Extend grace period to 5 days

Open the file:

1
2
3
4
5
6
<<<<<<< HEAD
private const int GraceDays = 7;
=======
// Finance asked for a longer grace period for corporate customers
private const int GraceDays = 5;
>>>>>>> 4f2c1a9 (Extend grace period to 5 days)

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:

1
2
// Finance asked for a longer grace period for corporate customers
private const int GraceDays = 7;

Then:

1
2
3
git add src/Store.Api/Reminders/OverdueInvoiceFinder.cs   # mark it resolved
git rebase --continue                                      # replay the next commit
# git rebase --abort                                       # instead of --continue: go back to before the rebase

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 toCommand
Throw away edits to a file (not staged)git restore src/File.cs
Unstage a file but keep the editsgit 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 pushedgit revert <sha>
Move a commit you made on main (not pushed) to a branchgit switch -c <branch>, then git branch -f main origin/main
Find a commit you lost after a reset or rebasegit reflog
1
2
3
4
5
6
7
8
git restore src/Store.Api/Program.cs             # the file goes back to the last commit
git restore --staged src/Store.Api/Program.cs    # out of the staging area, edits kept
git reset --soft HEAD~1                          # last commit undone, changes still staged
git revert a1b2c3d                               # new commit that reverses a1b2c3d
git switch -c feature/123-overdue-reminders      # committed on main by mistake: the new branch keeps the commit
git branch -f main origin/main                   # and local main goes back to the last fetched server version
git reflog                                       # every place HEAD has been, with hashes
git reset --hard 'HEAD@{3}'                      # jump back to one of those places (quotes needed in PowerShell)

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:

1
2
3
4
5
git stash push -u -m "half-done reminder template"   # save changes, including new untracked files
git switch main                                      # go do the other thing
git switch feature/123-overdue-reminders             # come back
git stash list                                       # see what is parked
git stash pop                                        # restore the latest stash and drop it

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:

1
2
3
dotnet new gitignore     # creates a .gitignore with bin/, obj/, .vs/, *.user and friends
git add .gitignore
git commit -m "Add .gitignore for .NET"

If bin and obj were already committed, .gitignore does not remove them:

1
2
git rm -r --cached src/Store.Api/bin src/Store.Api/obj   # stop tracking, keep the files on disk
git commit -m "Remove build output from the repository"

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:

1
2
3
* text=auto
*.sh text eol=lf
*.cs text

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:

1
2
3
dotnet user-secrets init --project src/Store.Api                 # adds a UserSecretsId to the csproj
dotnet user-secrets set "ConnectionStrings:Store" "Server=localhost,1433;Database=Store;User Id=sa;Password=Dev_Passw0rd;TrustServerCertificate=True" --project src/Store.Api
dotnet user-secrets list --project src/Store.Api                 # confirm what is stored

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:

  1. Rotate it first. Change the password, revoke the key. Deleting the file in a new commit does nothing; the old commit still contains it.
  2. Then decide with the team whether to rewrite history. Tools such as git filter-repo can 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 main because that is where the clone left you. Run git branch --show-current before the first commit of the day, and ask for a branch policy that blocks direct pushes.
  • git push --force to “fix” a rejected push. It overwrites other people’s commits. Fetch and rebase instead, and use --force-with-lease only 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 revert becomes 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 .gitignore if your team keeps per-developer settings files.

Checklist

  • On a branch named type/ticket-description, never on main
  • git status is clean except for what you mean to commit
  • Each commit is one logical change with an imperative message
  • git fetch and git rebase origin/main before asking for review
  • --force-with-lease, never --force, and only on your own branch
  • Conflicts resolved, solution builds, tests pass, then push
  • .gitignore from dotnet new gitignore and .gitattributes with text=auto committed
  • 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.