Bruno Brant
Bruno Brant

Reputation: 8564

Limiting a String length on a property

This question arose when I was trying to figure out a larger problem that, for simplicity sake, I'm omitting.

I have to represent a certain data structure in C#. Its a protocol that will be used to communicate with an external system. As such, it has a sequence of strings with predefined lengths and integer (or other, more complicated data). Let's assume:

SYSTEM : four chars
APPLICATION : eight chars
ID : four-byte integer

Now, my preferred way to represent this would be using strings, so

class Message
{
    string System {get; set; };      // four characters only!
    string Application {get; set; }; // eight chars
    int Id {get; set; };
}

Problem is: I have to ensure that string doesn't have more than the predefined length. Furthermore, this header will actually have tenths of fields, are those will change every now and then (we are still deciding the message layout).

How is the best way to describe such structure? I thought, for example, to use a XML with the data description and use reflection in order to create a class that adheres to the implementation (since I need to access it programatically).

And, like I said, there is more trouble. I have other types of data types that limits the number of characters/digits...

Upvotes: 3

Views: 3371

Answers (1)

Michael Madsen
Michael Madsen

Reputation: 55009

For starters: the whole length issue. That's easily solved by not using auto-properties, but instead declaring your own field and writing the property the "old-fashioned" way. You can then validate your requirement in the setter, and throw an exception or discard the new value if it's invalid.

For the changing structure: If it's not possible to just go in and alter the class, you could write a solution which uses a Dictionary (well, perhaps one per data type you want to store) to associate a name with a value. Add a file of some sort (perhaps XML) which describes the fields allowed, their type, and validation requirements.

However, if it's just changing because you haven't decided on a final structure yet, I would probably prefer just changing the class - if you don't need that sort of dynamic structure when you deploy your application, it seems like a waste of time, since you'll probably end up spending more time writing the dynamic stuff than you would altering the class.

Upvotes: 8

Related Questions