Abdulrahman Bin Fahad
Abdulrahman Bin Fahad

Reputation: 41

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.

Upvotes: 3

Views: 4007

Answers (3)

JustBeingHelpful
JustBeingHelpful

Reputation: 18980

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);
        }
    }

Upvotes: 1

manojlds
manojlds

Reputation: 301077

This is a compilation error and unrelated to calling it from another program. Basically , through all the if's and the else's, there is a path of execution that does not return a value from the function.

While you can add a return true at the end of your method to satisfy the compiler, your logic is also flawed because in the inner (in the loop) else, you are returning true, eventhough it might actually not turn out to be prime. Move the return true outside the loop and remove the else part in the loop.

To call this from another assembly / program, you have to reference this assembly and call the method. You may add a using statement too.

Upvotes: 1

leppie
leppie

Reputation: 117220

Move the return true to after the for loop.

Try understand why I say that :)

Upvotes: 1

Related Questions