简体   繁体   中英

Cannot implicitly convert type string to int in C#

I am fairly new to c# and I can't figure this out. The error says that I cannot convert string to int implicitly. Here is a snippet of my code. Thanks!

    private static int GenerateLetters(int size, bool lowercase) //added a return type
    {
        {
        string randomLetters = string.Empty;
        Random r = new Random();

        for (int i = 0; i < size; i++)
        {
            randomLetters += Convert.ToChar(r.Next(65, 90));                
        }

        if (lowercase)
            return randomLetters.ToLower();
        else
            return randomLetters.ToString();
            }
        }

You should change return type of your method to string

private static string GenerateLetters(...)

By the way it would be better if you change your method like this:

private static string GenerateLetters(int size, bool lowercase) //added a return type
{

     char[] chars = new char[size];
     Random r = new Random();

     for (int i = 0; i < size; i++)
     {
         chars[i] = Convert.ToChar(r.Next(65, 90));
     }

    if (lowercase)
           return new String(chars).ToLower();
     else
          return new String(chars);

}

change

private static int GenerateLetters

to

private static string GenerateLetters

you are returning string but method has return parameter int. What you are returning has to be compatible with method stub.

Read more about methods in c# at MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM