✅ How to implement a method of a class using the object which called it as its parameter
I want to create a method that uses the object that called it as a parameter.
It's because I don't want to type lines like or
Much help needed and appreciated!
5 Replies
Functions defined in the class can just use
this
to access the object
Although in many cases you don't even need to write this.
, as it implicitly accesses the fields, properties, and methods of the object automatically if there isn't a local variable hiding itPerhaps you mean
CallerMemberName
?CallerMemberNameAttribute Class (System.Runtime.CompilerServices)
Allows you to obtain the method or property name of the caller to the method.
Passing this as an optional string parameter will give you the method that called it. If you just want to know who invoked the method, this works.
But if you just want to omit passing the caller instance like you actually ask for, then I would advice you to just do it. I don't really understand why you would want to get rid of readability, just because you need to do the same action multiple times.
Because this would fix it, but then you are bound to the scope of the calling class, and it will limit the behaviour of your method to just that class. If this is intended, then sure, this will work.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.