+ 1

This & readonly: C#

there's an exemple at the bottom of the page on the C# course from here, on the More on Classes > This & Readonly page. it says, that we can use the actual instance as argument, like so: ShowPersonInfo(this); I don't understand very well the use of the actual instance as parameter, in this case, with the word "this. could anybody please provide me a better exemple of using this. Thank you very much :)

6th Jan 2018, 1:44 PM
Welliton Malta
Welliton Malta - avatar
1 Odpowiedź
0
I advice you to look into comments section if you don't understand something in the lecture. Here is a code, which was posted in the comments section: I am posting example code where we use object of Person as parameter in function class Person { private string name; private int age; public Person(string name, int age) { this.name = name; this.age = age; } public static void ShowInfo(Person p) { Console.WriteLine("This is " + p.name + ". Age: " + p.age); } public void TellMeAboutYourself() { ShowInfo(this); } } class SomeClass { static void Main(string[] args) { Person person = new Person("Anna", 21); Person.ShowInfo(person); person.TellMeAboutYourself(); } } Now look at the main method. So basically what we are doing here is we are creating an instance of class Person and giving it name "Anna" and age of 21. And now we can call a ShowInfo() method directly and giving it out instance with name "Anna" and age of 21. Or we can call TellMeAboutYourself method, which does the exact same thing, because if we look at this method we can see that it calls our ShowInfo method and providing it with THIS instance of class with name "Anna" and with the same age. Hope this helped.
6th Jan 2018, 2:53 PM
Groompel
Groompel - avatar