Reputation: 442
I'm using a C# port (libphonenumber-csharp) of what is originally a Java library to parse phonenumbers into the correct format. However, I'm a bit confused as to how I should approach the "instance" of the PhoneNumberUtil class. The following snippet (from the source code, shortened to only include relevant parts) shows how you are supposed to get an instance:
public class PhoneNumberUtil
{
// Summary:
// Gets a PhoneNumbers.PhoneNumberUtil instance to carry out international phone
// number formatting, parsing, or validation. The instance is loaded with phone
// number metadata for a number of most commonly used regions.
// The PhoneNumbers.PhoneNumberUtil is implemented as a singleton. Therefore, calling
// getInstance multiple times will only result in one instance being created.
//
// Returns:
// A PhoneNumbers.PhoneNumberUtil instance.
public static PhoneNumberUtil GetInstance()
{
return instance ?? GetInstance("PhoneNumberMetaData.xml");
}
public static PhoneNumberUtil GetInstance(string baseFileLocation, Dictionary<int, List<string>> countryCallingCodeToRegionCodeMap = null)
{
lock (ThisLock)
{
return instance ?? (instance = new PhoneNumberUtil(baseFileLocation, null, countryCallingCodeToRegionCodeMap));
}
}
}
Maybe I'm just getting confused by the "Instance"-terminology but I struggle in understanding how I should instantiate this in my code. From what I'm used to see I would expect a Util class to be static and then I would not need care about instantiating but rather just call methods like PhoneNumberUtil.Parse(args...) or similar. Would it make sense to save the intance in private static field as such:
using PhoneNumbers;
internal static class PhoneNumberHelper
{
private readonly static PhoneNumberUtil _phoneNumberUtil = PhoneNumberUtil.GetInstance();
private const string SwedishCountryCode = "SE";
public static bool TryParsePhoneNumber(string phonenumberToParse, out string result)
{
try
{
var phoneNumber = _phoneNumberUtil.Parse(phonenumberToParse, SwedishCountryCode);
result = phoneNumber.CountryCode.ToString() + phoneNumber.NationalNumber;
return true;
}
catch (Exception ex)
{
result = string.Empty;
return false;
}
}
}
Or should I rather just always call the GetInstance() method like this:
using PhoneNumbers;
internal static class PhoneNumberHelper
{
private const string SwedishCountryCode = "SE";
public static bool TryParsePhoneNumber(string phonenumberToParse, out string result)
{
try
{
var phoneNumber = PhoneNumberUtil.GetInstance().Parse(phonenumberToParse, SwedishCountryCode);
result = phoneNumber.CountryCode.ToString() + phoneNumber.NationalNumber;
return true;
}
catch (Exception ex)
{
result = string.Empty;
return false;
}
}
}
Does any of this even matter? Maybe I mix up static and singleton a bit?
Upvotes: 1
Views: 694