Where is the right place to format string in .NET?

Our database has a field called the employee number. This is a char (10) field. we keep the correct numbers. therefore we save numbers as " 1", " 2"etc. I'm not sure why we started to do this because it happened before I started working here.

In this regard, each function in business logic that has an employee number as one of the parameters must correctly substantiate the number. If we forget this, it will not update the database properly.

My question is:

Is there a better way to do this so that we don’t need to format the number in each function?

+3
source share
8 answers

, , , .

: , , varchar (10) ( , ) ( "" ). , , , .

. , . , .

+12

char, - . Integer, .

, , , .

+2

, , , , ,

+1

, . , .

, , . someString.RightJustify(10). . :

public static class ExtensionMethods
{
    public static string RightJustify(this string s, int chars)
    {
        if (s.Length > chars)
            return s.Substring(0, chars);
        else
            return s.PadLeft(chars, ' ');
    }
}
+1

, , . datalayer ? , ?

, , int bigint, , .

0

, , () .

public static int ToRightAlignedString(this int obj)
{
    return ("          " + obj.ToString()).Right(10);
}
0

(, ), , . - (#).

struct EmployeeNumber
{
    private int empNumber;

    public String EmpNum
    {
        set
        {
            int test;
            if (Int32.TryParse(value, out test))
            {
                empNumber = test;
            }
        }

        get
        {
            return empNumber.ToString("D10");
        }
    }
}

. , - ; . , . int .

0
Public Function foo(ByVal valToStore As Object) As String
    Dim RetVal As String = String.Empty
    If TypeOf valToStore Is String Then
        RetVal = DirectCast(valToStore, String)
    ElseIf TypeOf valToStore Is Integer Then
        RetVal = DirectCast(valToStore, Integer).ToString
    End If
    RetVal = RetVal.Trim.PadLeft(10, " "c)
    Return RetVal
End Function

, , . , VB.

0

Source: https://habr.com/ru/post/1704965/


All Articles