|
| 1 | +using System; |
| 2 | +using System.Linq; |
| 3 | + |
| 4 | +namespace CountryData.Standard |
| 5 | +{ |
| 6 | + /// <summary> |
| 7 | + /// Manages the CountryHelper instance and provides methods for retrieving country-related information. |
| 8 | + /// </summary> |
| 9 | + public class CountryExtensions : IDisposable |
| 10 | + { |
| 11 | + private CountryHelper _countryHelper; |
| 12 | + private bool _disposed = false; |
| 13 | + |
| 14 | + /// <summary> |
| 15 | + /// Constructor to initialize the CountryHelper instance. |
| 16 | + /// </summary> |
| 17 | + public CountryExtensions() |
| 18 | + { |
| 19 | + _countryHelper = new CountryHelper(); |
| 20 | + } |
| 21 | + |
| 22 | + /// <summary> |
| 23 | + /// Gets the country code for the specified country name. |
| 24 | + /// </summary> |
| 25 | + /// <param name="countryName">The name of the country.</param> |
| 26 | + /// <returns>The country code if found; otherwise, null.</returns> |
| 27 | + public string GetCountryCode(string countryName) |
| 28 | + { |
| 29 | + if (countryName == null) |
| 30 | + { |
| 31 | + throw new ArgumentNullException(nameof(countryName)); |
| 32 | + } |
| 33 | + |
| 34 | + var country = _countryHelper.GetCountryData() |
| 35 | + .FirstOrDefault(c => c.CountryName.Equals(countryName, StringComparison.OrdinalIgnoreCase)); |
| 36 | + |
| 37 | + return country?.CountryShortCode; |
| 38 | + } |
| 39 | + |
| 40 | + /// <summary> |
| 41 | + /// Dispose method to clean up resources. |
| 42 | + /// </summary> |
| 43 | + public void Dispose() |
| 44 | + { |
| 45 | + Dispose(true); |
| 46 | + GC.SuppressFinalize(this); |
| 47 | + } |
| 48 | + |
| 49 | + /// <summary> |
| 50 | + /// Protected method to dispose resources. |
| 51 | + /// </summary> |
| 52 | + /// <param name="disposing">Indicates whether the method is called from Dispose or finalizer.</param> |
| 53 | + protected virtual void Dispose(bool disposing) |
| 54 | + { |
| 55 | + if (!_disposed) |
| 56 | + { |
| 57 | + if (disposing && _countryHelper != null) |
| 58 | + { |
| 59 | + // Dispose managed resources. |
| 60 | + _countryHelper = null; |
| 61 | + } |
| 62 | + |
| 63 | + // Dispose unmanaged resources. |
| 64 | + |
| 65 | + _disposed = true; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + /// <summary> |
| 70 | + /// Finalizer to ensure resources are cleaned up. |
| 71 | + /// </summary> |
| 72 | + ~CountryExtensions() |
| 73 | + { |
| 74 | + Dispose(false); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments