astar
astar

Reputation: 29

C# why object can't be converted to int

I have some problems with simply exercise.. I have to write a program that asks the user for the value of N and then calculates N! using recursion. I wrote something like this:

namespace ConsoleApplication19
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This program will calculate a factorial of random number. Please type a number");
            String inputText = Console.ReadLine();
            int N = int.Parse(inputText);
            
            String outputText = "Factorial of " + N + "is: ";
            int result = Count(ref N);
            Console.WriteLine(outputText + result);
            Console.ReadKey();
        }

        private static object Count(ref int N)
        {
            for (int N; N > 0; N++)
            {
                return (N * N++);
            }
        }
    }

And the problem is in line "int result = Count(ref N);" I have no idea why it can't be converted to int.

Upvotes: 0

Views: 766

Answers (3)

Ehsan
Ehsan

Reputation: 32661

because it is returning an object and object cannot be implicitly converted to int, what you can do though is to change the signature of your method like

private static int Count(ref int N)

or you can do this

int result = (int)Count(ref N);

Take a simple example

//this is what you are doing
object obj = 1;
int test = obj;   //error cannot implicitly convert object to int. Are you missing a cast?

//this is what needs to be done
object obj = 1;
int test = (int)obj; //perfectly fine as now we are casting

// in this case it is perfectly fine other way around
obj = test;  //perfectly fine as well

Upvotes: 10

AnthonyGiraldo
AnthonyGiraldo

Reputation: 37

Yes, as previous replies have mentioned, you don't need the ref, and you need to return an int. Your question says you need to use recursion, but you are using a for loop?

here's how you write a factorial recursive method:

public long Factorial(int n)
{
   if (n == 0)  //base
     return 1;
   return n * Factorial(n - 1);
}

Upvotes: -2

Rodrigo Aguirre Vanda
Rodrigo Aguirre Vanda

Reputation: 92

I guess its beceause your method type is "object", and it should be "int".

Upvotes: 0

Related Questions