Question alternative of n.swap?

STAD

New member
Joined
Feb 23, 2022
Messages
1
Programming Experience
Beginner
Hi.
I am new to c sharp and I am using C# programming by brian jenkins.
Page 73 of his book has the following code:

Pass By Value code page 73 of C# programming by Brian Jenkins:
using System;

namespace MethodApplication
{
    class NumberChecker
    {
        public void swap(int a, int b)
        {
            int temp;

            temp = a; /* saving the valuee of a */
            a = b;  /* putting b into a */
            b = temp; /* putting temp into b */
        }
        static void Main(string[] args)
        {
            NumberChecker numberChecker = new NumberChecker();

            /* defining a local variable */
            int x = 10;
            int y = 20;

            Console.WriteLine("Before swapping, value of x is ; {0}", x);
            Console.WriteLine("Before swapping, value of y is : {0}", y);
           
            /* let's swap the values by calling the function */
               
                n.swap(x, y);

            Console.WriteLine("After swapping, value of x is : {0}", x);
            Console.WriteLine("After swapping, value of y is ; {0}", y);

            Console.ReadLine();
                }
    }
}


I did some searching and I have found nothing on the n.swap function.
Nada. zip. Zilch.

I get info on the swap function instead.

I also get a 'Error CS0103 The name 'n' does not exist in the current context'.

I mess with it and remove the n. from swap and that didn't correct it.
Added NumberChecker.swap and that didn't make it any better.

I run the code without n.swap and it runs as expected.

So what is going on? Why was n.swap put in when it works fine without it?
 
swap method starts at line 7, line 17 creates an instance of the class and is supposed to call this method on that instance. In your code the variable is named numberChecker, not n.
You can't call that method from a static method (Main) without changing it to static also.
Further ints are value types and the parameters must be ref to return the changed values to caller.
 
Back
Top Bottom