0

Is there an option to automatically pass this as parameter to a function? For example, you can use [CallerMemberName] to automatically pass string name. I'm looking for exact option with this.

Example:

void PassMeThis([AutomaticThisParam] object source);

and usage:

public class SomeClass{    
    void SomeMethod(){
        PassMeThis(); // instead of PassMeThis(this)
    }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Kuker
  • 65
  • 3
  • 11
  • `PassMeThis()` and `PassMeThis(this)` would be two separate methods, though – OneCricketeer Nov 07 '18 at 19:42
  • 1
    Where is located the PassMeThis method? If it is inside the same class then what is the purpose of this thing? – Steve Nov 07 '18 at 19:43
  • 1
    Most likely you are looking for .NET Extension methods, as @Willie answered. Alternatively, if you want default context data that is automatically picked up by such functions in your code in a given execution context, like a thread, then there are alternatives to that as well - like ThreadStatic fields. – Ryan Pierce Williams Nov 07 '18 at 19:55

2 Answers2

5

Yes absolutely. This is called an extension Method.

  1. Create a static class Public static class MethodExtensions

  2. Add a static method to it like this public static PassMeThis(this SomeClass model) { // }

  3. Call the method like this (referring to your code example): this.PassMeThis()

And it's automaticly filled. I hope thats what you were looking for

Willie
  • 352
  • 1
  • 3
  • 15
1

If PassMeThis is in the same class (or ancestor), as in your example, there is no point, this is avaiable there, too.

If it is in another class, there is no way to automatically get a reference to the calling object: IS there any way to get a reference to the calling object in c#?

Marcell Toth
  • 3,433
  • 1
  • 21
  • 36