• Downloading from our site will require you to have a paid membership. Upgrade to a Premium Membership from 10$ a month today!

    Dont forget read our Rules! Also anyone caught Sharing this content will be banned. By using this site you are agreeing to our rules so read them. Saying I did not know is simply not an excuse! You have been warned.

Tạo số ngẫu nhiên trong C# - Random Number in C#, Be careful of some of the samples you find

Admin

Well-Known Member
Staff member
Administrator
I recently came across this code on the internet for generating a random number with C#.

Code:
 private static int RandomNumber(int min, int max)
 {
    Random random = new Random();
    return random.Next(min, max);
 }
The problem with this code is that for a novice developer (and maybe even some advance developers) it can be misleading and in some instance will not work. Take for instance the following code…

The issue with this is not immediately obvious, but if you remember one thing about the Random object in C# is that when you do not pass it any parameters is uses a time based seed. In addition, if you use the same seed for an new instance the same numbers will be generated, thus they number really are not random. The same is also true for the Random.Next function, if called within the same time the same number as previous will be generated. So in the case of the function above, the for loop can go through the loop 4-5 times within a millisecond, so that means the same “random” number will be generated. So this function really does not generate a real random ID (since the same characters are repeated 4-5 times).

Code:
 public static string GenerateID(int MinSize, int MaxSize)

 {

    string stRefID = String.Empty;

    int iChosenMaxSize = RandomNumber(MinSize, MaxSize);

    for (int x = 1; x <= iChosenMaxSize; x++)

    {

       int iCharType = RandomNumber(1, 3);


       switch (iCharType) 

       {

          case 1:

          {

             stRefID += char.ConvertFromUtf32(RandomNumber(48, 57));

             break;

          }

          case 2:

          {

             stRefID += char.ConvertFromUtf32(RandomNumber(65, 90));

              break;

          }

          case 3:

          {

             stRefID += char.ConvertFromUtf32(RandomNumber(97, 122));

             break;

          }

       }

    }

    return stRefID; 

 }
So the code that does what is really needed cannot use the RandomNumber function that I found on the internet. Below is how the the function above can be written not using the RandomNumber function to do what is expected.

Code:
 public static string GenerateID(int MinSize, int MaxSize)

 {

    string stRefID = String.Empty;

    Random random = new Random();

    int iChosenMaxSize = random.Next(MinSize, MaxSize); 


    for (int x = 1; x <= iChosenMaxSize; x++)

    {

       int iCharType = random.Next(1, 3);


       switch (iCharType)

       {

          case 1:

          {

             stRefID += char.ConvertFromUtf32(random.Next(48, 57));

             break;

          }

          case 2:

          {

             stRefID += char.ConvertFromUtf32(random.Next(65, 90));

             break;

          }

          case 3:

          {

             stRefID += char.ConvertFromUtf32(random.Next(97, 122));

            break;

          }

       }

  

       System.Threading.Thread.Sleep(1);

    }
    return stRefID; 

    }


The 2 keys to the update function are:
1) The Random() object is only instantiated once so the seed is only set once.
2) The addition of the Thread.Sleep(1) call between each of the time through the loop. This makes sure that when the Next function is called the time has changed so that the number generated will not be the same as previously generated.
This is not a knock on the sample code I found, since it would work in certain instances. But just a warning to be aware that when downloading code samples (even if they get good reviews), might not work in the situation that you need it for and IMO need to be tested even more than code you wrote yourself.
 

Facebook Comments

Similar threads
Thread starter Title Forum Replies Date
LIA THUÊ VIẾT APP ỨNG DỤNG TẠO DÀN XỔ SỐ Kiến thức lập trình 0
T NHTW Thái Lan tạo dựng blockchain cho dự án tiền tệ kỹ thuật số Tin tức CNTT 0
Admin Hướng dẫn xanh tiền Ad Breaks và tạo fanpage từ con số 0 Tut, tool, mmo 0
Admin Hướng dẫn tạo plugin yêu cầu đủ số bài viết mới được phép gửi tin nhắn cho vbb Vbb tutorial 0
Admin Hướng dẫn tạo swap cho vps - Chỉnh thông số Swappiness VPS & Dedicated Server 2
Admin Hướng dẫn cách tạo nhiều blog và một số vấn đề về blog xtgem Wap builder, wapego, xtgem, wen.ru, wapka, wap4 0
S Hướng dẫn Xin hd tạo phòng chát room và 1 số link tạo lập cơ bản Wap builder, wapego, xtgem, wen.ru, wapka, wap4 5
S tut tạo yahoo bằng số mr.reeon Sử dụng, chia sẻ, hỏi đáp 1
D Xin Xin code tạo trang thống kê sổ kết quả xổ số PHP 4
katy Android Xưng danh "Nhà sáng tạo của năm" với gói cước tự tạo MM trên My MobiFone Điện thoại di động 17
Admin Hướng dẫn tạo usb cài windows chuẩn UEFI không dùng phần mềm Sử dụng, chia sẻ, hỏi đáp 0
katy Android Tự tạo gói cước đơn giản, dễ dàng phù hợp với nhu cầu chỉ có trên My MobiFone Điện thoại di động 38
katy Android Tự tạo gói cước linh hoạt thời gian sử dụng trên My MobiFone Điện thoại di động 10
Admin Cách tạo logo Thiết kế đồ họa 0
dinhtrungtek Phần mềm PC Phần mềm tạo USB cài win tự động dành cho cửa hàng - TekDT USB Creator Phần mềm 0
V Hướng dẫn tạo logo giống Xenforo Xenforo 4
tmarketingvnn Hướng dẫn Cách Tạo Tài Khoản Trên Sàn Exness Nhanh Chóng Kiến thức lập trình 0
Admin Hướng dẫn tạo VPS miễn phí 14 ngày - How to get a free VPS for 14 days VPS & Dedicated Server 1
Admin Hướng dẫn cách tạo mail edu miễn phí - How to get edu mail for free Tut, tool, mmo 0
Admin Hướng dẫn tạo nút like (reaction) xenforo 2 gif động giống Facebook - Reaction xenforo 2 gif animation same Facebook Xenforo 0
Admin Hướng dẫn tạo nút like (reaction) xenforo 2 giống Facebook Xenforo 0
cuongpro9x Tạo tài khoản Onedrive 5TB miễn phí Tin tức CNTT 7
nguoncoi1990 Hướng dẫn Cho em hỏi về tạo tên miền m.choquehuong.com cho web Vbulletin 22
Admin Hướng dẫn tạo cảnh báo khi người dùng nhấn vào nút thoát app trên Xamarin Forms Android, iOS 0
Admin Hướng dẫn tạo nút thoát ứng dụng trong Xamarin Forms Android, iOS 0
Admin Hướng dẫn tạo cảnh báo cho Xamarin Forms giống MessageBox.Show trên C# Android, iOS 0
Admin Hướng dẫn tạo hiệu ứng chữ chạy, ảnh chạy với thẻ Marquee trong HTML5 Mã nguồn wap 0
dammechiase Dowload phần mềm UltraISO Mới nhất phần mềm tạo ổ đĩa ảo mới nhất full key bản chuẩn kèm hướng dẫn Phần mềm 0
T Chia sẻ sâu sắc về trí tuệ nhân tạo Tin tức CNTT 0
P Phần mềm PC Air Live Drive Pro v1.3.1 – Tạo ổ đĩa đám mây ảo trên máy tính Phần mềm 0
T Blockchain phổ cập trong đào tạo lập trình Trung Quốc Tin tức CNTT 0
Admin Ads.txt là gì và quan trọng như thế nào? Tại sao tạo xong ads.txt thì không thấy hiện quảng cáo Google Thảo luận SEO 0
T Đức tạo dựng Viện nghiên cứu Blockchain châu Âu Tin tức CNTT 0
Admin Hướng dẫn tạo con vật thật sự trên màn hình điện thoại bằng Animal 4D+ Thảo luận chung 0
T Liệu có phải Blockchain sẽ tạo ra nhiều giá trị HTTP ? Tin tức CNTT 0
haopro Nhạc Liên Minh Huyền Thoại 2019 Nhạc dập liên tục tạo hương phấn khi chơi game Âm nhạc 0
Admin Hướng dẫn tạo video karaoke đơn giản và chi tiết nhất 2019 Video, clip 4
dammechiase Dowload Tải Phần Mềm LRTimelapse Pro 5.2 Mới Nhất Full Crack – Phần Mềm Tạo video Time-lapse từ ảnh Mới Nhất Phần mềm 0
dammechiase Dowload Phần Mềm DLC Boot 2017 Mới Nhất– Tạo USB Boot cài Windows 10, 8.1, 7 bản chuẩn Phần mềm 0
T Google tạo ra công cụ để phân tích blockchain của Ethereum Tin tức CNTT 0
G Share Tạo trang upload tập tin với PHP PHP 2
C Địa chỉ Đào tạo và dạy học nghề Nails cấp tốc chuyên nghiệp, tốt và uy tín ở Hà Nội Trò chuyện linh tinh 0
C Địa chỉ Đào tạo và dạy học nghề làm Nails uy tín và chuyên nghiệp ở Hà Nội Trò chuyện linh tinh 1
C Địa chỉ Đào tạo làm Nails, Dạy làm móng uy tín và chuyên nghiệp ở Hà Nội Trò chuyện linh tinh 0
C Hỏi Cách tạo hosting trên winserver 2008R2 chạy code php và worpress Hỏi đáp về domain & hosting 0
S Share cách tạo tên facebook 1 chữ hay Thủ thuật máy tính 2
E ad tạo e wap scam team Mã nguồn wap 1
K Xin Xin cách tạo subdomain ảo chạy trong thư mục PHP 2
Admin Hướng dẫn tạo CronJob xóa toàn bộ mail chờ DirectAdmin - How to clear queue mail with CronJob DirectAdmin VPS & Dedicated Server 2
D Geogebra giúp bé - sáng tạo hình toán học tốt nhất Góc thành viên học tập 1

Similar threads

New posts New threads New resources

Back
Top