Parameter passed by value being modified as reference

Asked

Viewed 24 times

0

I have the following situation, I have an object with value 2800, when I pass this object by value and divide the value of an object attribute within the scope of the function, the value of my object also changes as if I had passed by reference.

Follow an example:

public class Transaction
{
    public Double Valor { get; set; }
}

public class TransactionController
{
    public void ProccessCreditCardPayment(){
        Transaction transaction = new Transaction();
        transaction.Valor = 2800;
        Invoice invoice = new Invoice(transaction); //passando parâmetro por valor

        Debug.WriteLine(transaction.Valor); //valor = 28, ele foi modificado no outro metodo e influenciou no meu objeto fora do escopo da função

    }
}

public class Invoice
{
    public Double Valor{get;set;}
    public Invoice(Transaction transaction){ //parametro por valor            
        transaction.Valor = transaction.Valor/100;
        this.Valor = transaction.Valor;
    }
}

I can’t understand why this is happening,.

Following link explaining in C passage by value and by reference: https://www.ime.usp.br/~elo/Introducaocomputacao/Funcoes%20pass%20of%20parametros.htm

  • The "value" that is passed by parameter is a pointer to the object, so by changing the object within the method, the outside will also be changed.

  • But I didn’t pass for reference...

  • Even though I don’t make it clear ref he behaves as a reference? has no meaning for me

  • Almost that. Read the post I marked as duplicate that you will understand.

  • Here is an example: https://dotnetfiddle.net/0yRYzw

  • @LINQ now understood, the behavior is different when using complex types because it copies, but both with the same memory address

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.