Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name of the incoming parameter same as field name

Tags:

c#

class  Person
{
  public string name;

  public void SetName(string name)
  {
    name = name;
  }
}    

public void static Main(string[] args)
{    
  Person aPerson = new Person();
  aPerson.SetName("ruby");

  Console.WriteLine("person name is {0}}, aPerson.name);
}

The person's name is empty. This can eliminated using this.name = name;

What was the reason person name is empty(empty string)?

like image 399
Raghav55 Avatar asked Sep 08 '25 01:09

Raghav55


1 Answers

Currently, your assignment of

name = name;

is just assigning the value of the parameter back to itself. In other words, it's a no-op.

If you change it to:

this.name = name;

then that's assigning the value of the parameter to the field which is what you intended.

However, currently the Person's name field won't refer to an empty string - it will be a null reference. There's a big difference between the two.

(Of course, normally you shouldn't have a public field, and you should use a property instead of a SetName method.)

like image 57
Jon Skeet Avatar answered Sep 09 '25 15:09

Jon Skeet