Skip to content

Commit

Permalink
Merge pull request #44 from BurkusCat/nullable-parameters
Browse files Browse the repository at this point in the history
Add support for nullable value types in nav parameters
  • Loading branch information
BurkusCat authored Oct 23, 2023
2 parents f0189b4 + 0d73dbf commit f34a119
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/Burkus.Mvvm.Maui/Models/NavigationParameters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ internal NavigationParameters(IDictionary<string, object> dictionary) : base(dic
/// <param name="parameterName">The name of the parameter.</param>
/// <param name="defaultValue">The default value to return if the parameter is not set.</param>
/// <returns>The value of the parameter or the default value.</returns>
private T GetParameter<T>(string parameterName, T defaultValue)
private T? GetParameter<T>(string parameterName, T defaultValue)
{
return ContainsKey(parameterName)
? GetValue<T>(parameterName)
Expand All @@ -66,7 +66,7 @@ private T GetParameter<T>(string parameterName, T defaultValue)
/// <exception cref="ArgumentException">
/// Thrown when the parameter value cannot be converted to the specified type.
/// </exception>
public T GetValue<T>(string parameterName)
public T? GetValue<T>(string parameterName)
{
if (!ContainsKey(parameterName))
{
Expand All @@ -78,13 +78,25 @@ public T GetValue<T>(string parameterName)

try
{
if (value == null)
{
return default;
}

if (typeof(T).IsEnum)
{
return (T)Enum.Parse(typeof(T), value.ToString());
}
else
{
return (T)Convert.ChangeType(value, typeof(T));
// get the non-nullable type of T
var underlyingType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);

// convert the value to the non-nullable type
var convertedValue = Convert.ChangeType(value, underlyingType);

// cast the converted value to T
return (T)convertedValue;
}
}
catch (Exception ex)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,34 @@ public void GetValue_ObjectParameter_NullValue_ReturnsNull()
Assert.Null(result);
}

[Fact]
public void GetValue_NullableValueParameters_ReturnsNullValue()
{
// Arrange
var navigationParameters = new NavigationParameters();
navigationParameters["NullableCharParam"] = null;

// Act
var result = navigationParameters.GetValue<char?>("NullableCharParam");

// Assert
Assert.Null(result);
}

[Fact]
public void GetValue_NullableValueParameters_ReturnsCharValue()
{
// Arrange
var navigationParameters = new NavigationParameters();
navigationParameters["NullableCharParam"] = 'C';

// Act
var result = navigationParameters.GetValue<char?>("NullableCharParam");

// Assert
Assert.Equal('C', result);
}

[Fact]
public void MergeNavigationParameters_WhenCalledWithEmptyDictionaries_ReturnsEmptyDictionary()
{
Expand Down

0 comments on commit f34a119

Please sign in to comment.