r/csharp • • Dec 09 '21

Warning: Loud forbidden C# keywords

1.1k Upvotes

240 comments sorted by

225

u/Boring-Meat1334 Dec 10 '21

Yield forbidden?

114

u/williane Dec 10 '21

No joke, more like best practice

37

u/Korzag Dec 10 '21

I thought it was more that they were doing a "yield break" which I didn't know you could even do.

0

u/[deleted] Dec 10 '21

[deleted]

30

u/Korzag Dec 10 '21

Typically you use it to return individual items in an IEnumerable collection.

14

u/cs_legend_93 Dec 10 '21

I thought this was a good thing haha, it allows you to process collection results before it is done building.

like:

Do work Query Task: Find all students with GPA above 2.0

If there is some calculation involved, you can use IAsyncEnumerable and start processing the results before the query is complete.

Pretty friggen cool imo.

→ More replies (5)

2

u/psymunn Dec 10 '21

It's the equivalent of a 'break' in a loop. You can't just return...

2

u/rd07-chan Dec 10 '21

cursed not forbidden

27

u/FizixMan Dec 10 '21 edited Dec 10 '21

Your post title is "forbidden C# keywords."

5

u/rd07-chan Dec 10 '21

i typed forbidden while i was thinking of cursed

1

u/form_d_k αΉ¬akes things too var Dec 10 '21

I'm not familiar with `forbidden` loops. Is that new?!

11

u/trexug Dec 10 '21

Yes, I hope you don't like linq /s

→ More replies (21)

30

u/[deleted] Dec 10 '21

Yield is not forbidden its just u dont no how to use it.

2

u/rd07-chan Dec 10 '21

true i dont

20

u/edgeofsanity76 Dec 10 '21
public IEnumerable<int> GetItemValues()
{
    foreach(var item in items)
        yield return item.Value; 
}

Lesson over.

161

u/anw Dec 10 '21

sounds like it's less of "forbidden" and more of "don't use unless you know what you are doing"

-55

u/bajuh Dec 10 '21

The whole point of C# is to avoid low level things like these. As god intended, Java (and C#) should look like pseudo OOP code and nothing more.

When things are getting slow, you need to find a nuget package instead of making your codebase harder to read. For example you're concerned with the performance of your nested for loop that iterates over pixels. Instead of starting an unsafe block, you should use the OpenCV package. If a brand new algorithm is required for a big dataset, use C++ interop.

59

u/V0ldek Dec 10 '21

Ah yes, the low level semantics of a yield and @int.

→ More replies (1)

9

u/ItzWarty Dec 10 '21

When things are getting slow, you need to find a nuget package instead of making your codebase harder to read. For example you're concerned with the performance of your nested for loop that iterates over pixels. Instead of starting an unsafe block, you should use the OpenCV package.

Funny you mention this, my experience with classic vision on soft-realtime systems is that opencv builtins tend to be extremely slow compared to hand-optimized solutions.

5

u/pHpositivo MSFT - Microsoft Store team, .NET Community Toolkit Dec 10 '21

This is such a wrong take on so many levels.

"The whole point of C# is to avoid low level things like these. As god intended, Java (and C#) should look like pseudo OOP code and nothing more."

While C# has always be primarily used for GUI/OOP programming, this statement is easily disproven simply by looking at the incredibly bast number of features on both C# and the runtime that are specifically meant for performance. Clearly both the C# design team and the runtime team wouldn't be wasting their time on all this if "the whole point of C# was to avoid low level things like these".

"For example you're concerned with the performance of your nested for loop that iterates over pixels. Instead of starting an unsafe block, you should use the OpenCV package."

While there are scenarios where using a native library certainly makes sense, that doesn't come for free. Using native code adds overhead (in many cases, having a full implementation in C# can be faster than invoking a C++ assembly), and it kills your portability, and makes maintenance harder. There are libraries out there, such as ImageSharp that are great examples of how you can have a fully managed implementation of a native image processing library that has speed that are on the same level (or actually, faster in some cases) than native libraries, with also the advantage of being able to run everywhere.

1

u/sFXplayer Jan 12 '22

These features are really useful for working with native code.

9

u/[deleted] Dec 10 '21

[removed] β€” view removed comment

2

u/themidnightdev Apr 01 '24

Copying memory blocks and unsafe operations are most definitely low level things.

141

u/[deleted] Dec 10 '21

I want a forbidden access modifier, which makes a member unusable in any scope.

60

u/MrcarrotKSP Dec 10 '21

Ah yes unnecessary memory use

78

u/[deleted] Dec 10 '21

unnecessary would be another great one

wasted int myInt;

35

u/MrcarrotKSP Dec 10 '21

unnecessary is just a 50/50 chance that the compiler will completely ignore the existence of the member and anything that depends on its existence

5

u/ZombieNub Dec 10 '21

That would be an interesting idea for debugging purposes.

"I'm not sure if my code still needs this function/variable/object/struct/etc.. Try getting rid of it. If you can't get rid of it, inform me."

19

u/MitoG Dec 10 '21
wasted TimeSpan myTime;

4

