Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Object with fixed length C#

Tags:

c#

.net

I have a class wherein I want to use Strings with a fixed size. The reason for the fixed size is that the class "serializes" into a textfile with values with a fixed length. I want to avoid to write foreach value a guard clause and instead have the class handle this.

So I have round about 30 properties which would look like this

    public String CompanyNumber
    {
        get 
        {
            return m_CompanyNumber.PadLeft(5, ' ');
        }
        set 
        {
            if (value.Length > 5) 
            {
                throw new StringToLongException("The CompanyNumber may only have 5 characters", "CompanyNumber");
            }
            m_CompanyNumber = value; 
        }
    } 

I would like to have a String that handles this by itself. Currently I have the following:

public class FixedString
{
    String m_FixedString;

    public FixedString(String value)
    {
        if (value.Length > 5) 
        {
            throw new StringToLongException("The FixedString value may consist of 5 characters", "value");
        }
        m_FixedString= value;
    }

    public static implicit operator FixedString(String value)
    {
        FixedString fsv = new FixedString(value);
        return fsv;
    }

    public override string ToString()
    {
         return m_FixedString.PadLeft(5,' ');
    }
}

The problem I have with this solution is that I can't set the String length at "compile time".

It would be ideal if it would look something like this in the end

public FixedString<5> CompanyNumber { get; set; }
like image 628
Bongo Avatar asked May 12 '16 14:05

Bongo


1 Answers

I would go further back and question the design. This solution mashes together two concerns--internal application state and storage format--that should remain separate.

You could decorate each string property with a MaxLengthAttribute and then validate to that, but your code for (de)serializing from your storage format should be completely separate. It could use the same attributes to glean the field lengths for storage (if that happy coincidence holds) but your internal representation shouldn't "know" about the storage details.

like image 198
Marc L. Avatar answered Sep 23 '22 19:09

Marc L.