1

I might be having a brainfart here, and I probably am, however it's somewhat hard to word my problem, so I'm having some issues finding help.


Essentially, in Java, you can do something like this:

// create some generic class
public class Test {
   public void random() {}
}

// other class
public class Test2 {
   public Test2() {
      someFunction(new Test() {
         public void random() {
            System.out.println("howdy");
         }
      });
   }

   private someFunction(Test t) {
      t.random();
   }
}

I'm looking to convert this idea (modifying the contents of a class while passing it as a variable) into C#. I understand it can be done with lambda expressions, however I cannot for the life of me seem to figure it out. Any help is appreciated.

Reedie
  • 189
  • 1
  • 1
  • 11
  • You can't do something like that in Java: the call to `someFunction` would need to be in a method. Notwithstanding that, which bit of the "something" are you actually asking about: the Test class, the Test2 class, the anonymous class, the random method, the someFunction method...? – Andy Turner Oct 26 '15 at 00:15
  • Being able to modify the contents of random() while calling the method. – Reedie Oct 26 '15 at 00:17
  • Which one is "the method"? And how are you modifying the "contents of random()" in this code? – Andy Turner Oct 26 '15 at 00:19
  • In the class Test, the random function does nothing. When I pass an instance of Test to someFunction(), I edit the contents of random(). – Reedie Oct 26 '15 at 00:20

1 Answers1

1

I'm not 100% sure this is what you are trying to achieve, but you could do it this way. Replace the property with an Action delegate:

public class Test
{
    public Action random { get; set; }
}

And use like this:

var test = new Test 
{
    random = () => Console.WriteLine("Howdy")
};

test.random();

The delegate in this case is for a method that takes no parameters and has no return. If you wanted parameters you could use generic versions of Action. For example, if you need to pass an int:

public Action<int> random { get; set; }

Or if you wanted to return a value, then you would have to use Func<>:

public Func<int> random { get; set; }
DavidG
  • 113,891
  • 12
  • 217
  • 223