Jump to content

Improved C# bindings


stevehayles

Recommended Posts

Hi,

 

I'm yet to actually receive any Tinkerforge products but I am evaluating it as a prototyping platform for a commercial product.  The multiple language bindings are fantastic but we do a lot of work in CSharp and this will be our primary language.

 

The legacy support for .Net2 is understandable but prevents the use of a number of new language features.  In our test code the biggest single issue was the use of the 'out' style return values.  It felt like a 'code smell' from day one and more importantly is a major hurdle to placing these calls inside Async / Await style methods. 

 

To this end I have just finished a T4 template solution that takes the existing bindings and wraps every appropriate call (that has an out parameter) in an extension method that allows the use of a named tuple return type. 

 

This will maintain complete backward compatibility but allow some much cleaner patterns for users of newer .Net frameworks.

 

As an example the original call in the 'BrickletRGBLED' class remains

 

public void GetRGBValue(out byte r, out byte g, out byte b)
{
byte[] request = CreateRequestPacket(8,FUNCTION_GET_RGB_VALUE);

byte[] response = SendRequest(request);

r = LEConverter.ByteFrom(8, response);
g = LEConverter.ByteFrom(9, response);
        b = LEConverter.ByteFrom(10, response);
}

 

but a new file is created called 'BrickletRGBLEDExtension'

 

which contains

 

public static (byte R, byte G, byte B) GetRGBValueEx(this BrickletRGBLED device)
{
        device.GetRGBValue(out byte r, out byte g, out byte b);

return(r, g, b);
}

 

This allows a very simple call like

 

        var result = brick.GetRGBValueEx();
        var red = result.R;

        //or

        var red = brick.GetRGBValueEx().R;

 

It requires VS2017 and .Net 45 or later but without that requirement the problem does not exist in the first place.

 

I am keen to release these to the community and wondering if it's best as a Nuget package library or to release the actual templates so that issues of keeping the packages in sync don't cause issues.

 

The templates might need small tweaks for users local environment but they run very quickly and produce a complete set of extensions for every device.

 

Keen to hear peoples thoughts

 

Link zu diesem Kommentar
Share on other sites

  • 1 month later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Gast
Reply to this topic...

×   Du hast formatierten Text eingefügt.   Formatierung jetzt entfernen

  Only 75 emoji are allowed.

×   Dein Link wurde automatisch eingebettet.   Einbetten rückgängig machen und als Link darstellen

×   Dein vorheriger Inhalt wurde wiederhergestellt.   Clear editor

×   Du kannst Bilder nicht direkt einfügen. Lade Bilder hoch oder lade sie von einer URL.

×
×
  • Neu erstellen...