Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the value assignment operator work in this case?

Tags:

c#

oop

It helps to note I'm very new to c#.

But consider the following class:

class AllItems
{
    private readonly Database database;

    public AllItems(Database database)
    {
        this.database = database;
    }
}

I have the following questions:

  1. In the above example we are assigning private readonly Database databasethe value which gets passed into AllItems class, is that correct?

  2. Would it matter if I swapped this.database = database around, so it looked like database = this.database instead?

  3. Where we are saying this.database, does this refer to the database in AllItems(Database database) or does it refer to private readonly Database database ?

like image 588
Allen S Avatar asked Jul 14 '26 05:07

Allen S


2 Answers

In the above example we are assigning private read-only Database database the value which gets passed into the AllItems class, is that correct?

Yes

Would it matter if I swapped this.database = database around, so it looked like database = this.database instead?

Yes, it would. What you would end up doing there is assigning the database parameter being passed in to be the value of the database field (which would be null by default).

Where we are saying this.database, does this refer to the database in AllItems(Database database) or does it refer to private read-only Database database?

this is shorthand for the current class instance, therefore it refers to the private read-only member of database.

like image 132
James Avatar answered Jul 15 '26 19:07

James


  1. Yes
  2. Yes it would matter, then you would assigning the value of this.database (in this case null) into database.
  3. this.database in this case refers to private readonly Database database; field. I suggest you read more about the this keyword here.
like image 31
Sebastian Piu Avatar answered Jul 15 '26 20:07

Sebastian Piu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!