Тёмный

6 C# keywords you (probably) never had to use 

Nick Chapsas
Подписаться 295 тыс.
Просмотров 68 тыс.
50% 1

Become a Patreon and get source code access: / nickchapsas
Check out my courses: dometrain.com
Hello everybody I'm Nick and in this video I am going to cover 6 C# keywords that you almost definately never had to use. We will see what those features are and explain what they do alongside with examples on how they actually work.
Timestamps
Intro - 0:00
checked/unchecked - 0:40
unsafe - 3:36
fixed - 7:14
sizeof - 10:41
stackalloc - 13:17
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: bit.ly/ChapsasGitHub
Follow me on Twitter: bit.ly/ChapsasTwitter
Connect on LinkedIn: bit.ly/ChapsasLinkedIn
Keep coding merch: keepcoding.shop
#cleancode #cleancoder

Опубликовано:

 

15 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 227   
@Sporbus
@Sporbus 3 года назад
In case anyone wonders about the line using the -> operator: pointer->ToString() is the same as (*pointer).ToString() So, it means, "get the int from pointer and call ToString() on it"
@codemonkey6173
@codemonkey6173 2 года назад
and the parens around *pointer are needed due to operator precidence
@pxolqopt3597
@pxolqopt3597 Год назад
This is old news for anyone with the smallest amount of experience in C or C++
@znefas
@znefas Год назад
more formally, it's not "getting an int", but rather dereferencing for you
@magnusm4
@magnusm4 6 месяцев назад
@@pxolqopt3597 It's news to us who never touched C or C++(whose file type is called cpp) even after seeing C and C++ code several times.
@SimonClarkstone
@SimonClarkstone 2 года назад
"checked" is useful in some non-low-level code too, when converting from 64-bit IDs in a database to 32-bit IDs in an API.
@IvanRandomDude
@IvanRandomDude 3 года назад
Unsafe is C trying to fool us into using it
@unsafecast3636
@unsafecast3636 3 года назад
_takes your hand_ join me in the dark side for real though C is addicting, you should try it some time
@Xotchkass
@Xotchkass 2 года назад
@@unsafecast3636 nah. Lack of normal build system and package manager kills any motivation to write anything more serious than helloworld's in it.
@switchblade6226
@switchblade6226 2 года назад
@@Xotchkass i think youre forgetting about cmake, conan & vcpkg
@siriusblack9999
@siriusblack9999 3 года назад
i've had to use all but one of them, i've never used stackalloc, but since i'm working with C# to C++ interop, these concepts are actually used quite frequently :P
@nickchapsas
@nickchapsas 3 года назад
Damn I didn't know that people still do C# to C++ interop. That just blows my mind.
@Kalisparo
@Kalisparo 3 года назад
@@nickchapsas we do it to cheat in videogames of course... You can inject a .net CLR into an unmanaged process and detour between your unmanaged, into your managed space and back out. Could be used for monitoring tools as well I guess?
@iGexogen
@iGexogen 3 года назад
@@nickchapsas I use interop in mobile xamarin projects, we have some library implementing digital signature and encryption in GOST algorhytm, it is implementing Microsoft C++ CryptoApi, only way to use it on mobile is via interop. Only things I use for it is Marshal class and sequental layouted structs.
@siriusblack9999
@siriusblack9999 2 года назад
@@nickchapsas well i'm writing a C++ library for unity, so most of these things have at least cropped up at some point, though we do our best to limit it, since it does add a lot of complexity
@themiwi
@themiwi Год назад
​@@nickchapsas try calling a Win32-API...
@nielle1963
@nielle1963 3 года назад
When reading the title, I definitely assumed at you would cover “volatile”. :)
@nickchapsas
@nickchapsas 3 года назад
Funny enough, volatile is in the part 2 of this video :D
@najibmestaoui6950
@najibmestaoui6950 3 года назад
Same thing that poped in my head lol
@iGexogen
@iGexogen 3 года назад
I don't think volatile is applicable to this topic. I completely agree about all that unsafe stuff, it is almost never needed even if you sometimes work with unmanaged code like me. But volatile is not about low level code, it is about thread-safety in high level code, many people use it because it is more convinient way than explicitly using Interlocked class.
@nickchapsas
@nickchapsas 3 года назад
@@iGexogen The topic isn't about low level code. It's about keywords that you don't usually see used in C#. I just happened to have grouped many low level stuff in one video to help it be easily consumed.
@iGexogen
@iGexogen 3 года назад
@@nickchapsas It will be interesting to see how many of commentators actually use volatile, I think that unity guys must be using advanced multi-threading. It was suprising for me that you never needed it, I suppose lock statements and concurrent collections is enough for all your async purposes. Waiting for part 2)
@bilbobaggins601
@bilbobaggins601 3 года назад
I am so glad that i found this channel. It always keeps my attention, and the concepts discussed are usually so intriguing
@chiwai1986nl
@chiwai1986nl 3 года назад
When doing image processing, unsafe is the best option for performance.
@twiksify
@twiksify 3 года назад
I've used sizeof a few times, it's useful when implementing low level integrations that require fixed package sizes. When simulating a TCP/IP protocol for instance.
@barmetler
@barmetler 2 года назад
I want to point out something about pointers in C#: in C#, the star is part of the type. In C++ and C, the star is part of the declarator. What does this mean? In C#, "int* a, b;" will declare two int pointers. In C++, "int* a, b;" will declare an int pointer and an int. This is why we align stars and ampersands (for references, I'm not talking about the adress-of operator) to the right in C++. Because it is part of the declarator: "int *a, b; int *x, *y;" So if someone puts the star on the left in C++, that doesn't mean they have different style taste, it just means they don't understand how it actually works.
@samwhaleIV
@samwhaleIV 2 года назад
Really solid explanation. Thank you.
@BGroothedde
@BGroothedde 2 года назад
I agree mostly, with the exception of your last remark. I use right-aligned operators too, but I also understand why people use left aligned operators. Especially in businesses where multiple declarations in a single line are forbidden in their coding standard (a lot of companies have this as a rule). I would argue that aligning them to the left can make it a lot more clear to the reader what a variable or member can contain, there is a lot of debate of semantics versus technicality here. Saying someone does not understand how it works because you do not agree with their choices, is not a constructive point. I have had people that designed compilers explain to me why they used left aligned.
@barmetler
@barmetler 2 года назад
@@BGroothedde I guess I was being a little too general here. But 90% of the time, people put it on the left because they don't understand the implications of it. Maybe not in a job setting, but when people make the decision themselves. We can argue about good practice, but that never ends well. My stance on style is just to do what the project you're joining already does, so if a company puts the star on the left, I'll do that too. But if you see a star on the left in a personal project, it's an _indication_ that they lack some understanding of the language. But frankly, I was unaware that some companies do it, because it is imo just incorrect, the star belongs to the declarator. But if you don't ever group declarations (which I also don't do), then it might not matter so much.
@deanjohnson8233
@deanjohnson8233 2 года назад
Saying the star is not part of the type in c++ is nonsense. If that was the case, std::is_pointer and std::is_pointer should return the same value. Obviously they don’t and there are plenty of other examples where in type contexts whether something is a pointer type or not matters. I get what you are saying about multiple variable declarations, but I would contend that is a defect of the parsing rules of the language. In all other cases, you need to consider pointer/reference as part of the type of the variable.
@barmetler
@barmetler 2 года назад
@@deanjohnson8233 I don't think you understood what I said. Of course it is part of the type whether something is a pointer or not. But in the declaration statement, the star is not part of the token that describes the type, which is proven by the example I supplied. Also, a defect? It would be incredibly easy to "fix" if it was. It's by design.
@curtisdh4269
@curtisdh4269 3 года назад
Minor complaint about the the thumbnail. I'd love to be able to see these commands before I click on the video instead of them being blurred out, it'd peak my interest and give that effect of like "oh what does that keyword do"
@curtisdh4269
@curtisdh4269 3 года назад
@@lorinatzberger3624 Imo the clickbait would be more enticing if it wasn't blurred.
@curtisdh4269
@curtisdh4269 3 года назад
@@lorinatzberger3624 Fair point
@willemschipper7736
@willemschipper7736 3 года назад
You have such a great channel, I always learn something!
@SamCarleton
@SamCarleton 3 года назад
Thanks for sharing, I didn't know about a number of these. They help explain how to interact with unmanaged DLL's without having to resort to a C++/CLI layer, like I have in the days gone by. Thanks again!
@lazartrajkovic5911
@lazartrajkovic5911 2 года назад
In 'normal' or usual C# (C# only development) majority of these keywords probably wouldn't be used. But if your C# program works with unmanaged code (C++, Fortran...) these keywords are pretty useful. For example sizeof is used for types interoperability. You must be specially careful when mixing managed and unmanaged code. Another great video, Nick!
@superpcstation
@superpcstation 3 года назад
I love your videos, but your advanced c# stuff is extra awesome.
@klightspeed
@klightspeed 3 года назад
2:17 - casting an IntPtr to an int under 64-bit where that int would overflow will also throw an OverflowException, as the conversion occurs in a checked context. Using unchecked will also silence some overflow warnings, e.g. when working with the lparam in WndProc. 5:34 - that's a 64-bit pointer, so 6:39 you probably want to cast to a long, as casting to an integer will chop off the upper 32 bits of the 64-bit pointer. 9:16 - C# strings are not null terminated - the implementation just happens to put zeroes in the slack space after the end of the string.
@tslivede
@tslivede 2 года назад
In the C# language specification, section "22.7 The fixed statement" it says: A char* value produced by fixing a string instance always points to a null-terminated string. Within a fixed statement that obtains a pointer p to a string instance s, the pointer values ranging from p to p + s.Length ‑ 1 represent addresses of the characters in the string, and the pointer value p + s.Length always points to a null character (the character with value '\0').
@MichaelMiller-rg6or
@MichaelMiller-rg6or 3 года назад
Excellent video! I actually didn’t know about checked or stack_alloc.
@penetrarthur
@penetrarthur 3 года назад
Great work! Sounds like a video on stackalloc is already being filmed.
@sonicbhoc
@sonicbhoc 2 года назад
I do embedded systems programming and I can tell you I use all of those keywords with some frequency. Except stackalloc. That is a cool trick I'll have to remember.
@mirabilis
@mirabilis Год назад
I've used unsafe code in one of my projects. Used pointers to speed up bitmap calculations.
@InterRubke
@InterRubke 3 года назад
We do image manipulations in unsafe mode for performance reasons. Best to do this in a seperate project.
@kenbrady119
@kenbrady119 2 года назад
My first C# program in 2003 (the one where I 'cut my teeth' on C#, transitioning from C++) was an audio/MIDI app. Interacting with the WIN32 audio subsystem required allocating buffers, pinning them, and passing them via interop into unmanaged waveIn__ routines of the Winmm module. It was "unsafe" as heck, but what to expect from a C++ programmer :)
@SpicyMelonYT
@SpicyMelonYT 2 года назад
The sizeof keyword is very useful when dealing with gpu calls. I do this a lot in unity using compute shaders and compute buffers
@benjaminclehmann
@benjaminclehmann 3 года назад
The unsafe examples are potentially useful for interop. Although generally you use IntPtr and Marshalling when possible. Also, fixed lets you use fixed-sized arrays without initializing one. It's very niche but it's the only thing I've actually used fixed for.
@nickchapsas
@nickchapsas 3 года назад
And it can also be used with struct which I wanted to show but I totally forgot 🤦‍♂️
@magnusm4
@magnusm4 6 месяцев назад
My first thought was interop, though I didn't know this word for it. Otherwise my second was creating your own little compress program. Taking all the variables into an array of pointers. Go through each pointer and look for the same char or int in the same spot. Put that char/int in it's own struct variable along with it's place in the pointer, and remove it from the original variables. Then to zip it up. Just run a function that takes the struct and puts the char/int into the coordinate place given. Can probably do that better using a dictionary but I just thought of a struct for simplicity. Probably a poorly optimized mess of a program that takes more memory than anything but I just liked to think up the concept of a zip compress program yourself by reducing the address values.
@Flubberia
@Flubberia 3 года назад
Cool. Actually we are using sometimes unsafe and stackalloc in our projects where we need really high performance (hot path). Also playing with structures to achive like super performance 0 allocation lock free hype stuff. =)
@Kalisparo
@Kalisparo 3 года назад
Being able to use unmanaged code can be extremely beneficial when you're dealing with optimisations and having to do a lot of calculations/large data sets. In addition, you should learn how to use weakrefs for much better io performance allowing you to use large amounts of memory better when you would otherwise have a lot of disk io. Server applications are really good for this. Things starts getting strange when you need to move in and out of managed space, like you need to have an unmanaged thread (like in a program written in CPP) suddenly enter managed space and then back out.
@Pedro5antos_
@Pedro5antos_ 3 года назад
great vid, mate!
@ankushmadankar1756
@ankushmadankar1756 3 года назад
Informative!!
@TheKataan
@TheKataan 3 года назад
Resharper generates unchecked gethashcode by default. So that one I see often. Used all the unsafe features in my serialisation library (NHessian). Fastest way to calculate equality and hashcode for strings (char arrays) as well as decode Unicode.
@MrAymenmatador
@MrAymenmatador 3 года назад
Great video. This won't be weird if you are a C developer. Actually you had to deal with most of those keywords every day
@AlexxXRecorD
@AlexxXRecorD 2 года назад
Nice, thanks so much!)))
@staskovalevsky
@staskovalevsky 3 года назад
Thanks for your videos! One of the best .net youtuber
@cheebadigga4092
@cheebadigga4092 Год назад
All of these can be very handy when interfacing with C code (P/Invoke etc.) to reduce heap allocation in C# code when you know what you're doing..
@adamschneider868
@adamschneider868 3 года назад
That sizeof code example is pretty damn cool
@killpopers
@killpopers 3 года назад
I've used all of these but only because I have done some low level graphics stuff from C# for intrest rather than any real use but it an example of when you might do such a thing
@kleinmike
@kleinmike 3 года назад
I like to mod in games. and to know that you can do pointers natively in C# without a 3rd party dependency is great
@MarkusSchaber
@MarkusSchaber 3 года назад
There's also a project level property true which can also be set in the project properties (at least in Visual Studio), tab "build", then "Advanced", it's called "Check for arithmetic overflow". It sets the global default to "checked", then you can use the "unchecked" keyword to opt out. :-) From the language design view, they should have made "checked" the default, but nowadays, it's far too late to change the default, breaking 20 years of code. :-)
@JoeBonez
@JoeBonez 3 года назад
The one time I’ve used unsafe and pointers was using writable bit maps for creating height maps.
@xxdeadmonkxx
@xxdeadmonkxx 2 года назад
It is all useful when it comes to create lowlevel graphic api wrappers etc btw "fixed" keyword can be used inside structs to create "embed" arrays inside struct if you really need cache friendly data with arrays in ECS or something
@BittermanAndy
@BittermanAndy 3 года назад
I've used all except stackalloc. But not often. Apart from unchecked, which is needed for good implementations of GetHashCode (among other things, but that's the common one).
@gipsnichmeer
@gipsnichmeer 2 года назад
When you started typing i thought: Stop! I never had ro use uint before lol
@TheRuko15
@TheRuko15 2 года назад
I've used stackalloc and sizeof once; when generating waveform images of hours long audio files.
@MrKulkoski
@MrKulkoski 3 года назад
I actually have a use for the combination of unsafe, unmanaged and sizeof combo in a project I'm doing, lol.
@unqualifiedgamer6252
@unqualifiedgamer6252 3 года назад
Was messing around with silk . net a c# wrapper for stuff like opengl, vulkan, glfw and other common game development libraries. and had to get to try and understand unsafe, fixed and how pointers worked. it was very confusing at first, coming from .net mvc background. unfortunately I had to postpone the project indefinitely when covid happened, so I barely remember any of it anymore.
@keithrobertson7579
@keithrobertson7579 2 года назад
Some other keywords which devs don't use often but should know how to use them: `volatile` for thread interaction, `extern` for defining PInvokes, and `implicit` and `explicit` for type conversion operators.
@shanehebert396
@shanehebert396 3 года назад
I've seen some unsafe code in graphics manipulation code. It may come into play if you need to access some types of hardware or something as well (if you're writing your own code and not using a library).
@henke37
@henke37 2 года назад
C sharp generally doesn't run in contexts that have access to memory mapped hardware.
@Micz84
@Micz84 3 года назад
Unsefe, stackalloc, fixed and sizeof are good to know if you are using C# for Unity and you are using data-oriented technology stack. Stackalloc is good for avoiding false sharing.
@bishop8958
@bishop8958 3 года назад
I actually learned about Unsafe code because of unity, Though I didn't know about stackalloc.
@raznagul
@raznagul 3 года назад
I'm quite suprised by checked/unchecked. I always thought checked was the default.
@phizc
@phizc 3 года назад
It's checked at compiler time, so I sometimes have to do const int Default = unchecked(0xCA7F00D1); At runtime it is unchecked unless the compiler option CheckForOverflowUnderflow is set.
@Odinhaus
@Odinhaus 3 года назад
I have used them all, and then some :)
@David-id6jw
@David-id6jw 3 года назад
I used checked/unsafe/fixed a lot back in.. gosh, .NET 1.1 days, when writing a scientific/image processing application. Obviously no stackalloc because it didn't exist back then, though I have used stackalloc in a small, high performance algorithm recently. Sizeof is the one I find most niche, despite it also being the one that most people would be familiar with. I know an int32 is going to be 32 bits == 4 bytes, so I don't need code to tell me that. But it's also kind of like using nameof(parameter) to get a string representation of a parameter or property or whatever - you don't need it _right now_ , but it makes maintaining it later a little easier.
@JohnEBoldt
@JohnEBoldt 2 года назад
I thought you were going to include the goto statement, which I have only seen used once (not by me!) The last time I used goto was 40 years ago when I was doing Fortran!
@Bomag
@Bomag 3 года назад
Some of these are less often used like checked/unchecked, but these are far from 'definitely never had to use' territory for me personally. It isn't even about performance either, just the constant need to have easy to use tools for PInvoking vendor libraries, system calls, etc. Some of these are still being improved like the stackalloc you mention wasn't possible to use in safe contexts until recently with the addition of Span. I'm glad Microsoft keep improving this space to be honest.
@micmacha
@micmacha 2 года назад
C# is a powerful and, *if you know what you're doing*, a potentially very fast language; but sometimes I worry about the size and inconsistency of the lexicon. We have changes in LINQ, introduction of C syntax, all of these things, which have worked out so far but tend to leave novices feeling out of their depth.
@TheoWerewolf
@TheoWerewolf 3 года назад
The sizeof/unmanaged thing seems odd. When you pointed out that sizeof works with structs that didn't surprise me because internally, base types like int and byte ARE structs (except string which is an oddball type). "int" maps to struct Int32 {}... "long" maps to struct Int64{} and so on. Which now has me wondering why they would consider a struct to be "unmanaged". It does make a kind of sense in that structs are "value" objects not reference objects and have to have concrete existence when declared... but I'm not sure how that makes it "unmanaged".
@sebasortix
@sebasortix 2 года назад
I was grindering some weed when you declared the snoopDog variable.... I felt so alluded... 🤣
@micmacha
@micmacha 2 года назад
As an experienced C programmer these are great. You have to worry about your own pointer safety, but Jesus is it running fast.
@marna_li
@marna_li 3 года назад
One of the main reasons for using these is to write your own .NET bindings to unmanaged code - like P/Invoke to some DLL written in C/++ or even Rust. But nowadays there are tools that can generate that for free.
@BittermanAndy
@BittermanAndy 3 года назад
A tool such as...? I don't need to do it often, but it's always a pain when I do.
@Keldor314
@Keldor314 3 года назад
Guess what those tools use under the hood. ;-)
@KanashimiMusic
@KanashimiMusic 2 года назад
About the checked/unchecked keywords: unchecked is USUALLY unnecessary, because unchecked is the default state at runtime. However, CONSTANTS are checked at compile time by default, so if you want to cause an integer overflow with constants, the compiler will throw a compile time error at you and tell you to use the unchecked keyword. So for example, this: const int CONSTA = int.MaxValue; const int CONSTB = CONSTA + 42; will not compile. It will only compile if you write CONSTB = unchecked(CONSTA + 42);
@daniell.raharitahiana5727
@daniell.raharitahiana5727 3 года назад
I remember using unsafe code to write a weird implementation of a voronoi noise bitmap generator using pointers. It was more of an exercise than it was of any actual use, and it was slow as all heck, but it was definitely fun to mess around with lower level stuff in C#. But hey it's called unsafe for a reason, right? (•~•)
@stephenyork7318
@stephenyork7318 3 года назад
Real world example...I once had to index multiple millions of records of electoral role details on a laptop. The machine was disconnected and SSDs weren’t around at the time. To make the thing work in a realistic time it was an in memory solution. When I put everything in memory with a dictionary there simply wasn’t enough RAM for it to work. I ended up implementing a very lean hash table with collision detection using unsafe blocks and we managed to load everything in with room left over.
@nickchapsas
@nickchapsas 3 года назад
Wow, in C#?
@HighwaysTravel
@HighwaysTravel 3 года назад
For me it's checked and unchecked are new keywords. But others are good to revise 😁
@st0ox
@st0ox 3 года назад
From now on I will always call my unsafe pointers snoopDog
@nimrodel3924
@nimrodel3924 3 года назад
I litterally use all of these daily, currently working on 3D graphics software 😉
@brentsteyn6671
@brentsteyn6671 3 года назад
I know a little bit why you would use it. But then... WHY?
@GhostTyper
@GhostTyper 2 года назад
Back in .NET 2, 3, 3.5 and 4 i used pointers all the time, because those versions were sooooo slooooow.
@superpcstation
@superpcstation 3 года назад
Without watching the video, here are three my guesses: Global Goto Unchecked
@superpcstation
@superpcstation 3 года назад
Lol i only got one right 😅
@nickchapsas
@nickchapsas 3 года назад
You technically got Global right as well. It will be in part 2 :D
@renich6666
@renich6666 3 года назад
I've used all of them.
@Terrados1337
@Terrados1337 3 года назад
I always just assumed c# had pointers :D Now that I know, I will have some fun with it :D Must leave unmanagable legacy code for generations to come
@igorthelight
@igorthelight 3 года назад
You! Get back here! :-)
@phizc
@phizc 3 года назад
It's hardly legacy code. Pointers are useful for interop and low level performant code. In dotnet5/C# 9 we've also now got function pointers. Stackalloc also returns a raw pointer by default, that's why he wrote "Span" instead of just "var".
@Terrados1337
@Terrados1337 3 года назад
​@@igorthelight muhahah and now I build an undocumented nuget package and use botnets to download it constantly so its always on top of search results xD
@igorthelight
@igorthelight 3 года назад
@@Terrados1337 Ha-ha :-)
@sewer56lol
@sewer56lol 3 года назад
Aaaaa. I mod native games using C# on a regular basis and I practically use those keywords daily. I was expecting something of the likes of volatile ahahaha.
@lithium820
@lithium820 3 года назад
i always imagined sizeof is pretty universal across langs
@HamishArb
@HamishArb 3 года назад
I use all of those very often, except stackalloc (since it can stack overflow) because it runs faster. I was expecting the 4 __ keywords to be on this video lol. I do not use the __ keywords often lol.
@JohnLudlow
@JohnLudlow 3 года назад
I have had to use sizeof once but it's not exactly common in C#. I'm surprised goto wasn't on the list.
@danielhadad4911
@danielhadad4911 3 года назад
What did you use it for?
@mk72v2oq
@mk72v2oq 3 года назад
I always use all the unsafe stuff. This is just the way to write real high performance code. And you are VERY underestimating the performance gain. In some cases it can make code hundreds or even thousands times faster. But yeah, this is not common approach for C#. Such things are really useful only when you are familiar with C/ASM level of things.
@nickchapsas
@nickchapsas 3 года назад
There is no doubt in my mind that coding like this would yield great performance gains but it comes with a lot of shortcomings. Code needs to be easy to maintain, easy to work with and easy to get new hires to work on. As a hiring manager myself, I can guarantee that if I was using all those keywords in our codebase then it would be impossible to hire engineers. And at the end of the day, it is way easier to scale an app out to 100 stateless instances than optimize that single codebase.
@mk72v2oq
@mk72v2oq 3 года назад
@@nickchapsas in general - yes. But sometimes ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-7GTpwgsmHgU.html
@Cralis1
@Cralis1 3 года назад
I'm trying to work out why they defailed to unchecked. Your example of the max value is good. The answer becomes wrong, I believe. Strange that you can't override to unchecked rather.
@ashisheady8841
@ashisheady8841 2 года назад
you never need class keyword you can trust me.
@Baekstrom
@Baekstrom 3 года назад
Woohoo! I can put C++ into my C# code!
@ovidiurudi
@ovidiurudi 3 года назад
This part is usefull when you want to use some native dll functions you'll have to wrap up all those functions and "unsafe" & co will be your friends :)
@Ownage4lif31
@Ownage4lif31 3 года назад
Or couldn't you just use dll import? I've never had an issue using dll import to use my c++ functions. Barely ever used it but it works. Not sure on the limitations though
@ovidiurudi
@ovidiurudi 3 года назад
@@Ownage4lif31 right now it can be. Ten years ago when I made some wrappers over few Delphi libraries I had to do that. One of the libraries was a protocol over TCP/IP and I had some issues about how data types are stored. Honestly speaking I don't remember exactly what was the issue but when an c# app send the data to our delphi ecosystem apps it was received corrupted. Happy codding!
@ziaulhasanhamim3931
@ziaulhasanhamim3931 3 года назад
unsafe, sizeof, stackalloc are actually very useful for high-performance apps.
@jimread2354
@jimread2354 2 года назад
That's an interesting video, I've been programming in C# for nearly 15 years now and I didn't know about the checked keyword. I actually use "unsafe" quite a lot when I'm calling Windows APIs because they deal with pointers quite often but if you're doing that, you kind of have to use "fixed" or else, like you mentioned your next look at the pointer might not be valid. I also use sizeof when I'm writing out custom binary data files when I don't have access to a database.
@vladimirdoktorov1511
@vladimirdoktorov1511 3 года назад
you forgot to implement private GetHigh() method for the UnsafeExample
@KvapuJanjalia
@KvapuJanjalia Год назад
I was expecting to see likes of "__arglist", "__makeref", "__reftype" and "__refvalue" in these series, but all I saw were pretty normal everyday (or maybe, "every-month") keywords.
@corruptconverter2616
@corruptconverter2616 3 года назад
Some other keywords: __arglist, __makeref, __refvalue, __reftype
@stefanreinike6724
@stefanreinike6724 3 года назад
Use more often the "SnoopDog"-pattern :-)
@nathounathou
@nathounathou 3 года назад
420
@W1ngSMC
@W1ngSMC 3 года назад
Why doesn't the compiler just make every "new" you use in a local scope into stackalloc?
@ezra3871
@ezra3871 3 года назад
No mention of "dynamic" in this and the sequel it's just that variable type is determined at runtime
@nickchapsas
@nickchapsas 3 года назад
Dynamic is very common still, mainly due to packages like Dapper
@anonimxwz
@anonimxwz 11 месяцев назад
unsafe is used sometimes when you do renders
@DaddyFrosty
@DaddyFrosty 2 года назад
I love the video but I feel like you were worried about people not understanding char* and -> when you haven't explained memory in the video. Those that understand memory don't need to worry about char*
@aybarsacar9375
@aybarsacar9375 3 года назад
I didn’t know c# had pointers capability. And the unsafe syntax is the same as c++ syntax
@darioabbece3948
@darioabbece3948 2 года назад
I guess fixed could be used if you were to manage password or encription
@fredhair
@fredhair 3 года назад
Seems like many of these are low level enabling features which imo is better left to C or C++. C# is a great language but its never likely to get the same performance in these situations. If you want direct control of your memory you really should be using C++ or maybe rust? C# is meant to be high level and take care of low level operations for you at the expense of some performance impact. For most use cases C# is great and versatile and it can get closer to the hardware reasonably well, far better than many other high level languages e.g. python, java. StackAlloc seems to be the only one of these I would probably use in C#, for low level I would have to consider the overhead of calling into a C++ DLL vs just using these low level features.
@jerryplayz101
@jerryplayz101 3 года назад
On the subject of “stackalloc” is that at all similar to “malloc” from C? I haven’t looked too much into it, but if it means “memory allocate” (I.e. to RAM) and “stack allocate” for the prior- what does the other variation, “heapalloc” do?
@phizc
@phizc 3 года назад
malloc in C allocates on the heap. Stackalloc is like c arrays. E.g signed int numbers[3] = {4,2,0};
@jordangaines496
@jordangaines496 3 года назад
`malloc` in C allocates memory on the heap, not on the stack.
@Keldor314
@Keldor314 3 года назад
"stackalloc" is like "malloca" from C I believe. And you have to be extremely careful with it since it will become deallocated the moment you return from the enclosing function and drop the stack frame. If you want data allocated on the stack, use a struct. That's what those are for.
@Keldor314
@Keldor314 3 года назад
Regarding "heapalloc", I believe that it just does what "malloc" would do in most cases. (And I believe it's native WIN32, so unmanaged) Evidentally you can also create multiple heaps, which I suspect is something more interesting for people writing the actual OS and maybe device drivers than ordinary programmers. I can imagine where from the OS's perspective, each process has its own private heap, but of course the OS has to make all that work.
@Gastell0
@Gastell0 3 года назад
You definitely used sizeof if you ever dealt with any Windows API with Interops and Marshaling via P/Invoke, pinvoke website is life
@BufordTJustice42069
@BufordTJustice42069 2 года назад
Not the first C# pointer video with references to 69 or 420. Nnnniiice.
@Hugo-pj4bm
@Hugo-pj4bm 3 года назад
You use all of these a lot when doing graphics programming with opengl or similar
@nickchapsas
@nickchapsas 3 года назад
Yeah apparently graphics people are using those a ton. I had no idea and I’m so pleasantly surprised
@AB-cn5hb
@AB-cn5hb 3 года назад
What editor is he using? Debugging looks nice.
@nickchapsas
@nickchapsas 3 года назад
I'm using JetBrains Rider
@etopowertwon
@etopowertwon 3 года назад
I'm surprised `dynamic` is not on the list.
@user-fz3nn8pt9h
@user-fz3nn8pt9h 3 года назад
Used all of them except for 'checked'.
@najibmestaoui6950
@najibmestaoui6950 3 года назад
I pressed the thumb up icon 10x but only incremented once lol. Thumb up for the pointer arrow!
@ImSplashGG
@ImSplashGG 5 месяцев назад
C# Midudev!
@aurinator
@aurinator 3 года назад
Need units on sizes IMO...
@neilsg2001
@neilsg2001 3 года назад
Stackalloc performance gain?
@androfonthdez6870
@androfonthdez6870 3 года назад
Do volatile keyword, it is a rare one too
@nickchapsas
@nickchapsas 3 года назад
Next video alongside some other rare ones 😀
Далее
Elegant Acceptance Testing in .NET with SpecFlow
18:36
What is Span in C# and why you should be using it
15:15
Drive through the color🚗❓
00:13
Просмотров 5 млн
Прятки #nyanmp3
00:25
Просмотров 450 тыс.
C# Multithreading - Master Threads and Tasks
9:51
Просмотров 28 тыс.
Stupid C Tricks: Unsafe Functions You MUST Avoid!
9:26
The Most Useless Keyword in C?
10:26
Просмотров 68 тыс.
5 (Extreme) Performance Tips in C#
12:26
Просмотров 73 тыс.
8 await async mistakes that you SHOULD avoid in .NET
21:13
Writing C# without allocating ANY memory
19:36
Просмотров 145 тыс.
The Fastest Way to Modify a List in C# | Coding Demo
10:30