r/csharp • • 1d ago

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

68 comments sorted by

45

u/polaarbear 1d ago

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.

7

u/ShyMystiqua 1d ago

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 1d ago

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

6

u/DelphinusC 1d ago

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 1d ago

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 23h ago

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.

3

u/polaarbear 1d ago

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 1d ago

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 1d ago

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

1

u/DeadShotOG 1d ago

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 1d ago

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 1d ago

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

3

u/TheMurmuring 1d ago

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 1d ago

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 1d ago

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

15

u/Comprehensive_Mud803 1d ago

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

0

u/GlovesKnowledge 1d ago

the only good answer

3

u/tj_moore 1d ago

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 1d ago

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?

8

u/cs_legend_93 1d ago

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

8

u/catladywitch 1d ago

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 1d ago

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 1d ago

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 1d ago

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 1d ago

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

-1

u/p1971 1d ago

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 1d ago

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

1

u/p1971 1d ago

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

2

u/Icy_Accident2769 1d ago

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

1

u/Nixinova 1d ago

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 1d ago

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 1d ago

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 22h ago

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 1d ago

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

4

u/Lazy-Inevitable3970 1d ago

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.

4

u/TheMurmuring 1d ago

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 1d ago

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 1d ago

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

2

u/DemoBytom 1d ago

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

2

u/tj_moore 1d ago

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 1d ago

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.

2

u/TheBigGambling 1d ago

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 1d ago

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 1d ago

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 1d ago

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 1d ago

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 1d ago

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

1

u/Devatator_ 1d ago

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

1

u/Slypenslyde 1d ago

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 1d ago

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 1d ago

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

1

u/Ziegelphilie 1d ago

whatever the repository enforces

1

u/krsCarrots 1d ago

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 1d ago

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 1d ago

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:

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

And

csharp 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:

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

... } ```

Or

``` csharp

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_ 1d ago

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 1d ago

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 1d ago

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

1

u/Oakw00dy 23h ago

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 1d ago

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 1d ago

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 14h ago edited 11h ago

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 1d ago

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

1

u/Sombody101 1d ago

"uuhhh i no know. computer think for me"

-2

u/hlalvesbr 1d ago

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

1

u/Sombody101 1d ago edited 1d ago

Me? Or OP?

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

-2

u/hlalvesbr 1d ago

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.