Jump to content

Improved C# bindings


Recommended Posts



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;


        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 to comment
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.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...