0

i want to generate vouchers of alpha numeric code of 10 digits and the error is "cannot implicitly convert 'void' to system.collections.generric.list"

voucher_no= generatedVouchers.Add(voucher);//it is giving me error in this line

    static Random random = new Random();
    public ActionResult RandomVouchers()
    {

        int vouchersToGenerate = 1;
        int lengthOfVoucher = 10;


        List<string> voucher_no = new List<string>();

        List<string> generatedVouchers = new List<string>();
        char[] keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890".ToCharArray();

        while (generatedVouchers.Count < vouchersToGenerate)
        {
            string voucher = GenerateVoucher(keys, lengthOfVoucher);
            if (!generatedVouchers.Contains(voucher))
            {
            voucher_no=   generatedVouchers.Add(voucher);//it is giving me error in this line

            }
        }
        return View(voucher_no);
    }
    private static string GenerateVoucher(char[] keys, int lengthOfVoucher)
    {

        return Enumerable
            .Range(1, lengthOfVoucher) // for(i.. ) 
            .Select(k => keys[random.Next(0, keys.Length - 1)])  // generate a new random char 
            .Aggregate("", (e, c) => e + c); // join into a string
    }

2 Answers2

4

List<T>.Add does not return a value, its of return type void so you cant assign the result of this method call to anything.


Also there is no reason to have both voucher_no and generatedVouchers. Remove one of those, in the refactored code below I removed voucher_no.

As far as your lists are concerned do not use a List<T>, instead use a HashSet<T> so that way the check for duplicates in your list inside the loop is much more efficient as the number of codes you want to generate increases.

public ActionResult RandomVouchers()
{
    int vouchersToGenerate = 1;
    int lengthOfVoucher = 10;

    void generatedVouchers = new HashSet<string>();
    char[] keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890".ToCharArray();

    while (generatedVouchers.Count < vouchersToGenerate)
    {
        string voucher = GenerateVoucher(keys, lengthOfVoucher);
        if (!generatedVouchers.Contains(voucher))
        {
            generatedVouchers.Add(voucher);
        }
    }
    return View(generatedVouchers);
}

Also see this as a reference for how to generate a random code: How can I generate random alphanumeric strings in C#?

Community
  • 1
  • 1
Igor
  • 60,821
  • 10
  • 100
  • 175
1

You are trying to equalize a void function (.Add), to a list of string. Add function returns nothing but you are assuming that it does. That's why you are getting the error. You should do it like this

voucher_no.Add(voucher);
generatedVouchers.Add(voucher);
Burak Karakuş
  • 1,368
  • 5
  • 20
  • 43