locked
Using Action<T> as property RRS feed

  • Question

  • User-331009151 posted

    Hi all, I have come across something that I cannot quite get my head around. I have a class that has a property defined as follows;

    public Action<HttpRequestMessage> CustomiseRequestMessage { get; set; }

    This class is passed to another function that uses the properties set for CustomiseRequestMessage, in this case RequestHeaders.

    I can create an instance of the class itself but the property above is always null and I do not know how to initialize it correclty.

    The other bit I am struggling with is how do I go about setting any of the properties of CustomiseRequestMessage which is of type HttpRequestMessage?

    I have not worked much with delegate, func, etc and this Action<T> is a new one on me.

    Can anybody point me to any examples on how I can set the properties?

    Wednesday, November 15, 2017 4:29 PM

Answers

  • User-335504541 posted

    Hi scout7,

    I can create an instance of the class itself but the property above is always null and I do not know how to initialize it correclty.

    Please try to use the following code:

        class Program
        {
            static void Main(string[] args)
            {
                Model m = new Model();
                m.Name = "HttpRequestMessage";
                Action<HttpRequestMessage> RequestMessage;
                RequestMessage = ShowMessage;
                m.CustomiseRequestMessage = RequestMessage;
            }
           
            private static void ShowMessage(HttpRequestMessage message)
            {
                Console.WriteLine(message);
            }
        }
    
        class Model
        {
            public Action<HttpRequestMessage> CustomiseRequestMessage { get; set; }
            public string Name { get; set; }
        }

    The other bit I am struggling with is how do I go about setting any of the properties of CustomiseRequestMessage which is of type HttpRequestMessage?

    Do you want to set the properties of HttpRequestMessage? You could use Action<T1, T2> to pass the parameters to the function.

    And the Action Delegate takes up to 16 parameters.

    Here is the reference:

    https://msdn.microsoft.com/en-us/library/018hxwa8(v=vs.110).aspx

    Best Regards,

    Billy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 16, 2017 5:44 AM