u/[deleted] Dec 11 '21

forbidden enlarged private myMember

1

u/Wimachtendink Dec 10 '21
//In anticipation of new features in next version
//  //to prevent complaints of new version being slower 
//  //which we already are expecting it to be

everything has a valid use!

7

u/RunawayDev Dec 10 '21

Now add grammar when using multiple modifiers..

privately static

Becomes even more fun with the made-up keywords.

unnecessarily wasted // me too lol

1

u/falconfetus8 Dec 10 '21

The compiler would just optimize it away.

5

u/[deleted] Dec 10 '21

How about authenticate? You would have to 2FA on pornhub before you can use a member 🀣

2

u/cs_legend_93 Dec 10 '21

lol like private?

8

u/RunawayDev Dec 10 '21

still allowed in private scope. forbidden would disallow even that :D

1

u/cs_legend_93 Dec 10 '21

Good point! Forgive me, but what would be the point of the forbidden keyword if you can't use the stored variable in any scope?

In my ignorant mind, if I do not want something to be used in any scope, then why would I even add it to the code in the first place?

3

u/RunawayDev Dec 10 '21

The point would be for it to be pointless.

It's a troll.

The most functionality you could imagine for a feature like this would be to have commented-out stuff that yet still has to compile. Then again we have the [Obsolete(true, "fuck off!")] attribute.

1

u/cs_legend_93 Dec 11 '21

Haha its true!! Thank you for the info on that!!

Many times I wish we had some more annotative features like [Obsolete], but more like Alert, or Notice. I know you can put this in the comments.. but sometimes its nice to have code there instead.

I think [Obsolete] encourages legacy code. But they can't take it off, many complaints would be had haha

2

u/RunawayDev Dec 11 '21

Well... you can implement custom attributes to do that for you and raise the respective compiler events like hint, info, warning, error. The last two though you'd already have covered with the Obsolete attribute.

I think [Obsolete] encourages backwards compatibility. Sure, you could just remove a member and have dependencies throw when trying to access it. But business reality looks a bit different than our often times idealistic personal coding standards. If a customer's cash register breaks after an update of a referenced library, you can expect a LOT of pressure to fix it. If it instead is able to keep working while generating a truckload of warnings, well, that's acceptable and yet still will alert you or the decisionmakers to have this fixed before it get's worse aka cash flow stops.

2

u/FizixMan Dec 10 '21

How about marking the member with the [Obsolete] attribute then configuring the project to treat the associated compiler warning as an error when that member is referenced?

1

u/ExplodingPotato_ Dec 12 '21

Brave of you to think the codebase doesn't use reflections or doesn't interpret strings as code.

1

u/EvilPigeon Dec 10 '21

Can I still access it with reflection?

1

u/[deleted] Dec 11 '21

Only via the nuget package System.Reflection.Forbidden in an unsafe context, for a monthly subscription of $599.99.

0

u/[deleted] Dec 10 '21

[deleted]

5

u/Cbrt74088 Dec 10 '21

That's exactly what static classes are.

0

u/[deleted] Dec 10 '21

[deleted]

4

u/Cbrt74088 Dec 10 '21

If you look at the IL, it says abstract sealed.

0

u/[deleted] Dec 11 '21

[removed] β€” view removed comment

1

u/Cbrt74088 Dec 11 '21

Yeah, OK.

2

u/ArcticMonkey667 Dec 10 '21

Top tier meme right here

2

u/rd07-chan Dec 10 '21

yea its not a serious post about keywords you should avoid, its just a meme

2

u/markiiitu Dec 10 '21

LMAO, had a good laugh, thanks for that

1

u/rd07-chan Dec 10 '21

I'm glad someone isn't taking this seriously

2

u/kobriks Dec 11 '21

So funny, thank you for the laughs.

58

u/leakypipe Dec 10 '21

@ is useful for a code generator

2

u/thinker227 Dec 10 '21

Or basically any time you're doing metaprogramming.

33

u/Jmc_da_boss Dec 10 '21

So basically don't use the perf stuff and goto πŸ˜‚

27

u/bluMarmalade Dec 10 '21

goto is the king of keywords in C#

21

u/kopczak1995 Dec 10 '21

To be fair it's sometimes better to use goto to escape few nested loops than write complex logic for that. But if you have 3+ nested loops and need to use goto then you might have worse problems.

7

u/_MovieClip Dec 10 '21

Exactly. If you are going down a hole and your solution is to come out in China, then maybe don't jump in the first place.

2

u/quentech Dec 10 '21

It's quite useful in high perf code, too.

2

u/kopczak1995 Dec 11 '21

Yeah, sure. I saw a lot of those in core dotnet/runtime libraries. It's a wild ride to read those codes though, lol.

2

u/wischichr Dec 10 '21

You could also make a separate method and return out of the nested loops. I've never seen a situation (excluding some edge case switch statements) where a goto was the most readable solution.

1

u/stikves Dec 10 '21

I would recommend reading the original Djikstra paper. My understanding of the common wisdom was wrong before that.

Go-to used properly is sometimes the best choice.

25

u/[deleted] Dec 10 '21

