Author Topic: Improved C# bindings  (Read 514 times)

stevehayles

  • Newbie
  • *
  • Posts: 13
    • View Profile
Improved C# bindings
« on: February 28, 2018, 15:32:35 »
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

Code: [Select]
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

Code: [Select]
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

Code: [Select]
        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

jijothomas

  • Newbie
  • *
  • Posts: 1
  • Assignments, Essays, Dissertations and More
    • View Profile
    • Assignment Help
Re: Improved C# bindings
« Reply #1 on: April 25, 2018, 11:01:08 »
Great One!, Glad to be here, I was looking for something like this.