Search code examples
c#methodsclass-library

How can i call a method from library to C# console


i created a method in a new library this is my code

namespace ClassLibrary1
{
    public class Class1
    {
        public static bool ISprime(int prime)
        {

            if (prime < 2)
                return false;
            else if (prime == 2)
                return true;
            else
            {
                for (int i = 2; i < prime; i++)
                {
                    if (prime % i == 0)
                        return false;
                    else
                        return true;
                }

            }
        }
    }
}
  1. how can i call that method in my console " program.cs "
  2. i got an error that said " Error 2 'ClassLibrary1.Class1.ISprime(int)': not all code paths return a value"

what does that mean ?

sorry i'm a new programmer.


Solution

  • 1.) call the method by doing the following:

    ClassLibrary1.Class1.ISprime(123);
    

    or

    Class1.ISprime(123);  // make sure to reference ClassLibrary1 at the top of your class
    

    2.) You need to return some value at the very end of the method. I also changed some of the logic:

    public static bool ISprime(int prime)
    {
        if (prime == 1) 
            return false;
        if (prime == 2) 
            return true;
    
        for (int i = 2; i < Math.Sqrt(prime); ++i)  {
            if (prime % i == 0) 
                return false;
        }
    
        return true;
    }
    

    3.) Answering comment about what's different from the logic. Try running this and you'll see the differences.

        for (int n = -10; n < 10; n++)
        {
            if (Class1.IsPrimeCorrect(n) != Class1.IsPrimeIncorrect(n))
            {
                Console.WriteLine(n);
            }
        }