8

Where described well-known reflection restrictions for Silverlight types?

For example: if I try to set protected or private property value with PropertyInfo.SetValue method I get an exception MethodAccessException.

Why did these restrictions?

AndreyR
  • 294
  • 4
  • 15

1 Answers1

11

For security purposes, reflection in Silverlight is limited to what is available at compile time. Mostly this means you can only access public members.

Here's what MS says about it: http://msdn.microsoft.com/en-us/library/stfy7tfc(VS.95).aspx

The reason for this is that the Silverlight internals are mostly private or internal to the main Silverlight assembly. If I could call those private functions without any parameter checking, I might be able to write a Silverlight app that reads your private files or something like that.

Gabe
  • 84,912
  • 12
  • 139
  • 238
  • 1
    Well, but where described that behavior? Which "security purposes" you know? – AndreyR Feb 18 '10 at 07:06
  • I don't actually understand this reasoning, considering that you can build Expressions that access private members. – Mike Marynowski Jul 11 '13 at 15:13
  • @Mike: Do you have an example? – Gabe Jul 11 '13 at 16:34
  • It's kind of silly actually how I had to write this whole wack of Expression based methods to get around reflection limitations...but it works. – Mike Marynowski Jul 11 '13 at 17:45
  • Note that this does not work for accessing private members in core framework assemblies, only user assemblies. But if they added the logic to work that our for Expression-based code, I really don't see why they didn't use the same validation logic for reflection. Would have made my life (and I'm sure many others) much easier. – Mike Marynowski Jul 11 '13 at 23:49
  • @MikeMarynowski What is the purpose of `if (obj != null && obj.GetType().IsSubclassOf(field.DeclaringType))`? If the object is a subclass of the field's declaring type, shouldn't it be expected to have the same requested fields? I guess I'm not following what the thrown exception is trying to prevent, and in my use case it throws but it seems like I'm able to still get the value back I'm looking for if I just commented that out... – Peter Tirrell Dec 07 '15 at 19:37
  • @PeterTirrell: The passed in object may be null, as you could be trying to access a static field. – Gabe Dec 24 '15 at 01:44
  • I know this reply is way overdue, been too busy for StackOverflow...but that was definitely a mistake. It should be: if (obj != null && !field.DeclaringType.IsInstanceOfType(obj)) – Mike Marynowski Jun 29 '16 at 23:55