-2

(I'm a bit new to programming so if this doesn't make sense just say so)

Let's say that a method takes in a void as parameter. Ex:

method(anotherMethod);

and I want to write the void inside of the brackets rather than writing the void and putting the name inside so rather than

void theVoid() {
    doSomethingHere;
}

and then calling it like

method(theVoid());

I wanted to do

method({ doSomethingHere; })

directly, is it possible to do so?

  • 2
    `void` is not a type. There is not way to have a method take `void` as a parameter type. In your first example you are not pass in "a void", you are passing a method (whose return type is `void`). Please post a reasonable example of what you're trying to do. – Rufus L Jun 17 '19 at 20:40
  • 1
    `method(theVoid());` doesn't make much sense. Can you show a code sample that actually compiles? – Sweeper Jun 17 '19 at 20:40
  • Just no, bro(for now). It seems you're trying to run before you can walk. I would just write out my code as "archaic" as possible, get it to work. and during the refactoring process, you can see if you can call methods within a method (which is usually possible depending on the method and circumstance). And because your void method isn't returning any type of data, chances of throwing that in as a argument for another method's parameter seems like it just isn't going to happen.... :/ sorry to tell ya – jPhizzle Jun 17 '19 at 20:46
  • I guess I worded my question wrong, but what I meant was what the first answer said below, my mistake. – Bolinho De Arroz Jun 17 '19 at 21:21

1 Answers1

0

The thing you are trying to do is called "lambda" it's anonymous functions Here is the documentation for that. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions

Your method will need to be passed a Delegate (if you do not return anything, an Action should be fine) https://learn.microsoft.com/en-us/dotnet/api/system.action-1?view=netcore-2.2

Method(TheVoid()); // does not compile
Method(TheVoid); // compiles
using System;

public class Example
{

    public void Method(Action func)
    {
        func();
    }

    public void TheVoid()
    {
        Console.WriteLine("In example.TheVoid");    
    }
}

public class Program
{
    public static void TheVoid()
    {
        Console.WriteLine("In TheVoid");
    }
    public static void Main()
    {
        var example = new Example();
        example.Method(example.TheVoid);
        example.Method(() => {
           Console.WriteLine("In lambda");
        });
        example.Method(TheVoid);
    }
}

Example of what you are trying to do

Blowa
  • 70
  • 1
  • 6