Yield is fine. And if you need to do some low level performant coding (like when interfacing with unmanaged code) and you know what you're doing, using fixed, unsafe, stackalloc can be of great help. Not for most development these days, though.

1

u/DixiZigeuner Dec 10 '21

I think C# wouldn't be the language of choice for low-level performant code in the first place

10

u/[deleted] Dec 10 '21

It really depends. I work in an environment where most people are C# developers. When it came time to porting an old scientific calculation library from C to "a modern language", C# turned out to be a great option for us. Partly because people here are familiar with C#. Many of these "forbidden" C# language keywords/features were critical in keeping on par with performance while using AOT compilation and producing native binaries. Worked great.

We did consider re-writing in something like Rust. But, porting the (large) library would have taken much longer due to the language differences being much greater. Also, no one here was familiar with Rust and we didn't want this important library to be a learning exercise and have to be rewritten again.

5

u/quentech Dec 10 '21

I think C# wouldn't be the language of choice for low-level performant code in the first place

I do more high perf C# work than most. It's in a SaaS web service that serves StackOverflow levels of traffic.

Most of the code has no need to be maximally efficient with hardware resources. The places where I drop into code using things like fixed, unsafe, etc. are only here and there in very targeted areas.

Consumers of those C# API's by and large have no idea the code they are calling is low level. Integrating safe and unsafe parts of the code is seamless.

These days - with Span and friends - I would have very little need for any unsafe code.

I have to manage large amounts of varying internal and external traffic across HTTP, SQL, Redis, file storage, etc. along with piles of frequently changing data. .Net is pretty great at that out of the box and with some popular Nugets.

Unsafe, low-level performant code tends to show up where the CPU needs to do a bunch of work on a set of data. Idiomatic C# is good enough in the vast majority of those cases but usually you can do an order of magnitude or two better if it pays to. We save a developer's salary worth of compute costs with unsafe C# code.

Efficient code is also more resilient. When shit goes sideways and you're puking out exceptions, retries, and log data like a drunk frat boy you'll be cursing those wasted cycles.

I've said in past comments that I would gouge my eyeballs out trying to write this system in C++. Doing it in C# is a pleasure, and the ability to write performant code is there when/if you need it.

That said, C# is not perfect for everything and there are certainly plenty of scenarios where you would be better off mainly using a lower level language.

17

u/panosc Dec 10 '21

unchecked is the default

By default the value of that option is unset and arithmetic operations are executed in an unchecked context.

33

u/[deleted] Dec 10 '21

Is there like a list of obscure but useful C# keywords/features?

10

u/only_4kids Dec 10 '21

Here is a list :

  • fixed

  • yield

  • implicit

  • uncheked

  • volatile

  • unsafe

  • stackalloc

  • __makeref

  • goto

  • int @int = 10;

I hope I will have some more time later on, so I can put in links to MSDN documentation as well.

5

u/6501 Dec 10 '21

There are good use cases for yield, volatile, stackalloc, & goto imo.

6

u/pHpositivo MSFT - Microsoft Store team, .NET Community Toolkit Dec 10 '21

All of them have valid use cases, except for __makeref πŸ™‚

10

u/HellGate94 Dec 10 '21

add __arglist to the list

but how are fixed, unsafe, stackalloc, implicit, unchecked, volatile forbidden? I use them quite frequently

4

u/thinker227 Dec 10 '21

implicit is really useful for discriminated union-like types.

26

u/PartyByMyself Dec 10 '21 edited Dec 10 '21

Yield is very useful and in many cases required depending on what you are doing.

https://stackoverflow.com/questions/39476/what-is-the-yield-keyword-used-for-in-c

For anyone who wants a bit of extra information on it.

Fixed keyword can only be used when used in an unsafe condition and just prevents garbage collection from cleaning up the allocation of the values you have collected. It does have uses when dealing with pointers or volatile memory that you don't want to lose. It just gives extra control over the garbage collection system C# has. If you know how garbage collection operates, it's rather safe to do this as long as you manage your data properly. It's just another way to get a little closer to the functionality of C/C++ w/ C#.

Extra info on Fixed https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/fixed-statement

Stackalloc is a double edge sword, used incorrectly, you create a performance impact due to the allocated memory at the CPU, used correctly, however, you bypass the GC and actually gain performance. Again, if you don't know what the hell you are doing, don't use it. If you do know how to properly use it and know that the way you are using it will increase performance, then use it.

A lot of C# is managed code with an automatic garbage collection system that other languages do not have or have a very simple system of handling. Some of these keywords give control over the GC and are ok to use.

Some of these aren't forbidden, just impractical like the "goto" or "@" or uncommonly used "makeref"

I'd say the only one here you should probably never use is Volatile. There are almost no cases where you need to use it.

13

u/cat_in_the_wall @event Dec 10 '21

i am not sure what you mean about stackalloc. the stack is universally cheaper than the stack. you just can't make it too big otherwise you'll overflow.

fixed pins an object, but can only be used for primitive types. for other things, enter the world of GCHandle. There are pin flavors and ones that are like normal but where gc compaction/moving is allowed: mostly useful for callbacks from native back to managed.

