views:

120

answers:

3

Take the following property:

public string Foo
{
   get;
   private set;
}

Using reflection, I can still set the value of this property from outside the owning class. Is there a way to prevent this? Removing the set accessor is not an option as it must be WCF friendly.

+4  A: 

Jon Skeet says:

You can't (AFAIK) stop reflection being used in a situation where the caller has "full trust". If they're running with less than full trust then some things about reflection (if not all) are automatically disabled, I believe - however, if this is to stop other people from calling some code, you can't prevent them from running your code with full trust unless you're in control of their box in the first place.

dtb
[ReflectionPermission(SecurityAction.Deny, Flags = ReflectionPermissionFlag.AllFlags)] is about all i can think of, but it may not really help
Greg Dean
+3  A: 

A really ugly solution would be to use the StackTrace class to verify that only methods from your own class calls the setter.

Simon Svensson
A: 

You could obfuscate the code. This would make it hard to reflect on it.

erikkallen