0

EDIT: The referenced duplicate is not an option as it was answered 5 years ago (and my reference 6 years ago) and I was hoping there was something more recent that did this rather than hand crafted work around code. Nor is the referenced duplicate a fully declarative solution.

I have a number of string properties off a class that are only allowed to be a maximum length. Coming from a Delphi background you were able to define a custom type as:

type TString10 = string[10];
type TString50 = string[50];

and then use that as part of a property definition:

property TString10 MyString
property TString10 MyOtherString
property TString50 YetOtherString
property TString50 AndTheLastOne

There appears to be no declarative equivalent in C# that I am aware of? So it appears my only options are:

  1. Write manual property setters or getters (that truncate to the specified length)
  2. Call a validation method that checks the properties to ensure their length is as needed

Or are there other approaches to enforcing a length on a string property declaritively?

Community
  • 1
  • 1
TheEdge
  • 9,291
  • 15
  • 67
  • 135

2 Answers2

1

What ways can I ensure that a string property is of a particular length?

I'm not entirely positive, but I believe this is what you are looking for. If it is, it appears that normal setters and getters are really the best way to go about this.

Community
  • 1
  • 1
ethan codes
  • 87
  • 10
1

I think options 1 & 2 pretty much cover it; they're the only two that I've ever used.

The fanciest way that I've ever done it is to create attributes that can be used to decorate the properties, and then have a Validation method to check the string length against the actual value. The classes were able to validate themselves, so everything was encapsulated within the class itself.

It also means that you can still use auto-properties.

DeanOC
  • 7,142
  • 6
  • 42
  • 56