none
Deleted RRS feed

Answers

All replies

  • There is a decent discussion here

    https://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c-sharp


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, August 15, 2019 5:59 PM
    Moderator
  • IMO, no you cannot pass a method has an argument to a method, expecting the method to be executed.

    You can pass an object into a method and execute a method on the passed in object as a parm on the method, a form of dependency injection.

    Thursday, August 15, 2019 6:10 PM
  • Hi BataBo,

    Thank you for posting here.

    For your question, you want to pass a method as a parameter to another function.

    You could refer to the following link.

    how to pass any method as a parameter for another function

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, August 16, 2019 2:18 AM
    Moderator
  • That is what delegates are for. LINQ is loaded with them but we'll do a simple one.

    public void CreateMyData ( Action<MyData> initializer )
    {
       var data = new MyData();
     
       //Call method defined by caller
       initializer(data);
    }
    
    //How you'd use it, using a lambda here
    var data = someType.CreateMyData(d => {
       d.Id = 10;
    });
    
    //Can be any function though
    private void InitializeData ( MyData data )
    {}
    
    var data = someType.CreateMyData(InitializeData);
    
    Note that if you only expect a single "function" to be called then a parameter to a method makes the most sense. If you want more of a notification system then use events. They are delegates as well and behave the same way, just designed for a different scenario.


    Michael Taylor http://www.michaeltaylorp3.net

    Friday, August 16, 2019 3:23 PM
    Moderator