i am 50/50 on unsafe. sometimes i think it's just easier to use slabs allocated by Marshall. most struct interop (assuming friendly non dynamically sized ones) can be done safely with ref or out.

5

u/PartyByMyself Dec 10 '21

Stackalloc doesn't allocate memory at the heap, so it skips garbage collection. It has use cases where dealing with certain memory can be more performant when it isn't managed by GC.

You're best to use stackalloc with a constant for size allocation. There are certain Do's and Don't with stackalloc where if you use it correctly, you will see a noticeable performance increase, but if you use it incorrectly, you will see a performance decrease.

Once again, most of these come down to level of knowledge for applying the logic of a keyword.

5

u/crozone Dec 10 '21

When would you ever see a performance decrease on stackalloc besides overflowing the stack? Alignment issues? If you manage to blow out stack cache locality for locals? Isn't stack size only 1-4MB depending on OS/Arch anyway?

→ More replies (9)

22

u/Assassinnuendo Dec 10 '21

I feel like the "don't use goto" mantra is residual trauma from unstructured languages. It's amazing in the rare case it makes your code more readable.

That's happened only like a small handful of times in my career though. lol

6

u/KevinCarbonara Dec 10 '21

When I was in college, we had a professor who told us to implement a finite state machine using 'goto'. Conceptually, it was ideal. But the students were up in arms about it because they'd all read that goto was bad

3

u/Cbrt74088 Dec 10 '21

Sometimes, the code people write to avoid goto is worse than goto.

4

u/PartyByMyself Dec 10 '21

That's why I saiid "goto" is impractical. in almost all situations you will never need to use "goto" and in many cases if you do, you can refactor to prevent the use.

"Goto" has a habit of improperly being used and turning into a huge code smell. With the right use, just like many other keywords, it can be good to use and sometimes practical to use or even performant to use. With most people however, it is advised to not use it because people tend to not know when or how to properly implement it to take advantage of it without creating code smell.

1

u/tester346 Dec 10 '21

"Goto" has a habit of improperly being used and turning into a huge code smell.

Could you show at least one example?

1

u/_MovieClip Dec 10 '21

To quote a well-known film critic about Deus ex machinas: "You can write it so it doesn't happen".

0

u/[deleted] Dec 10 '21

[deleted]

2

u/Kajayacht Dec 10 '21

The classic example would be breaking out of nested loops, though the proper solution would be to refactor until you don't need to use goto, because as we all know goto is evil.

foreach (var item in items)
{
  foreach (var prop in item.Props)
  {
    if (prop == magicValue)
    {
      found = true;
      goto END_SEARCH;
    }
  }
}

END_SEARCH:
  Console.WriteLine(found ? "Found it" : "Didn't find it...");

0

u/[deleted] Dec 10 '21

[deleted]

2

u/Kajayacht Dec 10 '21

It's hard to come up with a arguably valid scenario for goto ;)

What I was trying to go for is that we have a collection of objects that have a collection of values and we just want to find if any of them contain the value and return quickly.

Not too long ago, I was writing some code that I eventually found would require the use of a goto if I kept with that direction. I changed directions.

1

u/quentech Dec 11 '21

It's hard to come up with a arguably valid scenario for goto

unrolled loops

Not terribly common code to need to write, but without goto you're needlessly bloating your code size.

1

u/psymunn Dec 10 '21

Yep. Just need functions calling functions for readability and easier control flow

1

u/6501 Dec 10 '21

I used it recently in a C assignment for school, had to write a server & used a goto to avoid repeating code

0

u/[deleted] Dec 10 '21

[deleted]

2

u/6501 Dec 10 '21

If it's called two times & you want to not have the overhead of a function call it's worth using goto. It's a code smell but your guaranteeing that the codes inlined for performance.

5

u/zet23t Dec 10 '21

Volatile is to be used in threading. For instance a counter variable being updated in one thread and read in another.

I have never observed it, but the documentation says that if a variable is not marked as volatile, the value could be cached by the compiler / CPU - e.g a "while (!terminateThread)" loop could run infinitely because the compile could come to the conclusion that this value could never change within this code's scope.

There are also thread barriers which handle write orders and such, but this is pretty much arcane knowledge that's only relevant in special multithreading circumstances.

Honestly: I don't like the video. It's promoting the idea that certain keywords are evil and should not be used. Even goto is useful - for instance when writing interpreters and efficiency in a spot is just too important.

If you start looking into micro optimizations because your code is just needing it, half of the keywords in the video are actually absolutely legit.

I'm working on a unity mobile game and the renderer code uses quite a few of these tricks to be able to handle the amount of data it needs to compute as fast as possible.

2

u/[deleted] Dec 10 '21

[removed] β€” view removed comment

2

u/6501 Dec 10 '21

then the second thread may or may not see the change from the first thread depending on factors such as whether or not both threads were running in the same processor.

Are you saying there exists a situation where it's categorically impossible for a thread to see memory changes for all time or are you saying they might miss some memory changes some times?

2

u/antiduh Dec 10 '21 edited Dec 10 '21

