c# – Is using "ToUInt64()" to format string correct?


Looking for a practical way to format string I came across the following: Convert.ToUInt64(string).ToString(@"00000\-000") .

Is it good practice to use this method to format strings ? Is there a recommended way?

Here is an example of usage:

 public class Program { public static void Main() { var nomeCep = "JOSE - 09017092"; var cep = nomeCep.Split('-')[1]; Console.WriteLine(Convert.ToUInt64(cep).ToString(@"00000\-000")); } }

Result: 09017-092


If it achieves the expected result in all situations, I cannot say it is wrong. But I consider workaround (which is sometimes the best way).

But I wouldn't do that. Text is text, number is number. The fact that a text contains only numeric digits does not make it a number. CEP is not used for calculations. I would always avoid treating them like numbers under any circumstances. So I wouldn't use this conversion and would format it as text anyway:

var nomeCep = "JOSE - 09017092";
var cep = nomeCep.Split('-')[1];
WriteLine($"{cep.Substring(0, 6)}-{cep.Substring(6, 3)}");

See working on ideone . And in .NET Fiddle . Also posted on GitHub for future reference .

It obviously has several other forms.

I even think that .NET needs a library a little better for formatting text, they just worked on numbers and dates. If I find any external library I'll post it here, but I don't remember seeing anything. I just found a simple extension method , but it takes care of several scenarios.

Scroll to Top