Search code examples
c#referencepass-by-referencepass-by-value

confused about Passing by reference and passing by value in c#


i am a new programmer here. I have the following code. I passed the object by value, but when i printed the results, i got this

elf attacked orc for 20 damage!
Current Health for orc is 80
elf attacked orc for 20 damage!
Current Health for orc is 80

this got me confused about passing by reference because I did not expect the health in the main to be 80 since i passed the object by value. Can someone explain how the result for health in the program main function was 80 instead of 100?

//MAIN class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace passingTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // Enemy Objects
            Enemy elf = new Enemy("elf", 100, 1, 20);
            Enemy orc = new Enemy("orc", 100, 1, 20);
            elf.Attack(orc);
            Console.WriteLine("{0} attacked {1} for {2} damage!", elf.Nm, orc.Nm, elf.Wpn);
            Console.WriteLine("Current Health for {0} is {1}", orc.Nm, orc.Hlth);
            Console.ReadLine();

        }
    }
}

// Enemy Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace passingTest
{
    class Enemy
    {
        // variables
        string nm = "";
        int hlth = 0;
        int lvl = 0;
        int wpn = 0;

        public string Nm
        {
            get { return nm; }
            set { nm = value; }
        }
        public int Wpn
        {
            get { return wpn; }
            set { wpn = value; }
        }
        public int Hlth
        {
            get { return hlth; }
            set { hlth = value; }
        }
        public Enemy(string name, int health, int level, int weapon)
        {
            nm = name;
            hlth = health;
            lvl = level;
            wpn = weapon;
        }
        public void Attack(Enemy rival){
            rival.hlth -= this.wpn;
            Console.WriteLine("{0} attacked {1} for {2} damage!", this.nm, rival.nm, this.wpn);
            Console.WriteLine("Current Health for {0} is {1}", rival.nm, rival.hlth);
        }
    }
}

Solution

  • In C#/.NET, whether an object is passed by reference or by value is determined by the type of the object. If the object is a reference type (i.e. it is declared with class), it is passed by reference. If the object is a value type (i.e. it is declared with struct) it is passed by value.

    If you change the declaration of Enemy to

    struct Enemy
    

    you will see pass-by-value semantics.