From cfc537d8c6a087567b0083d7117fc69a1267f12e Mon Sep 17 00:00:00 2001 From: David Berry Date: Fri, 31 Oct 2025 23:18:40 -0500 Subject: [PATCH] Added extension method As to allow easy soft casting of objects --- .../Util/ObjectExtensionsTests.cs | 54 +++++++++++++++++++ .../Util/ObjectExtensions.cs | 26 +++++++++ 2 files changed, 80 insertions(+) create mode 100644 DavidBerry.Framework/DavidBerry.Framework.Tests/Util/ObjectExtensionsTests.cs create mode 100644 DavidBerry.Framework/DavidBerry.Framework/Util/ObjectExtensions.cs diff --git a/DavidBerry.Framework/DavidBerry.Framework.Tests/Util/ObjectExtensionsTests.cs b/DavidBerry.Framework/DavidBerry.Framework.Tests/Util/ObjectExtensionsTests.cs new file mode 100644 index 0000000..7aa424a --- /dev/null +++ b/DavidBerry.Framework/DavidBerry.Framework.Tests/Util/ObjectExtensionsTests.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DavidBerry.Framework.Util; +using Shouldly; +using Xunit; + +namespace DavidBerry.Framework.Tests.Util; + + + +public class ObjectExtensionsTests +{ + + public class Person + { + public string Name { get; set; } + public int Age { get; set; } + } + + + [Fact] + public void As_CorrectlyCastsAnObjectToCorrectType() + { + // Arrange + object obj = new Person() { Name = "John", Age = 30 }; + + // Act + var person = obj.As(); + + // Assert + person.ShouldBeOfType(); + person.Name.ShouldBe("John"); + person.Age.ShouldBe(30); + } + + + [Fact] + public void As_ReturnsNullWhenIncorrectTypeGiven() + { + // Arrange + object obj = new string("hello World"); + + // Act + var person = obj.As(); + + // Assert + person.ShouldBeNull(); + } + +} + diff --git a/DavidBerry.Framework/DavidBerry.Framework/Util/ObjectExtensions.cs b/DavidBerry.Framework/DavidBerry.Framework/Util/ObjectExtensions.cs new file mode 100644 index 0000000..e3995fe --- /dev/null +++ b/DavidBerry.Framework/DavidBerry.Framework/Util/ObjectExtensions.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DavidBerry.Framework.Util; + +public static class ObjectExtensions +{ + + + /// + /// Convenience method to perform an "as" cast on an object to the specified type + /// + /// The Type to as cast the object to + /// The object to be casted + /// The obejct as type T or null if the object cannot be casted to the specified type + public static T? As(this object obj) where T : class + { + return obj as T; + } + + +} +