user2431419 user2431419 - 5 months ago 21
Vb.net Question

Extension method generic Vb to c#

I have a problem converting a method extension from VB.NET to C#, here is my working VB.NET code

Module ClientBaseExtensions
Private Const HDR_TOKEN = "Token"

<Extension()>
Public Sub Initialize(Of T As Class)(ByVal client As ClientBase(Of T), url As String, pToken As String, pDeviceId As String)
client.Endpoint.Address = New EndpointAddress(url)
httpRequestProperty.Headers.Item(HDR_TOKEN) = pToken
OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = httpRequestProperty
End Sub
End Module


When converting it automatically it gives me this code wich is not recognized in my clientbased object

static class ClientBaseExtensions
{

private const HDR_TOKEN = "Token";

public static void Initialize<T>(ClientBase<T> client, string url, string pToken, string pDeviceId) where T : class
{
client.Endpoint.Address = new EndpointAddress(url);
httpRequestProperty.Headers.Item(HDR_TOKEN) = pToken;
OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = httpRequestProperty;

}
}


Thank you for your help

Answer

In C#, extension methods are declared by specifying the this keyword for the first parameter (the one which defines the type that is extended):

static class ClientBaseExtensions
{

    private const  HDR_TOKEN = "Token";

                           // insert this here
    public static void Initialize<T>(this ClientBase<T> client, string url, string pToken, string pDeviceId) where T : class
    {
        client.Endpoint.Address = new EndpointAddress(url);
        httpRequestProperty.Headers.Item(HDR_TOKEN) = pToken;
        OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = httpRequestProperty;

    }
}
Comments