Skip to content

Commit

Permalink
Remove extra call to PropertyInfo.GetValue(object) (#60415)
Browse files Browse the repository at this point in the history
Fix #52905
  • Loading branch information
danielmpetrov committed Oct 14, 2021
1 parent feed66d commit 97ef512
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -248,19 +248,17 @@ private static void BindProperty(PropertyInfo property, object instance, IConfig
return;
}

object propertyValue = property.GetValue(instance);
bool hasSetter = property.SetMethod != null && (property.SetMethod.IsPublic || options.BindNonPublicProperties);

if (propertyValue == null && !hasSetter)
if (!hasSetter)
{
// Property doesn't have a value and we cannot set it so there is no
// point in going further down the graph
// The property cannot be set so there is no point going further
return;
}

propertyValue = GetPropertyValue(property, instance, config, options);
object propertyValue = GetPropertyValue(property, instance, config, options);

if (propertyValue != null && hasSetter)
if (propertyValue != null)
{
property.SetValue(instance, propertyValue);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@ public class ByteArrayOptions
public byte[] MyByteArray { get; set; }
}

public class GetterOnlyOptions
{
public string MyString => throw new NotImplementedException();
}

[Fact]
public void CanBindIConfigurationSection()
{
Expand Down Expand Up @@ -343,6 +348,20 @@ public void ThrowsIfPropertyInConfigMissingInNestedModel()
Assert.Equal(expectedMessage, ex.Message);
}

[Fact]
public void DoesNotExecuteGetterIfNoSetter()
{
var dic = new Dictionary<string, string>
{
{"MyString", "hello world"}
};
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(dic);
var config = configurationBuilder.Build();

var _ = config.Get<GetterOnlyOptions>();
}

[Fact]
public void GetDefaultsWhenDataDoesNotExist()
{
Expand Down

0 comments on commit 97ef512

Please sign in to comment.