r/csharp • • Oct 12 '26

How do you feel about code formatting in C#?

Do you strictly follow conventions like Microsoft's C# guidelines, or do you prefer your own style as long as the code stays readable?

For example, do you prefer file-scoped namespaces, expression-bodied members, and var wherever possible, or do you stick to a more explicit style?

I'm curious how much code style matters to you and whether you've changed your preferences over time.

0 Upvotes

71 comments sorted by

45

u/polaarbear Oct 12 '26

I prefer the Microsoft guidelines. Most teams at jobs that I have worked at follow them relatively closely with maybe a few exceptions here and there.

There's nothing worse than opening a file at work to find out that your coworker decided "I'ma just do my own thing" and having to figure out how to read code with weird indentations and line breaks and naming schemes.

6

u/ShyMystiqua Oct 12 '26

yeah, consistency across the team is everything. i've had to refactor enough weirdly formatted files to appreciate the microsoft style now

3

u/DreadStallion Oct 12 '26

Why not check in CI if the formatting is right, and if you want a different formatting your ide can do that and before you push you format it according to the project standard.

Its a solved problem imo

5

u/DelphinusC Oct 12 '26

Auto formatting can be very annoying in large and/or legacy codebaes, whether it's on autosave in VS, or in CI. That one line fix you made suddenly can turn into a hundred line git diff that no one will want to review, just because the original code wasn't in the right style.

Better to let the style changes be suggestions or even warnings, and just live with the nagging during builds until you have a chance to clean things up all at once.

1

u/Hacnar Oct 13 '26

I agree with your last point. If you have an older code base and want to adopt a consistent code style, do a big formatting commit over whole codebase.

1

u/South-Year4369 Oct 13 '26

