简体   繁体   中英

C# Basic parameter passing

I am new to C# I am trying to pass a value to a method but receiving 0.Creating an instance to the main method of calc and calling the calc methods in main.

public void test()
{
var calc = new Calc();
calc.Add(1);
var actual = calc.Value;
}

public class Calc
{
        public int Value{
            get; set;
        }

        public void Add(int value)
        {
            int result = value + value;

        }

I am trying to set the current value, how could I do that?

I'd suggest refactoring it a bit so the variable names are more clear. Your initial problem is that you weren't doing anything with the result, when really you wanted to set it to your property.

public class Calc
{
    public int CurrentValue { get; set; }

    public void Add(int number)
    {
        this.CurrentValue = this.CurrentValue + number;
    }
}

The result of your Add method is not stored anywhere, ie the after the method is complete all the memory allocated while it was executed, is released. If you wish to save the result of your method you should either return it (which will require changing your method's prototype) or save it in a member of you class and access it with an appropriate property or getter-method.

Your class should be something like this:

public class Calc
{
        private int result;
        public int Value
        {
                get { return result; } 
                set { result = value; }
        }

        public void Add(int value)
        {
            result = value + value;

        }
}

Please note that currently the Add methods just saves the result of two times of the value of the sent parameter value into the class member result

I think you want something more like this:

public class Calc
{
        public int Value{
            get; private set;
        }

        public void Add(int value)
        {
            this.Value += value;
        }
}

Note I changed your Value to have a private setter, so that only the Calc class has access to change its value, whereas other objects are still able to retrieve its value.

Notice the change in the Add function, we're adding the value passed into the function onto your Value property. In your case you were just creating a new variable result in each call of the Add method, and then doing nothing with it.

You can see it in action here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM