Random Finally Gets Its Missing Methods in .NET 8

Sdílet
Vložit
  • čas přidán 26. 02. 2023
  • Use code REST15 for 15% off the new From Zero to Hero - REST APIs in .NET course: bit.ly/restchapsas
    Become a Patreon and get source code access: / nickchapsas
    Hello everybody I'm Nick and in this video I will show you the new methods under the Random and RandomNumberGenerator classes that are coming in .NET 8.
    Workshops: bit.ly/nickworkshops
    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
    #csharp #dotnet

Komentáře • 89

  • @NoName-1337
    @NoName-1337 Před rokem +5

    "Mike" should play some lottery. He's always the first on shuffle.

  • @spoonfuloftactic
    @spoonfuloftactic Před rokem +2

    It's actually not a weak password just because it doesn't have the special characters! You are defining the amount of entropy, and the CSPRNG is filling it up. Adding constraints REDUCES entropy. You are rejection sampling a bunch of passwords that would fill that space.

    • @oM1naE
      @oM1naE Před rokem

      yep, he has 66 possible characters, with a length of 10 that makes 1568336880910795800 possibilities (roughly 60 bits)... that is not very much, but for making passwords more secure the length is the much better option than the alphabet size

  • @timseguine2
    @timseguine2 Před rokem +17

    Forcing a string to have at least one special character technically lowers its expected entropy which also makes it a worse password. The only reason why password guidelines usually have that rule is because if they didn't many people would never consider adding one otherwise.
    Practically it is only an issue if they are intended to be used with a password system that enforces such rules.

    • @QwDragon
      @QwDragon Před rokem +3

      Entropy is good in everage, but if hacker enumerates passwords without special digits, he can do it much faster. And users who don't have special characters are unlucky in this case regardless the entropy.

    • @asdfxyz_randomname2133
      @asdfxyz_randomname2133 Před rokem +1

      @@QwDragon But users add special characters in a very predictable manner, which means a lower entropy AND the knowledge how people add special characters, means the passwords can again be broken more easily by a word list and small modification for special characters.

    • @timseguine2
      @timseguine2 Před rokem +2

      @@QwDragon That requires them to know ahead of time that the password has no special characters. That itself is a high entropy piece of knowledge.

    • @QwDragon
      @QwDragon Před rokem

      @@timseguine2 they can enumerate logins too.

    • @spoonfuloftactic
      @spoonfuloftactic Před rokem

      @@QwDragon Basically, if you want more security make it longer or add more possible special characters. DON'T reject passwords without special characters, you are JUST HURTING YOURSELF.

  • @azz111full
    @azz111full Před rokem +22

    Is it a coincidence that Mike was always first in the shuffled list?

    • @nickchapsas
      @nickchapsas  Před rokem +4

      Yes

    • @mahdi8572
      @mahdi8572 Před rokem +4

      random is random, even if it looks like it isn't, it is still random.

    • @ryanlashkevich9615
      @ryanlashkevich9615 Před rokem +1

      Probably, dont forget about Monte Carlo fallacy

    • @nerrierr
      @nerrierr Před rokem +4

      No... there is no coincidence... no mistake... no choice.... Mike is always first... Mike is always watching...

  • @sumitjoshi_01
    @sumitjoshi_01 Před rokem +4

    Amazing, you always provide some knowledge to me. Thank You 👍🏻👍🏻

  • @DarthJane
    @DarthJane Před rokem +1

    Oh yes, this is def a great addition, and I did in fact write some of those methods myself now and again.

  • @jasoncox7244
    @jasoncox7244 Před rokem +1

    This will totally replace my roll-your-own random password I wrote 10 years ago lol. Been a while since I updated that archaic library....

  • @evanboltsis
    @evanboltsis Před rokem +1

    Pretty useful stuff, thanks!

  • @billy65bob
    @billy65bob Před rokem +2

    Some weighted stuff for the shuffle would be cool, as in a parameter to make it only shuffle a little instead of completely.
    But I suppose I can do that manually by just invoking shuffle multiple times with smaller spans across the collection.

  • @karenkhachikyan8305
    @karenkhachikyan8305 Před rokem +1

    Very useful tips, thank you! Btw, it would be great if you could share your opinion on DataTables (in terms of performance) and if there are any better alternatives.

  • @shoobidyboop8634
    @shoobidyboop8634 Před rokem

    This is great, really like shuffle. For better and fast random gen, I use a c# implementation of PCG random.

  • @zaoralj
    @zaoralj Před rokem

    I remember to have of shuffle for collections. Nice features for sure.

  • @Ayymoss
    @Ayymoss Před rokem

    How do you get the memory allocation Rider is using in bottom right?

  • @droumerda
    @droumerda Před rokem +3

    I would love a method to get a single random item from a collection, but the choices could have indepentent weights. So if I give the method the array ["A", "B", "C"] and the weights [1, 2, 3], then I would have 1/6 chance to get an "A", 2/6 chance to get a "B", and 3/6 chance to get a "C".

    • @Basement-Science
      @Basement-Science Před rokem

      @droumerda I havent tested it, but I'm guessing if your base string contains a character multiple times in these new methods, that would act as a weight. In your example "ABBCCC". Not super memory-efficient if your symbol set is large or your weights are significantly different, but probably an option.

    • @Basement-Science
      @Basement-Science Před rokem +1

      @@milanstevic8424 Of course, it doesnt solve everything. I just wrote this to say that you can _sometimes_ use this and avoid writing something yourself or searching around for it.

  • @DarianBenam
    @DarianBenam Před rokem

    Awesome! 👀

  • @LasseVagstherKarlsen
    @LasseVagstherKarlsen Před 10 měsíci

    Question to ponder: If the Shared instance was *not* thread safe, would it be more, or less, random [aka unpredictable]?

  • @OleksiiKorniienko
    @OleksiiKorniienko Před rokem +1

    It might be handy, but is it supposed to work with a collection of objects? It's infrequent use-case when we have a collection of primitives. Will this work out of the box, or should the object implement IComparable or smth?

    • @donr484
      @donr484 Před rokem +1

      Shuffle should work on a span of any type.

  • @andreaspetersen2662
    @andreaspetersen2662 Před rokem

    Right now i use string.Create combined with Random to create random strings in production.
    Example:
    private static string GetString()
    {
    return string.Create(stringLength, chars, (span, state) =>
    {
    for (int i = 0; i < stringLength; i++)
    {
    span[i] = chars[Random.Shared.Next(chars.Length)];
    }
    });
    }
    where stringLength is the fixed length the word should be, and chars are the possible range of characters

  • @jensingels5958
    @jensingels5958 Před rokem

    For passwords, it feels more like an "I use it but I hope it adds the missing features and interfaces soon". The shared random, random item, and random fill feel like a feature that will push many people in .NET8 as soon it's out. Performance-wise, it feels so big, especially for projects who haven't been optimized yet. Optimizing the random function is a technical concern that often is pushed as "could have" in many projects. It will make so many projects that have random or could include shuffle so much more performant.

  • @user-di8kl4cc5u
    @user-di8kl4cc5u Před rokem

    Awesome video

  • @petrusion2827
    @petrusion2827 Před rokem +1

    Nice quality of life features, I've had to write helper methods for most of these in my past projects.

  • @freddyflares2757
    @freddyflares2757 Před rokem +5

    I like Jon Skeet's version of Shuffle on SO that yields an IEnumerable in random order. Will be cool to see Microsoft's faster and more efficient version.

    • @QwDragon
      @QwDragon Před rokem

      I think, usually Fisher-Yates shuffle is used. But I don't know if they used it too.

    • @donr484
      @donr484 Před rokem +1

      @@QwDragon The Microsoft shuffle appears to be a Durstenfeld in place shuffle, which is a bit more efficient than Fisher/Yates.
      I made a shuffle function that uses parallel linq sorting by a new guid to output an IEnumerable. It's smoking fast with large lists and several cores.

  • @QwDragon
    @QwDragon Před rokem

    Crypto random int is never int.MaxValue :(
    What are use cases for random string? Something like youtube id?

  • @mehdizeynalov1062
    @mehdizeynalov1062 Před rokem

    Good man

  • @jjxtra
    @jjxtra Před rokem

    Shuffle does not support IList?

  • @v0id_d3m0n
    @v0id_d3m0n Před rokem

    Could you pass 1 as the length for GetItems as a substitute for GetItem?

    • @reikooters
      @reikooters Před rokem +1

      You can, and he showed that in the video, but it's going to be less efficient than a GetItem method designed to only return one item

    • @v0id_d3m0n
      @v0id_d3m0n Před rokem +1

      @@reikooters oh right ty

  • @jodydonetti
    @jodydonetti Před rokem

    Strange that at every Shuffle() call the first item remained the same. And even when changing the seed that still hold true (but different from the one without seed).

  • @Archimagus
    @Archimagus Před rokem +2

    On the part about "Random" vs "RandomNumberGenerator" another reason to use regular random is sometimes you really want the predictable seeded random, such as in procedural generation. Things like Minecraft depend on the predictable nature of Random. So it's not purely for speed reasons.

  • @schk3
    @schk3 Před rokem

    Is Random finally thread safe?

  • @asedtf
    @asedtf Před rokem +1

    The BCL grows stronger

  • @shayvt
    @shayvt Před rokem

    Not related to video, did you try Rust? Will Rust replace java/dotnet?

    • @nickchapsas
      @nickchapsas  Před rokem +5

      Rust is awesome but it’s not gonna replace Java/dotnet no. It’s just great in isolation due to its model

    • @diadetediotedio6918
      @diadetediotedio6918 Před rokem +3

      It makes more sense to .NET replacing Java than Rust, they are different languages with different purposes

  • @Andrew90046zero
    @Andrew90046zero Před rokem

    My burning question for this entire video: How is RandomNumberGenerator cryptographically secure? I would assume that if it used some equation, then that means it would be deterministic in the same way as just Random. But how does it escape the determinism of math in general?

    • @asdfxyz_randomname2133
      @asdfxyz_randomname2133 Před rokem +3

      Cryptographically secure randomness is still deterministic and you can reproduce the same series of numbers if you know the seed.
      However, if you don't know the seed, you cannot possibly find out how the series will continue, which also means that the series must be indistinguishable from true randomness, unless you know the seed.
      For cryptographically unsecure randomness, finding out how the series will continue is not easy, but possible.

    • @Andrew90046zero
      @Andrew90046zero Před rokem +1

      ​@@asdfxyz_randomname2133 Ah thank you!
      That explains how you could then use some other "atmospheric data" to randomly generate the seed for the function. Like a camera and a lava lamp or sound from a microphone.

  • @FireDragon91245
    @FireDragon91245 Před rokem

    i would like a chance method
    Chance(int, int): bool
    Chance(1, 100) it would (statisticly speaking) return true 1 out of 100 times

    • @toebeann
      @toebeann Před rokem

      Would something like the following not suffice?
      static bool Chance(int numerator, int denominator) => Random.Shared.Next(denominator) < numerator;
      static bool ChanceSecure(int numerator, int denominator) => RandomNumberGenerator.GetInt32(denominator) < numerator;
      Then you can simply write e.g. Chance(1, 100) or ChanceSecure(1, 100) depending on your use case and it should return true only 1 in 100 times, statistically speaking. The implementation using Random.Shared is not guaranteed statistical validity because it is pseudo-random as discussed by Nick in the video, but is faster and more efficient.

    • @QwDragon
      @QwDragon Před rokem

      NextInt(0, 100) < 1 does this.

  • @rasimismatulin1400
    @rasimismatulin1400 Před rokem

    Please, can anyone explain what difference between simple random with cryptographic random?

    • @nocturne6320
      @nocturne6320 Před rokem

      System.Random is a pseudo-random generator. Meaning you give it a seed and it generates a sequence of numbers based on a mathematical formula.
      This approach is fast and well suited for games, for example. It is also deterministic, same seed == same output.
      HOWEVER it is NOT cryptographically secure, if someone knows the internal state of the generator (seed and how many numbers have already been generated), they can effectively predict what number comes next, which is not good for security purposes. If you know what algorithm is used you might even be able to reconstruct the seed just from looking at the generated sequence of numbers.
      RandomNumberGenerator is a cryptographically secure generator. It uses more complex algorithms that are harder to break, sometimes it's even seeded with real world data (eg. the current temperature of the hardware components) for even more unpredictability.
      This makes it well suited for security related tasks (provided you know what you're doing), but makes it a lot slower.

    • @protox4
      @protox4 Před rokem

      Simple random is fast and produces values that a human would consider random enough. Cryptographic random is slow (comparatively) and produces values that a computer would consider random.
      Simple random has a pattern that is easy for computers to recognize, but hard for humans to recognize.

    • @asdfxyz_randomname2133
      @asdfxyz_randomname2133 Před rokem

      Both have a seed, both are deterministic, but the cryptographic randomness is indistinguishable from true randomness unless you know the seed, while with normal, cryptographically unsecure, randomness, you can in fact find out how the series will continue from the series itself, which is obviously bad if someone can predict what private key, symmetric key or password you might have generated.
      However, you still need a seed that cannot be predicted and that seed is handled by the cryptographically secure randomness implementation of microsoft, by pulling unpredictable data with enough entropy from the whole computer environment, so you don't have to seed it yourself.

  • @AshleyPOliver
    @AshleyPOliver Před rokem

    Umm. If you 'bias' your character space so that the probabilities of characters in it being selected are not 1/n where n is the size of the set you are making it weaker not stronger ...

  • @Fireballl14
    @Fireballl14 Před rokem +4

    Until Random gets state serialization - its not useful in games dev. Also weighted random would be nice.

    • @Fireballl14
      @Fireballl14 Před rokem

      @@IIARROWS turn committed - you logged every interaction, send turn log to other player. Than replayed it on both device's. If you don't have random state, you need to recreate random object with turn seed each time. And that depending on how fast turns are commencing may not be ideal.

    • @Fireballl14
      @Fireballl14 Před rokem +1

      @@IIARROWS Until some tech art guy will think. Hey I need a random number of particles here. Yeah we spend too much time working on that particular bug. x_x

    • @QwDragon
      @QwDragon Před rokem

      @@IIARROWS save the game. Make a step getting a random prize. If you don't like what you get, load the save and try again. If state is not saved, you'll get another thing. Repeat until you get what you need.

    • @QwDragon
      @QwDragon Před rokem

      @@IIARROWS But you don't replay all game from start, you are loading some middle state.

    • @QwDragon
      @QwDragon Před rokem

      @@IIARROWS No, saving seed does not solve the problem unless you rectearte random on each save.

  • @jeremyhofmann7034
    @jeremyhofmann7034 Před rokem

    This was so random

  • @TechySpeaking
    @TechySpeaking Před rokem +1

    First

  • @klocugh12
    @klocugh12 Před rokem

    Super useful for me. I used RYO method for: get n distinct random numbers from range all the time
    Now just Shuffle(Enumerable.Range(1, n1)).Take(n2);

  • @LilPozzer
    @LilPozzer Před rokem +1

    looking forward to see .NET 252442