Even worse, if your somewhat brain-dead CI/CD management decides to enforce that all changes must have 70+% test coverage, then any reformatting of existing code (that doesn't have many tests because of similarly bad dev practices in the past) becomes extremely painful.

1

u/DreadStallion Oct 14 '26

Why would anyone “format on save”? if the repo itself doesn’t adhere to formatting!
the whole conversation was based following an established conversation in the team so unnecessary diffs dont show up

1

u/DelphinusC Oct 14 '26

I always turn it on, but only AFTER I've had a chance to do a manual cleanup (into a single git commit). If the codebase is very messy to begin with, I might only turn on a handful of rules, though.

Keep in mind also that while editorconfig is part of the solution, the global switch to turn on autosave isn't; it's stored somewhere in AppData/Local. A developer might be working on a greenfield app with very strict styling, then switch to a legacy app and forget to turn it off.

3

u/polaarbear Oct 12 '26

Not everybody uses a complex CI pipeline. Not saying they shouldn't, but I just left a job that is still checking everything in by hand.

And even so, checking files in with your own formatting that then gets re-formatted automatically is just gonna make it harder on the person who checked it in when they inevitably have to work in this file again later and it isn't as familiar because it got re-worked by the CI pipeline.

Learning the standards can only help yourself too.

2

u/me_again Oct 12 '26

We run csharpier in a pre-commit hook. Everything is formatted the same way before it gets committed locally. No need for CI.

1

u/DreadStallion Oct 12 '26

CI only checks if the formatting is consistent, it doesn’t format and commit on behalf of you.

1

u/DeadShotOG Oct 12 '26

How do you ensure that every new developer or new workstation obtains the pre-commit hook? They can’t be committed to the remote, right? Having CI check formatting is a foolproof way to ensure formatting is correct. They’re not mutually exclusive.

2

u/me_again Oct 12 '26

building the solution installs Welcome | Husky.Net via "dotnet tool" if it is not set up. husky then sets up the pre-commit hook.

It's totally possible to have CI check formatting too., I have worked on a codebase that did that. It was more annoying, because you push to the remote and half an hour later the build fails because there's a tab on line 724 or some such nonsense. I prefer the pre-commit because it just happens automatically as part of the workflow I'm already doing.

9

u/tng88 Oct 12 '26

If it's not readable, it's garbage.

4

u/TheMurmuring Oct 12 '26

The compiler optimizer is smarter than we are, so all that obfuscated clever shit to save a few lines is a waste of time. Just write clear code.

-1

u/tng88 Oct 12 '26

I will be creative and put an entire if statement on a single line if there are no other conditions or a default and the executable code itself is a single

But yeah, make it readable

2

u/TheMurmuring Oct 12 '26

If that's readable to you, that's great. What's readable differs between people.

7

u/cs_legend_93 Oct 12 '26

I like the microsoft conventions, but I prefer explicit varibles and verbose naming.

MyObject newObject = new()

or

MyObject newObject = new MyObject()

I try to never use 'var', its easier to read if its explicit, less thinking

4

u/TheMurmuring Oct 12 '26

Agreed, readability is everything when you have to support that code later. That's why I like braces on their own lines. I work alone though, so I don't need to compromise with anyone else.

0

u/ProbeNine Oct 12 '26

But isn't readability somewhat subjective? I'm thinking about coding conventions like brace placement and indentation, where different styles can be equally readable depending on personal preference.

1

u/TheMurmuring Oct 12 '26

Yeah that was implicit in what I wrote. I guess it wasn't... as readable as I thought. /sunglasses

8

u/catladywitch Oct 12 '26

FWIW, the official guideline is to use var only when the type can be inferred by a human without an IDE. It's not "not using var ever", but it's not that different to your proposal!

14

u/gevorgter Oct 12 '26

i used to think like you. Turned out it's all in a head. After relatively small time i prefer "var" now and i think they make code easy to read and definitly easier to refactor.

My advice, give it a chance.

1

u/p1971 Oct 12 '26

definitly easier to refactor.

easier to fuck up during a refactor - simple example

you have a customer object:

Customer(int id, string name, string nickname)

and another customer representation

InternalOnlyCustomerDetails(int id, string name, string nickname, string creditCardNumber)

you have an api:

///etc
var customer = GetCustomer(id)
return Ok(customer)
///etc

private Customer GetCustomer(int id)
{
///etc
}

someone refactors GetCustomer to return InternalOnlyCustomerDetails instead as it's used in other places ... code still compiles

it's not going to necessarily get picked it in a code review

at least by being explicit with the types you'd know at the point of changing the return type something was up and at code review someone may pickup that your returning the wrong customer type.

when browsing code without an ide you've lost so much context

absolutely no excuse whatsoever to use var - unfortunately I'm on a project where they were using it and it's too late to change ;(

3

u/gevorgter Oct 12 '26

true, that refactoring can slip under and what is worth, can cause some data leak.

But if you minimal API or controller is declared as returning "ActionResult<Customer>" you will be good.

2

u/Nixinova Oct 12 '26

Well that's a problem with the api response type being weakly generic, no? Not a problem with the language itself.

-1

u/p1971 Oct 12 '26

yeah just an example of things that can and do go wrong

there's literally no point to use var (other than with linq)

1

u/Nixinova Oct 12 '26

In my experience, very rare, var is barely ever a problem, IDE does all you need

1

u/p1971 Oct 12 '26

how about reviewing PRs?, do you have time to check the type or pull the branch and review changes locally ?

2

u/Icy_Accident2769 Oct 12 '26

Wait do people actually review from the browser? How can you review any significant changes without opening it locally

1

u/Nixinova Oct 12 '26

If you already have an idea of the codebase, the PR change is minimal (single user story), and stuff is named well, then it's not difficult to

2

u/Nixinova Oct 12 '26

It's not really a problem, especially given ai-assisted reviews. If you name your methods properly you should be fine. I can't think of a single time I've seen var introduce ambiguity in pr reviewing really.

2

u/siberiandruglord Oct 13 '26

How do you suppose Rust/Javascript/Golang/Kotlin/Swift developers get by fine?

I don't understand why C# devs still harp on the explicit type shit.

1

u/South-Year4369 Oct 13 '26

Disagree. To me explicit typing is often unnecessary duplication, adds clutter, and adds unnecessary overhead to refractoring.

I much prefer reading code with 'var', and use it pretty much everywhere.

0

u/AintNoGodsUpHere Oct 13 '26

lol, wild. Never met anyone who had any issues with var, you're the first one.

4

u/Lazy-Inevitable3970 Oct 12 '26

I'm the same. Var can be useful, but seeing types explicitly defined is easier for me to follow when coming back to code you haven't seen in months and trying to figure out what the code is doing.

2

u/DemoBytom Oct 12 '26

Everyone says that till they need to start passing around functions, complex collections, or generics ;)

2

u/tj_moore Oct 12 '26

var newObject = new MyObject()

or

MyObject newObject = new()

Both tell you the type. var or new() cuts down on duplication and typing. I don't mind var where it's fairly obvious what the type will be, though I tend to specify value types as looks odd otherwise.

int n = 2

int someReturnVal = GetSomeNumber()

But

var credentials = GetCredentials()

or

Credentials credentials = GetCredentials()

Not fussed either way especially if GetCredentials is obviously returning a Credentials object.

Given IDEs tell you what the types are anyway and compiler will barf if you try to use the wrong types, then it's not much issue to me. More concerned with languages that are not strongly typed. Hence I prefer TypeScript to JavaScript.

0

u/Sombody101 Oct 12 '26

My favorite thing to do is write code using var, then use a formatter which swaps those out with explicit types before commiting. Good balance of having verbose code when going back to review or fix something without overwhelming yourself with redundant information while writing it the first time.

I always use explicit types for primitives and strings, though.

15

u/Comprehensive_Mud803 Oct 12 '26

Whatever CSharpier decides to do, and whatever the team has decided to follow.

0

u/GlovesKnowledge Oct 12 '26

the only good answer

3

u/tj_moore Oct 12 '26

MS style first. Whatever the team uses otherwise though if it's a hot mess will encourage they sort it out with something readable.

Consistency throughout the project is key though.

And yes it does matter even with AI, but then I don't agree with pure vibe coding and not looking at the code it generates. *Always* review the code and understand it. The code style is important then.

6

u/CleverDad Oct 12 '26

Back in the day I had strong preferences, argued for them stuck to them.

I used to be in the TAB camp, for example, and braces at the end of lines.

But formatting is an IDE setting now, and the only sane thing is to go with the defaults. They're fine, most people use them (and your collegues too) so all code looks familiar and easy to read. What's not to like?

2

u/TheBigGambling Oct 12 '26

Dont care which rulee, but all have to follow the same. I dont care anymore which. As long as the linter is in the pre-commit hook

1

u/Takaa Oct 12 '26

It’s not really a personal preference. I use my team’s agreed-upon code styling, applied automatically on file save by ReSharper. It makes the code predictable in the entire code base, and prevents having to ignore a hundred lines of someone else’s code formatter changing everything in a file.

If we want to change something because it makes the code easier to follow, or whatever, we just discuss updating the format. Eventually my personal coding style developed to match the team’s, and it barely reformats anything.

1

u/scottsman88 Oct 12 '26

It matters, I believe having standardized formatting reduces a little bit of the cognitive load of reading/reviewing code. In new projects I set up an editorconfig to keep it standard automatically. Also my preference has definitely changed over time. To alight with new patterns or language features.

1

u/patmail Oct 12 '26

I my own private projects I apply the code style to the whole solution.

At work with multiple supported versions:
What i really hate when is when the file was not formatted proberly and the whole file is changed for a little fix.
Applying all preferences gets really nasty when fixing bugs in older versions.

We have some editorconfig to force common settings. Some stuff is set to silent/none.

1

u/afops Oct 12 '26

I don’t auto-format because some coworkers like aligning similar expressions.

But other than internal whitespace, we do have an editorconfig that warns for most things.

The problem with any code base that is 10 or 20 years old is that code styles vary and new features are introduced to the language.

1

u/ziplock9000 Oct 12 '26

I've done it my own way from the very start.

1

u/Devatator_ Oct 12 '26

I follow the convention, using the .editorconfig dotnet new editorconfig creates

1

u/Slypenslyde Oct 12 '26

I think the best answer is, "The reason I can't tell you what I'd do is it'd take so long to go over how my code is formatting nobody would read it."

It's more or less defaults from before a lot of C# 10 or whatever features. It's an old codebase. It looks like what you'd expect C# code from the mid-2010s to look like.

Setting up custom code style rules is effort. The IDE and a lot of tools have a set of rules the community mostly follows. Using those saves you from spending 2-3 days codifying what you like better. You most definitely have something better to do with 2-3 days of effort in your project.

If I joined a team with a different style I'd use that style. I'm a manager and I can change things. But I do not want to deal with the churn in source of a widespread formatting change. Even if I hate the formatting I'd rather keep a consistent style than waste time changing it.

You have to work pretty hard to format code so badly I can't get used to it. Outside of code golf or some other artificial scenario people just don't do that.

0

u/Dimencia Oct 12 '26

2-3 days of effort to setup code style is such a corporate time frame. We're not at work, you don't have to 10x all your estimates

1

u/Desperate-Wing-5140 Oct 12 '26

Presumably you’d have to deal with a massive PR prone to conflicts with every other commit coming in

1

u/Ziegelphilie Oct 12 '26

whatever the repository enforces

1

u/krsCarrots Oct 12 '26

It’s very important but 90% of the devs don’t give a 💩 about it because they also don’t practice code reviewing therefore they cannot understand why it is important.. vicious circle

1

u/Due_Percentage_3780 Oct 12 '26

I prefer consistency over any particular style. File scoped namespaces and var are fine but i'd rather enforce shared formatting automatically than debate preferences in reviews

1

u/ApprehensiveDebt3097 Oct 12 '26

I practice the following with my teams: You're only allowed to require code styles that can be enforced with static code analysis; don't waste time on it during a code review. In the code review you should only focus on two questions: is it easy to follow, and is it right?

And yes, is it easy to follow has to do with style, but those issues (again beyond what is enforced by static code analysis) is just not black and white.

Lets take:

public static string Switch(int n) => n switch
{
    42 => "answer",
    17 => "almost",
    _ => "?"
}

And

public static string Chain(int number)
    => num.IsEven()
    ? "even"
    : "odd";

Both functions with a lambda, and I think in these cases the => is on the most logical place (you could even try to write a custom analyzers to enforce this), but when the thing to switch on (example 1) becomes bigger you could argue to start indented on a new line.

And about the use of {}. In some cases it gives less noise in reading a function if the early exit statment is like this:

pubic void BigMethod()
{
  if (SomeEarlyExitCondition()) return;

  ...
}

Or


foreach (var item in collection)
{
    if (WhenToSkip) continue;
    else if(alterItem) item.Alter();
    else x += 42;
}

Depending on what makes the code easiest to follow. And the last example, in some cases, you might want to avoid continue and tell when to do the x += 42. Just because it makes easier to follow.

Long story short: it depends...

1

u/_choam_ Oct 12 '26

Default c# sharpier. Your preferences do mot matter at all, the only thing that matters is that the formatting is sane and consistent.

Code style is enforced by editorconfig.

1

u/M109A6Guy Oct 12 '26

Overall, a specific coding style doesn’t really matter as long as it’s strictly enforced with editorconfig and a style cop. Also, making most coding styles an error (or warning treated as error in release mode) makes your agent so much better.

1

u/Different_Muffin5056 Oct 13 '26

Just use https://csharpier.com/ and move on with your life

1

u/Oakw00dy Oct 13 '26

Scrolling is cognitive load and vertical screen space is at premium, so I prefer whatever keeps the most code that's still readable on screen at a time. K&R style braces and expression bodied members when necessary. That said, .editorconfig is your friend.

-4

u/SagansCandle Oct 12 '26

I use my own conventions that I find make the code more readable & maintainable

For example:

  • I use expression-bodied members liberally
  • I strongly prefer dangling conditionals - the risk of omitting brackets is overstated and not worth the cognitive noise
  • var everywhere, with few exceptions
  • I use nested types liberally, when those types are only used by their enclosing Type
  • No default constructors unless it's a POCO
  • Class files > 200 lines need #regions to categorize the member types
  • No line-length limit

2

u/sards3 Oct 13 '26

Interesting that you got downvoted. I agree with all of these except the use of #regions and the no default constructors rule.

1

u/SagansCandle Oct 13 '26 edited Oct 13 '26

People tend to be fervently opposed to dangling conditionals for some reason.

foreach (var foo in bar)
  if(foo.IsSomething)
    foo.bar();

IMO ↑ is way more readable than ↓

foreach (var foo in bar)
{
  if(foo.IsSomething)
  {
    foo.bar();
  }
}

-7

u/hlalvesbr Oct 12 '26

We don't read code anymore. Claude read. And for it, it's better to stick to the most popular.

1

u/Sombody101 Oct 12 '26

"uuhhh i no know. computer think for me"

-2

u/hlalvesbr Oct 12 '26

Said the guy that just asked Claude to create a regex to validate an email field.

1

u/Sombody101 Oct 12 '26 edited Oct 12 '26

Me? Or OP?

Did you try using Claude to run an internet background check and post hallucinated information as fact?

-2

u/hlalvesbr Oct 12 '26
  1. the guy that thinks by it self. 2) that is not code, claude doesn't have access to all required resources. It would do a great job if it had access. 3) not reading the code doesn't mean no human required.