0

I have this code using reflection and I decided to replace it by FastMember.

This is my code:

var VehicleType = TypeAccessor.Create(res.GetType());
var vehicleFastMember = ObjectAccessor.Create(res);

foreach (var kvp in dictionary)
{
    if (kvp.Key == "Identifier") continue;
    object value = kvp.Value;

    if (VehicleType.GetMembers().FirstOrDefault(prop => prop.Name == kvp.Key) != null)
    {
        // here inside if i want to check whether property is not readonly, 
        // I am afraid of runtime exception that readonly cannot be overwritten.
        **if (vehicleFastMember[kvp.Key].)**
        {
            vehicleFastMember[kvp.Key] = kvp.Value;
        }                        
    }
}

By reflection:

That row with stars would be solved by this line:

if (property?.CanWrite ?? false)

Does FastMember offer some elegant solution too?

3
  • Possible duplicate of At runtime, how can I test whether a Property is readonly? Commented Sep 16, 2017 at 23:47
  • However I would not use the marked answer. In the end there are many ways to implement a "read only property", the simplest being just a private or no setter and a lower solution handles those cases: stackoverflow.com/a/35856604/3346583 Commented Sep 16, 2017 at 23:57
  • Edgar: That link does not solve my problem in my opinion. kvp.Key is string and i cannot put string to the typeof() in that way how they do that. And that solution is not for FastMember. Commented Sep 17, 2017 at 10:18

1 Answer 1

0

According to the source code of fast-member's MemberSet.Member, CanRead/CanWrite are calling the same methods you are trying to call (PropertyInfo.Can[Read/Write]).

It's also worth noting that instead of determining if the property is writable, you could simply wrap the assignment into a try/catch, and catch the ReadOnlyException that would emerge and continue with the loop.

3
  • good answer, but i cannot reach from my code any public method from source code you referred to. When i press F12 in VS, it shows me diferrent source code, only several method declarations... I have installed FastMember.Signed 1.1.0 version. Commented Sep 17, 2017 at 11:17
  • It looks like the commit that added CanRead/CanWrite was pushed Sep 8'th, while FastMember 1.1.0 was released August 26'th, both in 2016. You can download the project and compile it yourself to access the CanRead/CanWrite on FastMember, or you can just use the PropertyInfo methods. Short of that you can bug the author on Github to issue a new release. Commented Sep 17, 2017 at 17:53
  • @StephenVernyi raise an exception and handle it, just to discard can be very time consuming
    – Skary
    Commented Aug 30, 2021 at 11:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.