1

Ok i am going through Saplo Api C# project. It stump me when i saw these code:

public class Helper
{
    private static int _currentId;
    public static int GetCurrentId()
    {
        return _currentId;
    }
    public static int GetNextId()
    {
        return ++_currentId;
    }
}

[DataContract]
internal class RequestBase<T>
{
    public RequestBase()
    {
        ID = Helper.GetNextId().ToString(CultureInfo.InvariantCulture);
    }

    public RequestBase(string method, T @params)
        : this()
    {
        Method = method;
        Parameters = @params;
    }

    [DataMember(Name = "id")]
    public string ID { get; private set; }

    [DataMember(Name = "method")]
    public string Method { get; set; }

    [DataMember(Name = "params")]
    public T Parameters { get; set; }
}

So if you look at the constructor for RequestBase.... public RequestBase()! you will see Helper.GetNextId() this only return an int why bother using CultureInfo.InvariantCulture i dont understand why a simple ToString inst good enough to do the job or what, isnt this is just more overhead?

Photonic
  • 1,316
  • 19
  • 31

2 Answers2

2

When it comes to integers, there is currently no recognized, official culture that would affect how Int32.ToString() behaves. It will always create an identical string.

However, that does not mean that a custom culture might not interpret the results differently. Resharper and other code style tools typically recommend using a culture to maintain consistency.

It is worth noting, when travelling outside of integers, cultures absolutely make a difference. For instance, in EN-US, commas are used for thousands separation and periods are used to represent the decimal point. On the other hand, in EN-GB it's the opposite. Keeping consistency between value types could certainly be viewed as a good habit.

That said, in this case, yes, providing CultureInfo for integers is probably unnecessary "overhead", unless you prefer to keep consistency in your codebase.

David L
  • 32,885
  • 8
  • 62
  • 93
0

In this case it doesn't seem necessary. I know plugins like ReSharper and StyleCop will complain(show a warning) about an empty ToString() unless you tell them not to. It's possible one of these plugins was used when writing this code.

Generally CultureInfo.InvariantCulture is used when converting dates and decimal/currency values.

MGM_Squared
  • 167
  • 7