'How to reference multiple variables in another method from another method?

I am new to C#. I have int a, b, c d which I want to use them in method Process(). How can I do this. Here is my code:

 public void Input()
    {
        int a, b, c, d;
        //using the conversion method from string to int
        Int32.TryParse(KingText1, out a);
        Int32.TryParse(KingText2, out b);
        Int32.TryParse(KingText3, out c);
        Int32.TryParse(KingText4, out d);

        
        
    }

    public void Process()
    {

        //THIS IS WHERE I AM HAVINg THE ISSUE OF USING VARIABLES FROM INPUT 
        int totalScore = a + b + c + d;
        int averageScore = (a + b + c + d) / 4;

       
        

    }        


    
    


Solution 1:[1]

Here is quick answers that you can apply right now.

  1. You could use static property.
public class ClassA
{
    private static int A = 0;

    public void Input()
    {
        // ...
        Int32.TryParse(KingText1, A);
    }

    public void Process()
    {
        int totalScore = A + b + c + d;
        int averageScore = (A + b + c + d) / 4;
    }
}       
  1. You could use instance property.
public class ClassA
{
    private int _a;

    public void Input()
    {
        // ...
        Int32.TryParse(KingText1, _a);
    }

    public void Process()
    {
        int totalScore = _a + b + c + d;
        int averageScore = (_a + b + c + d) / 4;
    }
}   

However, I am not recommand above answers. You can do it, but it is bad practices. If you want to be a developer, You should learn a better way to write code for you in the future, who will suffer from smelly code.

Therefore, I recommand this.

  1. Learn C# programming (https://dotnet.microsoft.com/en-us/learn/csharp)
  2. Read Clean Code (https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882)
  3. Then write some code with a senior developer's review.

Solution 2:[2]

You could do it like

public bool Input(out int a, out int b, out int c, out int d)
{
    a = default;
    b = default;
    c = default;
    d = default;

    if(!int.TryParse(KingText1, out a)) return false;
    if(!int.TryParse(KingText2, out b)) return false;
    if(!int.TryParse(KingText3, out c)) return false;
    if(!int.TryParse(KingText4, out d)) return false;

     return true;     
}

And later use it like e.g.

public void Process()
{
    if(!yourInputClassReference.Input(out var a, out var b, out var c, out var d)) return;

    int totalScore = a + b + c + d;
    float averageScore = totalScore/ 4f;
}        

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 derHugo