C
C#2y ago
Nora

✅ 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.
public class Example
{
//code
}

class Program
{
static void Main()
{
Example ex1 = new Example();
ex1.FooFunction();
}
}
public class Example
{
//code
}

class Program
{
static void Main()
{
Example ex1 = new Example();
ex1.FooFunction();
}
}
It's because I don't want to type lines like
ex1.FooFunction(ex1)
ex1.FooFunction(ex1)
or
cs Example.FooFunction(ex1)
cs Example.FooFunction(ex1)
Much help needed and appreciated!
5 Replies
vdvman1
vdvman12y ago
Functions defined in the class can just use this to access the object
public class Example
{
public string MyField = "hello";

public void FooFunction()
{
this.MyField = "there";
}
}
public class Example
{
public string MyField = "hello";

public void FooFunction()
{
this.MyField = "there";
}
}
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 it
FusedQyou
FusedQyou2y ago
Perhaps you mean CallerMemberName?
FusedQyou
FusedQyou2y ago
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.
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server