C# help please

Associate
Joined
2 Oct 2003
Posts
2,121
Location
Chester
Hello!

Quite new to C# but gave myself the challenge of writing a promotion code generator like the ones you get on the Internet.

The results have to be unique and I want to generate between 10,000 and 500,000 a time. The class I have wrote seems to be rather slow and I am wondering if there is a faster way of doing this?

PHP:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace WindowsFormsApplication1
{
    class PromotionCodeGenerator
    {
        StreamWriter sw = new StreamWriter(@"c:\codes.csv");

        /// <summary>
        /// Generate a list of codes.
        /// </summary>
        public void GenerateCodes(int ID, int Qty)
        {
            HashSet<string> Codes = new HashSet<string>();

            for (int i = 0; i < Qty; i++)
            {
                string Code = GenerateCode(ID);
                
                if (Codes.Contains(Code))
                {
                    i--;
                }
                else
                {
                    Codes.Add(Code);
                    WriteToFile(Code);
                }
            }  
        }

        /// <summary>
        /// Generate a new promotion code.
        /// </summary>
        private string GenerateCode(int ID)
        {
            Random r = new Random();      

            return Convert.ToString(String.Concat(ID,"-", r.Next(10000000, 99999999)));
        }

        /// <summary>
        /// Write promotion code to file.
        /// </summary>
        private void WriteToFile(string Code)
        {
            sw.WriteLine(Code);
        }
    }
}
 
Back
Top Bottom