Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unreachable code detected C# (absolute beginner) [closed]

Could you explain how should I avoid this warning: "Unreachable code detected" in Visual Studio 2010 Express ? I'm learning C# from a manual. It's an exercise for creating a simple method. I'm entering the example precisely as written in the book. Thanks.

public class Multiply 
{
    //Multiplies argument by 4 

    public static int MultiplyBy4(int aNumber)
    {
        return 4 * aNumber;
        //Shows ways of passing various arguments to a method public static void Main
        int x = 7;
        int y = 20;
        int z = -3;
        int result = 0;

        result = MultiplyBy4(x);
        Console.WriteLine("Passsing a variable, x : {0}", result);

        result = MultiplyBy4(y + 2);
        Console.WriteLine("Passing an expression, Y + 2: {0}", result);

        result = 5 + MultiplyBy4(z);
        Console.WriteLine("Using MultiplyBy4 in an expression: {0}", result);
        Console.ReadLine();
    }
 }

I don't understand the manual commentary: "Shows ways of passing various arguments to a method public static void Main" after creating the method with a parameter and a return value. How do I make the method MultiplyBy4 recognize x, y, z as being "aNumber" ? Maybe this is a retarded questions but I'm stuck here. Thanks.

like image 922
user3190322 Avatar asked Feb 16 '26 04:02

user3190322


2 Answers

The comment line is messed up and contains the definition of the Main method. The code should read:

    public class Multiply 
{
        //Multiplies argument by 4 
        public static int MultiplyBy4(int aNumber)
        {
            return 4 * aNumber;
        }

        //Shows ways of passing various arguments to a method
        public static void Main(string[] args)
        {
                int x = 7;
                int y = 20;
                int z = -3;
                int result = 0;

                result = MultiplyBy4(x);
                Console.WriteLine("Passsing a variable, x : {0}", result);

                result = MultiplyBy4(y + 2);
                Console.WriteLine("Passing an expression, Y + 2: {0}", result);

                result = 5 + MultiplyBy4(z);
                Console.WriteLine("Using MultiplyBy4 in an expression: {0}", result);
                Console.ReadLine();
            }
 }
like image 151
Carsten Heine Avatar answered Feb 18 '26 18:02

Carsten Heine


The return statement is exiting the function here.

So the declarations of x,y,z and result, and the Console.Write will never run...

like image 36
cubitouch Avatar answered Feb 18 '26 16:02

cubitouch