celia grenjay
celia grenjay

Reputation: 13

Is there a way to pull information from one variable created inside a function, and use it in another

I was wondering if there is a way I can take the information that gets passed through EleWeight in this function I created below, and use that information in another function.

static void ElementData(string EleName, string EleSymbol, string EleNumber, string EleWeight)
    {
        Console.WriteLine("Element: " + EleName);
        Console.WriteLine("Symbol: " + EleSymbol);
        Console.WriteLine("Atomic Number: " + EleNumber);
        Console.WriteLine("Atomic Weight: " + EleWeight);
        NewElement();
    }

Upvotes: 1

Views: 68

Answers (2)

xanatos
xanatos

Reputation: 111860

You have to put it somewhere... A static field for example... Note that this will break if there is no clear ordering between ElementData() calls and OtherFunction() calls. The suggested way of doing it is probably calling OtherFunction() from ElementData()

Another way:

public class OtherFunctionClass
{
    public readonly int EleWeight;
    public OtherFunctionClass(int eleWeight) 
    {
        EleWeight = eleWeight;
    }

    public void OtherFunction()
    {
    }
}

and then from ElementData:

static OtherFunctionClass ElementData(string EleName, string EleSymbol, string EleNumber, string EleWeight)
{
    ....
    ....
    return new OtherFunctionClass(EleWeight);
}

So ElementData returns an object that contains the EleWeight and that has the OtherFunction method.

Upvotes: 0

Tanuki
Tanuki

Reputation: 849

static void NewElement(string EleWeight)
{
    ...
}

static void ElementData(string EleName, string EleSymbol, string EleNumber, string EleWeight)
{
    Console.WriteLine("Element: " + EleName);
    Console.WriteLine("Symbol: " + EleSymbol);
    Console.WriteLine("Atomic Number: " + EleNumber);
    Console.WriteLine("Atomic Weight: " + EleWeight);
    NewElement(EleWeight);
}

If you want to keep the information between function calls you would need to store that in some kind of class field variable

Upvotes: 1

Related Questions