Search code examples
c#arraysmethodsref

Need help using REF and Arrays, and Methods


Ok, I'm doing my lab from C# class which involve using ref parameters, arrays, and methods. There is a few problems which I encounter while doing this and I'm begging for help. So.. First I modified problem into simplest chunks to help me explain which problems I have. Here is a piece of simplified code:

using System;

public class Repository 
{
    string[] titles;

    static void Main(string[] args)
    {
        string title;

        Console.Write("Title of book: ");
        title = Console.ReadLine();

        getBookInfo(ref title);
    }

    static void getBookInfo(ref string title)
    {
        titles[0] = title;
    }

    static void displayBooks(string[] titles)
    {
        Console.WriteLine("{0}", titles[0]);
    }
}

Now, as u will try to compile code, you notice that can not be compiled because error say "An object reference is required to access non-static member 'Repository.titles'". The problem is that the format of 3 methods must b exactly as posted as told in the assignment. Now, how can I avoid this problem while keeping this template in place?

Other question, how would I display content of method displayBooks in main? (I haven't got this far because of problems).

Regards, and please help!

----------------------- THANK YOU FOR HELP !!! ---------


Solution

  • Firstly, you don't need to use ref unless you want to alter the value of title as it exists within Main(). The following code demonstrates the concept:

    static void Main(string[] args)
    {
        string a = "Are you going to try and change this?";
        string b = "Are you going to try and change this?";
    
        UsesRefParameter(ref a);
        DoesntUseRefParameter(b);
        Console.WriteLine(a); // I changed the value!
        Console.WriteLine(b); // Are you going to try and change this?
    }
    
    static void UsesRefParameter(ref string value)
    {
        value = "I changed the value!";
    }
    
    static void DoesntUseRefParameter(string value)
    {
        value = "I changed the value!";
    }
    

    An array needs to be created before you can use it. So here is your code that has been corrected:

    static string[] titles;
    
    static void Main(string[] args)
    {
        string title;
        titles = new string[1]; // We can hold one value.
    
        Console.Write("Title of book: ");
        title = Console.ReadLine();
    
        getBookInfo(title);
    }
    
    static void getBookInfo(string title)
    {
        titles[0] = title;
    }
    

    To display your books you could try the following method:

    static void displayBooks(string[] titles)
    {
        // Go over each value.
        foreach (string title in titles)
        {
            // And write it out.
            Console.WriteLine(title);
        }
    }
    // In Main()
    displayBooks(titles);