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?

user8620575
  • 165
  • 2
  • 9
  • Possible duplicate of [At runtime, how can I test whether a Property is readonly?](https://stackoverflow.com/questions/5243764/at-runtime-how-can-i-test-whether-a-property-is-readonly) – Edgar Luque Sep 16 '17 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: https://stackoverflow.com/a/35856604/3346583 – Christopher Sep 16 '17 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. – user8620575 Sep 17 '17 at 10:18

1 Answers1

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.

Stephen Vernyi
  • 768
  • 5
  • 11
  • 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. – user8620575 Sep 17 '17 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. – Stephen Vernyi Sep 17 '17 at 17:53
  • @StephenVernyi raise an exception and handle it, just to discard can be very time consuming – Skary Aug 30 '21 at 11:06