Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<Person>();

// Assert
person.ShouldBeOfType<Person>();
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<Person>();

// Assert
person.ShouldBeNull();
}

}

26 changes: 26 additions & 0 deletions DavidBerry.Framework/DavidBerry.Framework/Util/ObjectExtensions.cs
Original file line number Diff line number Diff line change
@@ -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
{


/// <summary>
/// Convenience method to perform an "as" cast on an object to the specified type
/// </summary>
/// <typeparam name="T">The Type to as cast the object to</typeparam>
/// <param name="obj">The object to be casted</param>
/// <returns>The obejct as type T or null if the object cannot be casted to the specified type</returns>
public static T? As<T>(this object obj) where T : class

Check warning on line 19 in DavidBerry.Framework/DavidBerry.Framework/Util/ObjectExtensions.cs

View workflow job for this annotation

GitHub Actions / build

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 19 in DavidBerry.Framework/DavidBerry.Framework/Util/ObjectExtensions.cs

View workflow job for this annotation

GitHub Actions / build

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
{
return obj as T;
}


}