Some changes will be lost. It's better to use Interlocked instead.

Volatile tells the compiler to emit code such that every access to the variable is performed with a full read/write to ram, negating any cache. That helps, but does not fix all threading problems.

Consider two threads adding to a shared accumulator variable. They have the following three steps to do, at the machine level:

  • fetch the current value of the variable from its authoritative location in ram.

  • compute the new value, typically in a temp register.

  • store the new value in the authoritative location in ram.

Those three steps remain with or without volatile. Volatile only changes steps 1 and 3 to force full reads from ram.

OK, so what goes wrong with those three steps?

Well, those two threads could be running with arbitrary timing to teach other.

Consider the following events:

  • T1 reads ram value, is 1000.

  • T2 reads ram value, is 1000.

  • T1 computes new value, 1001.

  • T2 computes new value, 1001.

  • T1 writes to memory.

  • T2 writes to memory.

And thus the wrong value is computed and stored at the end of the final transaction.

This bug is easy to see for yourself. Create two threads that simply loop for a 1000 iterations adding 1 to a shared volatile variable. The result would be 2000 at the end if it worked correctly, but you'll get some value less than 2000.

To fix this, you'd use Interlocked.

Here's some demo code:

class Program {
    static void Main( string[] args ) {
        var test = new BadAccum();

        for( int i = 1; i < int.MaxValue; i++ ) {
            if( test.DoTest() == false ) {
                Debug.WriteLine( $"Failed after {i} tests." );
                break;
            }
        }
    }

    private class BadAccum {
        private const int iterations = 100_000;
        private const int addend = 1;
        private volatile int sharedCount = 0;

        public bool DoTest() {
            this.sharedCount = 0;

            List<Thread> threads = new List<Thread> { new Thread( ThreadEntry ), new Thread( ThreadEntry ) };

            foreach( var thread in threads ) { thread.Start(); }
            foreach( var thread in threads ) { thread.Join(); }

            int expected = addend * iterations * 2;
            if( this.sharedCount != expected ) {
                Debug.WriteLine( $"Failed: Got {this.sharedCount}, Expected {expected}." );
                return false;
            }

            return true;
        }

        private void ThreadEntry() {
            for( int i = 0; i < iterations; i++ ) {
                sharedCount += addend;
            }
        }
    }
}

And here are ten runs of it:

Failed: Got 188256, Expected 200000.
Failed after 1 tests.

Failed: Got 175283, Expected 200000.
Failed after 5 tests.

Failed: Got 141815, Expected 200000.
Failed after 3 tests.

Failed: Got 169255, Expected 200000.
Failed after 1 tests.

Failed: Got 173171, Expected 200000.
Failed after 1 tests.

Failed: Got 129428, Expected 200000.
Failed after 1 tests.

Failed: Got 146771, Expected 200000.
Failed after 2 tests.

Failed: Got 157018, Expected 200000.
Failed after 1 tests.

Failed: Got 116015, Expected 200000.
Failed after 2 tests.

Failed: Got 160761, Expected 200000.
Failed after 1 tests.

I've found that setting iterations to 10000 consistently makes it fail, and setting to 1000 causes it to seemingly never fail. And now maybe you understand why heisenbugs occur.

5

u/[deleted] Dec 10 '21

[removed] β€” view removed comment

4

u/antiduh Dec 10 '21

You're right on all counts, I was (over) simplifying for my audience and the argument I wanted to make - that volatile doesn't have nearly the 'synchronizing' strength that most people think it does.

And you're right that load fences and store fences on x86 aren't separate, you can only get a full memory barrier, but on arm you absolutely can. And you're right that the keyword not only tells the compiler to emit these fences, but also to not reorder how it emits instructions.

1

u/zet23t Dec 10 '21

It depends. A jit compiler might in deed reason that the value is never going to change and optimize the memory access away. Even an aot compiler might conclude this. In that case, the executed code will never be able to track a change done from outside. This is exactly what volatile is preventing from happening: the compiler will know that this value can change due to external factors it can't know and will thus not assume its value to be static when it looks like it should be.

So in this case, if you don't use volatile, you might think your program is reading data from memory when it in fact is not doing anything even remotely like that ever.

A further problem is that a value that the CPU is caching in a register is not updated with the value stored in memory. Such caches will usually be outlived after a while (fractions of seconds typically). If you don't define in your code that values should be written to / read from memory, your bets are off when multiple threads get involved.

Another thing that is confusing is execution order of memory writes/reads. You might believe that you are writing things in an order like a,b,c ... but the CPU thinks that it's better to write it like c,b,a. If you have memory values shared between threads without locking, you can't rely on that stuff and any code that does will face problems.

Thread.MemoryBarrier is a way to excert some control over this. It's complicated and I'm not well versed in it. I only know that it's not as simple as one might think.

The good news is that if you don't do threading AND shared memory access, you can ignore all this complexity. The bad news is, that if you have to work on such a problem, your assumptions about the code will be most likely wrong.

2

u/zet23t Dec 10 '21

How can this be prevented?

1

u/bossfoundmyacct Dec 10 '21

