Getting a string's max length in C#

3 posts / 0 new
Last post
Offline
Last seen: 8 years 6 months ago
Joined: 09/26/2014
Posts: 5
Getting a string's max length in C#

I have a Topic with a string<150> field. Today, I learned that in C#, I can create such a topic, assign it a string that's too long (say, has 200 characters) and nothing will crash... until I actually try to write said topic (then the writer throws a retcode error that gives little information). So now for every topic that contains a string, I need to check that the string I assign doesn't exceed the maximum length before I write a topic sample. However, I can't seem to find any field or method to get the maximum length of a string field in a topic. All I can find is a comment in the .h file next to the field. Do I need to hardcode this value in my own code or is there a better way to get this information?

Thanks!

Offline
Last seen: 9 years 5 months ago
Joined: 01/29/2013
Posts: 4

Hello Philipe,

Indeed, the C# code (or any other supported programming language code) generated from the IDL does not contain any fields or methods to get the maximum length of a string field. The specification does not define this kind of functionality.

For this reasons (and others), it is considered good practice to use identifiers in the IDL to define the maximum length of a string, and similar for sequences. Something like this is found in the example Hello_idl in the standard distribution:

const long MAX_STRING_SIZE = 64;

const long MAX_PAYLOAD_SIZE = 8192;

struct HelloWorld {

  string<MAX_STRING_SIZE> prefix;

  long sampleId;

  sequence<octet, MAX_PAYLOAD_SIZE> payload;

};

This will allow you to refer to the identifiers MAX_STRING_SIZE and MAX_PAYLOAD_SIZE to check for the boundaries in your code.

Hope this helps,

Reinier

Offline
Last seen: 8 years 6 months ago
Joined: 09/26/2014
Posts: 5

Thanks, that seems like a good solution!