ArgumentNullException.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Runtime.CompilerServices;
  6. namespace CommunityToolkit.Mvvm;
  7. /// <summary>
  8. /// Internal polyfill for <see cref="System.ArgumentNullException"/>.
  9. /// </summary>
  10. internal sealed class ArgumentNullException
  11. {
  12. /// <summary>
  13. /// Throws an <see cref="System.ArgumentNullException"/> if <paramref name="argument"/> is <see langword="null"/>.
  14. /// </summary>
  15. /// <param name="argument">The reference type argument to validate as non-<see langword="null"/>.</param>
  16. /// <param name="paramName">The name of the parameter with which <paramref name="argument"/> corresponds.</param>
  17. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  18. public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null)
  19. {
  20. if (argument is null)
  21. {
  22. Throw(paramName);
  23. }
  24. }
  25. /// <summary>
  26. /// A specialized version for generic values.
  27. /// </summary>
  28. /// <typeparam name="T">The type of values to check.</typeparam>
  29. /// <remarks>
  30. /// This type is needed because if there had been a generic overload with a generic parameter, all calls
  31. /// would have just been bound by that by the compiler instead of the <see cref="object"/> overload.
  32. /// </remarks>
  33. public static class For<T>
  34. {
  35. /// <summary>
  36. /// Throws an <see cref="System.ArgumentNullException"/> if <paramref name="argument"/> is <see langword="null"/>.
  37. /// </summary>
  38. /// <param name="argument">The reference type argument to validate as non-<see langword="null"/>.</param>
  39. /// <param name="paramName">The name of the parameter with which <paramref name="argument"/> corresponds.</param>
  40. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  41. public static void ThrowIfNull([NotNull] T? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null)
  42. {
  43. if (argument is null)
  44. {
  45. Throw(paramName);
  46. }
  47. }
  48. }
  49. /// <summary>
  50. /// Throws an <see cref="System.ArgumentNullException"/>.
  51. /// </summary>
  52. /// <param name="paramName">The name of the parameter that failed validation.</param>
  53. [DoesNotReturn]
  54. private static void Throw(string? paramName)
  55. {
  56. throw new System.ArgumentNullException(paramName);
  57. }
  58. }