Yield is very useful and in many cases required depending on what you are doing.

https://stackoverflow.com/questions/39476/what-is-the-yield-keyword-used-for-in-c

For anyone who wants a bit of extra information on it.

I gotta say, after reading through the post, best answer, and subsequent comments twice, I still can't understand where you'd use yield. Even the "real world" example if flying over my head. Any other resource you can recommend for me to wrap my head around this?

2

u/ItzWarty Dec 10 '21

Think of it like async/await in terms of being a deceptively simple paradigm shift that leads to big changes in how code can be architected.

2

u/bschug Dec 10 '21

It is very useful when you want to separate how you iterate over your data vs how you process the individual items. Let's say you're building a web scraper for fetching the match results from something like nfl.com and save them to your own database. In a proper SOLID manner, you will want to separate the logic for:

  • Parsing the HTML into a DOM tree

  • Parsing the DOM element of an individual match into your own class

  • Saving a match into your database

  • Iterating over the list of matches on a single page

  • Iterating over the list of result pages on the website

  • Handling connection errors / retrying

  • Rate limiting to avoid getting your ip banned

The yield keyword makes this really easy and readable, especially if you combine it with async/await:

async Task ScrapeMatches(Uri uri)
{
    await foreach (MatchData match in AllMatchesFrom(uri))
    {
        _db.Insert(match);
    }
}

async IAsyncEnumerator<MatchData> AllMatchesFrom(Uri uri)
{
    await foreach (HtmlDocument html in AllMatchPages(uri))
    {
        foreach (HtmlDiv div in MatchDivsFromPage(html))
        {
            yield return MatchFromDiv(div);
        }
    }
}


async IAsyncEnumerable<HtmlDocument> AllMatchPages(Uri uri)
{
    Uri nextUri = uri;

    while (nextUri != null)
    {
        HtmlDocument html = await LoadHtml(nextUri);
        yield return html;

        DOMElement nextPageLink = html.GetElementById("nextpage");
        nextUri = nextPageLink;
    }
}

IEnumerable<HtmlDiv> MatchDivsFromPage(HtmlDocument html)
{
    DOMElement root = html.GetElementById("matchlist");
    foreach (var child in root.Children)
    {
        if (child.ClassList.Contains("match"))
        {
            yield return child;
        }
    }
}

MatchData MatchFromDiv(DOMElement div)
{
    ...
}

So as you can see, on the high level logic, iterating over all the matches from the whole website is a simple for loop. If you stopped the process at a certain page, you can easily resume it from there. You can handle rate limiting and retrying in the LoadHtml function. This solution also loads only one page and one match at a time, so it has a low memory consumption.

Some of these can be replaced with LINQ, which works easily because LINQ is just syntactic sugar around the yield return iterator logic.

If you were to build something like this without iterators, the naive solution would either store all the data into lists before passing it on to the next step, which is not feasible for large amounts of data. Or you'd have to make heavy use of callbacks, which hurts readability and prevents you from using LINQ. Or abandon all hope of separating concerns and build a single spaghetti function with five nested loops.

Does this help?

1

u/cob_258 Dec 10 '21

I'd say the only one here you should probably never use is Volatile. There are almost no cases where you need to use it.

Never tried c# in embedded systems, only c/c++ and volatile is necessary in some cases (GPIOs, interrupts..etc), so depending on how dotnet is implemented it might be useful.

7

u/[deleted] Dec 10 '21

I've worked at places that treated extension methods as the work of the devil

2

u/[deleted] Dec 10 '21

Aren't extension methods not mockable? I think it's something that all static methods lack, the ability to be mocked. Haven't done my homework so I could be wrong.

5

u/[deleted] Dec 10 '21

They are not, but they are testable.
I sometimes transplant common tasks (think someCollection.Any() == false to someCollection.None() ) for readability

2

u/Relevant_Monstrosity May 12 '22

Extension method binding can be overridden by declaring the same signature in the namespace of the caller.

1

u/[deleted] May 12 '22

You mean declaring another static with the same name? Do you have any examples? This sounds really cool

2

u/Relevant_Monstrosity May 12 '22

https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/language-specification/overload-resolution

The full algorithm is documented here.

Suppose that you are working in Mine.Tests and the extension is in Theirs.Extensions.

You implement an overloaded extension method in Mine.Tests matching the signature of Theirs.Extensions.

Now because your extension's namespace is "closer", the binder will bind yours.

1

u/[deleted] May 12 '22

Thank you!!

7

u/BeakerAU Dec 10 '21

What's wrong with yield?

16

u/[deleted] Dec 10 '21

the first time I saw @object as a variable name I about lost my shit

18

u/cat_in_the_wall @event Dec 10 '21

i thought this too but sometimes you just really ought to call something "event".

5

u/FizixMan Dec 10 '21 edited Dec 10 '21

I agree.

EDIT: I was just joking around. Sometimes you just really ought to call/flair something/cat_in_the_wall "event".

3

u/jonwah Dec 10 '21

Why is this getting downvoted? I've written multiple applications for sports management, where there are legitimate dB entities called events.. so @event does make a lot of sense for a local variable name..

1

u/lvlint67 Dec 10 '21

Maybe it would be nice of event was a valid identifier... But its not.

myEvent is my usual fallback. It looks dirty and reminds me of Perl.. Bit it tends to work and is more readable than @event

2

u/jonwah Dec 10 '21

If you try and name a variable event, @event is what VS auto renames it to..

And I don't really like the look of foreach(var myEvent in events)

To be fair I don't like @event either, but whatevs, it's a local variable name, I just name it and move on with my life

2

u/[deleted] Dec 10 '21

How the hell does it goes spookier every time that well. Good job.

5

u/jugalator Dec 10 '21 edited Dec 10 '21

Forbidden != unusual. These are unusual and it's borderline calling Span<T> forbidden given that it does for stackalloc. Like half of these or more are oriented around optimizing interop or low level code that is sometimes crucial for the standard library, wrappers etc. But yes, some of them have been replaced by better methods now that don't need you to go unsafe first.

Speaking of unusual keywords, I sometimes (rarely) use preprocessor directives to create a slightly different build in Debug vs Release, usually around how the application starts up. The C-like #if DEBUG / #else / #endif are perfectly fine in C# and Visual Studio will even highlight the code for you to tell when it'll be run.

5

u/_MovieClip Dec 10 '21

I have only seen goto used in C# once in my career and it was by a guy that did weird shit because he thought it funny. Our expression at the time was accurately depicted by the meme.

4

u/yanitrix Dec 10 '21

implicit forbidden? lol
also, stackalloc is useful for optimizing things, fun stuff to do actually

3

u/saponsky Dec 10 '21

Why volatile though? Can someone ELI5?

8

u/[deleted] Dec 10 '21

[removed] β€” view removed comment

5

u/botterway Dec 10 '21

Eh? Volatile is simple. It's just a compiler hint that says "use the actual value in memory, not a recently-cached version of that variable which may not represent the value if it's been updated by another thread". It's not complicated. It's a performance thing, that stops optimisation by the compiler and CPU leading to race conditions.

You can argue that in most cases the same can be achieved with a lock (locks do the same thing, forcing cache invalidation for variables), but volatile won't result in a deadlock, so sometimes it makes code simpler.

Stop trying to make simple concepts in the language seem unobtainable or black magic. It's basically gatekeeping.

3

u/[deleted] Dec 10 '21 edited Dec 10 '21

[removed] β€” view removed comment

1

u/botterway Dec 10 '21

Right. Volatile is a compiler hint to avoid certain optimisations. It's not simple, but it can be useful.

To a certain extent, this thread (my post and replies) shows the danger of replying casually to a thread about subtle usage functionality, without checking my wording makes sense. I understand volatile (I used to even do an interview question about reordering and volatile, back in about 2013) but things get rusty after years, and I rarely use volatile. Good clarification though.

As for the most misunderstood thing, I guess ConfigureAwait wins, but it's not a keyword, so I'll give it to you. 😁

1

u/[deleted] Dec 10 '21

[removed] β€” view removed comment

1

u/Wixely Dec 10 '21

multiprocessor system

That is a system with multiple processors that each have their own L1/L2 cache etc. On your average consumer desktop computer they are not multiprocessor, they are multicore. That documentation seems to be pointing out an edge-case and it makes sense as each CPU would have its own cache and therefore not have the same guarantees running on a server compared to running on an average users machine.

-1

u/botterway Dec 10 '21

Lol. What you quoted basically says what I said. And it makes sense today because everything is multicore with L1 and L1 caches.

Simple fact is, if you're declaring a variable that will be used across multiple threads but is a base type (so updates and reads will he atomic) it's a good idea to declare it volatile to avoid caching and reordering nuances that might otherwise cause race conditions. So to say "you shouldn't use it" is daft.

2

u/[deleted] Dec 10 '21

[removed] β€” view removed comment

→ More replies (6)

3

u/martindp_ Dec 10 '21

dynamic pls

3

u/Splamyn Dec 10 '21

stackalloc + Span<T> is the best thing that happend to C#
Change my mind

3

u/No_Boss_3626 Dec 10 '21

In college I used goto in one of my first assignments and the professor put my code up on the projector and roasted me infront of the class.

4

u/[deleted] Dec 10 '21

Looks like someone should read the documentation

5

u/insulind Dec 10 '21

Regardless of the fact non of this is 'forbidden', this video is also shit...

2

u/voizs Dec 10 '21

what is wrong with volatile?

2

u/iwueobanet Dec 10 '21

Except for makeref and goto, this is bullshit. They all have their valid uses.

2

u/themidnightdev Apr 01 '24

Goto is definitely cursed, i'll give OP that.

2

u/[deleted] Dec 10 '21

lmao

2

u/snow_coffee Dec 10 '21

Wow a video nobody will do it so effortlessly covering almost everything, thanks

1

u/thecryingman32 Dec 10 '21

Whats the song at the end? Kinda sounds familiar

1

u/[deleted] Dec 10 '21

@ can also be fine in some situations. E.g. var event = ....

1

u/tester346 Dec 10 '21

@ is very fine

unsafe/fixed I've seen mostly for perf like hardware intrinsics

goto is viable, rarely, but viable.

1

u/[deleted] Dec 10 '21

Implicit operators are awesome.

1

u/[deleted] Dec 10 '21

Is the @ a sql declaration mix up? If so, I get that.. I’m forever mixing syntaxes by mistake.

The GoTo is inexcusable tho! Haha!

3

u/thedwalker Dec 10 '21

The @ is used to prevent name collision with a keyword.

1

u/[deleted] Dec 10 '21

Oh of course.. int. fml I didn’t even see that.

1

u/gevorgter Dec 10 '21

I forgot that goto exists :) and did not know about declaring variables with @

1

u/[deleted] Dec 10 '21

Whats wrong with using implicit operators? We are doing this some times in our company to reduce code needed to map from one type into another or to get results out of a type

1

u/QuietusPlus Dec 10 '21

This is so dumb πŸ˜‚

1

u/sards3 Dec 10 '21

Wow, I didn't even know that the volatile keyword existed in C#.

1

u/[deleted] Aug 18 '22

What's wrong with yield?

1

u/clestrada12 Dec 10 '21

I use @ with stream writer. Instead of having to put something in front of each escape character

12

u/cob_258 Dec 10 '21

The @ in this case is used to give a variable a reserved name, in the given example the variable of type int is named int

1

u/lsgrv_ali Dec 10 '21

I have been learning c# almost for 2 years and I still don't know any of these. FUCK

3

u/yanitrix Dec 10 '21

tbf these are used in very specific conditions, most of them are used for low-level optimizations. I'd say yield return, yield break and implicit are more 'normal' - more widely used and also very useful

1

u/lsgrv_ali Dec 10 '21

Oh, thanks

3

u/chucker23n Dec 10 '21

I've been writing C# for a decade and a half and have yet to use stackalloc or volatile.

1

u/lsgrv_ali Dec 10 '21

oh God, at least I know why we are using @ in int @int = 10; . But have never used it

1

u/Palmquistador Dec 10 '21

You can use whatever tf you want in JS according to a post I saw earlier. Maybe give that a go.

1

u/Floydianx33 Dec 10 '21

What is this garbage?

1

u/Graphene Dec 10 '21

Implicit, I love implicit

-1

u/[deleted] Dec 10 '21

I never learnt C# before, but I wanted to know why people use that language. If someone could enlighten about why C# is used it would be amazing

6

u/Crozzfire Dec 10 '21

Because it's easy to use (has a lot of quality of life features and is hard to mess up in the same way as e.g. c++), it looks good, runs mostly everywhere, has a large community, many libraries and it performs well.

2

u/[deleted] Dec 10 '21

Because it's a good language?

-4

u/rd07-chan Dec 10 '21

. But have never use

because Microsoft is the best

-7

u/doweknowyou22 Dec 10 '21

No wonder people prefer Java. Less keywords, more productivity.

Let the down vote begin

9

u/Cbrt74088 Dec 10 '21

less keyword: true.

more productivity: absolutely false.

-1

u/rd07-chan Dec 10 '21

it was hard to not downvote, but again C# is the best cuz Microsoft is the best

0

u/[deleted] Dec 10 '21

[deleted]

11

u/edgeofsanity76 Dec 10 '21

Yeah I use this all the time

0

u/[deleted] Dec 10 '21

[deleted]

31

u/winggar Dec 10 '21

I think flipping yield and fixed would make sense here

12

u/ethandjay Dec 10 '21

yeah yield works as babby's first weird reserved identifier

0

u/AlgoH-Rhythm Dec 10 '21

Uhh I was using it like day one in unity with coroutines

3

u/ethandjay Dec 10 '21

Good for you big man

1

u/AlgoH-Rhythm Dec 10 '21

Just saying what you're saying is completely wrong lol

0

u/[deleted] Dec 10 '21

[deleted]

9

u/cat_in_the_wall @event Dec 10 '21

i only counted 2. makeref and goto. the rest are either occasionally useful or even simply required when doing interop with native code. i have learned to embrace the interop.

0

u/[deleted] Dec 10 '21

[deleted]

6

u/cat_in_the_wall @event Dec 10 '21

(i am not downvoting you here)

if goto isn't on your list, which 3 were?

21

u/user_8804 Dec 10 '21

fix your nasty nested loops instead of using goto you pagan

4

u/pHpositivo MSFT - Microsoft Store team, .NET Community Toolkit Dec 11 '21

There are still cases where goto is valid. For instance, if you have a perf sensitive method that would have multiple return points, you might just place a return at the end and redirect your other returns to just goto there. This would lead to better codegen in many cases, as the JIT wouldn't have to emit multiple epilogues for the methods to pop registers back from the stack and return. As a result the overall code size would also likely be smaller. Sure, a very niche case, but there are legitimate use cases.

6

u/[deleted] Dec 10 '21

[removed] β€” view removed comment

4

u/SirSooth Dec 10 '21

It's funny cause he calls them low level here when they are in fact high level constructs.

I think OP should learn the language instead of making memes.