I know some of relection capabilities, but i never understand exectly when and why should i use them , I would like some examples on how and when is a good idea to use it?
What are the design patterns you know wich performed with reflection?
Is there any operation that can be done only with the use of reflection?
very common use case: calling a function decided at run time.
Imagine a server that accepts requests like this
foo(3)
bar("joe")
wiz(42.0)
You need to write code that looks up to find the requested method and call it. You could do that with a big switch statement but that doesnt work in some cases (maybe you allow dlls to be loaded at different time that has different functions), also you need to work out what transformations need to be made of the paramters.
Instead you do
// name = method to execute
// module is instance of execution code class
var method = module.GetType().GetMethod(name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);
method.Invoke(module, ....);
Reflection is a powerful tool to implement difuse programming. When you know what you want, but you don't know what you'll get until run-time, reflection is the answer.
Common scenarios:
1) Meta-programming: Attributes.
When you need to extend the language to provide more meaning where access modifiers (public, private...) aren't enough, you use attributes.
Attributes are associated with assembly members and type members, and they need to be got using reflection.
Given the following attribute and a class using the whole attribute:
public class NameAttribute : Attribute
{
public NameAttribute(string name)
{
Name = name;
}
public string Name { get; }
}
[Name("Custom name")]
public class A
{
}
...you get the attribute using reflection:
NameAttribute nameAttr = typeof(A).GetCustomAttribute<NameAttribute>();
Since attributes are regular classes, they provide a powerful way of associating metadata to assemblies, classes, interfaces, enumerations and type members during compile-time to get them during run-time based on a set of conditions.
2) To implement convention over configuration
Convention over configuration is a powerful development paradigm to implement frameworks and libraries that work with near to zero configuration and, if you follow some rules, they get automatically configured.
Reflection plays an important role here. For example, Entity Framework can determine which is the primary key on the database when using Code First strategy using reflection.
Given an entity like the following one:
public class Customer
{
public Guid Id { get; set }
public string Name { get; set; }
}
...Entity Framework may know that Id will be the primary key by convention, and using reflection can find out if there's an Id property:
PropertyInfo idProperty = typeof(Customer).GetProperty("Id", BindingFlags.Public | BindingFlags.Instance);
if(idProperty != null)
{
// Yes, it has an Id property!
}
3) To take decisions during run-time
Since reflection enables your code to introspect and execute nearly everything you could do during compile-time (obviously, with a high performance impact), it lets you get a method, property or whatever based on a search and invoke them to get or set values.
4) Expression trees: introspecting expression's body
Expression trees are a powerful tool in C# to produce code as a data structure.
For example, I can define a class FileChecker and wrap a call to its Exists method in an expression tree, and later get which method was called, its parameters and even the class which declares the whole method during run-time using reflection:
public class FileChecker
{
public bool Exists(string filePath) { }
}
Checker checker = new Checker();
Expression<Func<bool>> expr = () => checker.Exists(#"C:\hello.txt");
MethodCallExpression methodCallExpr = (MethodCallExpression)expr.Body;
MethodInfo calledMethod = methodCallExpr.Method;
IEnumerable<ParameterInfo> inputParams = calledMethod.GetParameters();
Type declaringType = calledMethod.DeclaringType;
Related
What is the difference in functionality between using a field with get and set methods versus using a property to attribute a value to an object through a class? For example, when setting up a value val in a class, are there any reasons to choose one of the two classes below over the other (other than length of code written and interface compatibility):
class FieldTest
{
public FieldTest()
{
}
private string val;
public void SetVal(string temp)
{
val = temp;
}
public string GetVal()
{
return val;
}
}
Versus
class PropertyTest
{
public PropertyTest()
{
}
public string val { get; set; }
}
Tested Usage in Visual Studio 2010:
class TestFunctions
{
static void Main(string[] args)
{
FieldTest Test_Fields = new FieldTest();
Test_Fields.SetVal("Test");
string temp_str = Test_Fields.GetVal();
PropertyTest Test_Property = new PropertyTest();
Test_Property.val = "test";
string temp_str_prop = Test_Property.val;
System.Windows.Forms.MessageBox.Show("Field: " + temp_str + "\n\nProperty: " + temp_str_prop);
}
}
I know only a field can use ref and out keywords, but the other advantages usually attributed to a property--encapsulation, versioning, etc-- seem to be the same with these two setups.
I've checked articles such as Difference between Property and Field in C# 3.0+ and What is the difference between a Field and a Property in C#?. Though they give good descriptions of the ideas behind properties and fields, I have not been able to find a specific answer to my question.
Thanks in advance for clarification.
EDIT 2015-07-29:
I believe this to be a separate question from other StackOverflow answers, such as those found here, as these answers did not seem to specifically address using fields with their own get and set methods as a replacement for a property.
My statement above, "I know only a field can use ref and out keywords..." comes from answers similar to the following (found here):
"Fields may be used for out / ref parameters, properties may not. Properties support additional
logic – this could be used to implement lazy loading among other things."
The functionality is almost identical. For "normal" code use-cases, these snippets will act exactly the same, as a property is in effect just a hidden field with two hidden methods (get and set).
However, there is a difference when it comes to reflection. Properties show up as PropertyInfo, and methods MethodInfo. You also can only bind to properties (in WPF/WinRT). Serialization also only works against properties. Both of these (and doubtlessly others) fail because they use reflection to find the members to act against.
So depending on your use case, they are the same. Generally speaking, I would stick with properties.
In the .NET world properties are how you attribute data to objects. Methods are typically actions associated with the objects. Fields usually store internal (private) object instance state.
Under the hood, read/write property accessors get compiled to get and set methods.
Additionally, many technologies do not work with methods. Data Annotations, Entity Framework, and serialization are a few that pop instantly to mind.
I would always vote for properties rather than getter and setter.
First of all - using Property is neat and clean. The code is more clear, less junky and easy to understand.
If you use Automatic Property you just need one line of code for one Property where you need at least 6 for a getter and setter approach. So if your class has 20 attributes then total 120 lines of codes? Oh Man!!!
but the other advantages usually attributed to a property--encapsulation, versioning, etc-- seem to be the same with these two setups. => I disagree, consider a scenario where you want to force all implementation of an interface with an attribute to be readonly. That is easily doable with a readonly property in the interface. Now try that with getter and setter. Frankly you can't.
Then there comes Serialization. You cannot serialize a computed value unless that is a property. Methods are never serialized.
Let's take a look at your second code:
class PropertyTest
{
public PropertyTest()
{
}
public string val { get; set; }
}
As said in the Auto-Implemented Properties page on MSDN, when you declare an auto-implemented property like in your example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
In other words, it would be like writing this code:
public class PropertyTest
{
public PropertyTest()
{
}
private string _val;
public string val
{
get { return _val; }
set { val = value; }
}
}
So, properties are a way to encapsulate fields. As you can see on MSDN, too:
A property is a member that provides a flexible mechanism to read,
write, or compute the value of a private field. Properties can be used
as if they are public data members, but they are actually special
methods called accessors. This enables data to be accessed easily and
still helps promote the safety and flexibility of methods.
In my opinion, you should always prefer to use the property implementation than the getter/setter methods. Not because it seems cleaner and flexible to make things like compute values, but it is actually easier to implement (you write less code on auto-implemented properties).
We could say that there are almost no difference from the properties than the getter/setter methods too, if we look at the part where MSDN says "but they are actually special methods called accessors". But again, we have the example of brainless coder above, we have Framework behaviours that encourages us to use properties: methods can not be serialized, while properties can.
I'm creating a custom attribute in C# and I want to do different things based on whether the attribute is applied to a method versus a property. At first I was going to do new StackTrace().GetFrame(1).GetMethod() in my custom attribute constructor to see what method called the attribute constructor, but now I'm unsure what that will give me. What if the attribute was applied to a property? Would GetMethod() return a MethodBase instance for that property? Is there a different way of getting the member to which an attribute was applied in C#?
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property,
AllowMultiple = true)]
public class MyCustomAttribute : Attribute
Update: okay, I might have been asking the wrong question. From within a custom attribute class, how do I get the member (or the class containing the member) to which my custom attribute was applied? Aaronaught suggested against walking up the stack to find the class member to which my attribute was applied, but how else would I get this information from within the constructor of my attribute?
Attributes provide metadata and don't know anything about the thing (class, member, etc.) they are decorating. On the other hand, the thing being decorated can ask for the attributes it is decorated with.
If you must know the type of the thing being decorated you will need to explicitly pass it to your attribute in its constructor.
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property,
AllowMultiple = true)]
public class MyCustomAttribute : Attribute
{
Type type;
public MyCustomAttribute(Type type)
{
this.type = type;
}
}
Since there seems to be a lot of confusion with respect to how the stack frames and methods work, here is a simple demonstration:
static void Main(string[] args)
{
MyClass c = new MyClass();
c.Name = "MyTest";
Console.ReadLine();
}
class MyClass
{
private string name;
void TestMethod()
{
StackTrace st = new StackTrace();
StackFrame currentFrame = st.GetFrame(1);
MethodBase method = currentFrame.GetMethod();
Console.WriteLine(method.Name);
}
public string Name
{
get { return name; }
set
{
TestMethod();
name = value;
}
}
}
The output of this program will be:
set_Name
Properties in C# are a form of syntactic sugar. They compile down to getter and setter methods in the IL, and it's possible that some .NET languages might not even recognize them as properties - property resolution is done entirely by convention, there aren't really any rules in the IL spec.
Now, let's say for the moment that you had a really good reason for a program to want to examine its own stack (and there are precious few practical reasons to do so). Why in the world would you want it to behave differently for properties and methods?
The whole rationale behind attributes is that they are a kind of metadata. If you want a different behaviour, code it into the attribute. If an attribute can mean two different things depending on whether it's applied to a method or property - then you should have two attributes. Set the target on the first to AttributeTargets.Method and the second to AttributeTargets.Property. Simple.
But once again, walking your own stack to pick up some attributes from the calling method is dangerous at best. In a way, you are freezing your program's design, making it far more difficult for anybody to extend or refactor. This is not the way attributes are normally used. A more appropriate example, would be something like a validation attribute:
public class Customer
{
[Required]
public string Name { get; set; }
}
Then your validator code, which knows nothing about the actual entity being passed in, can do this:
public void Validate(object o)
{
Type t = o.GetType();
foreach (var prop in
t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (Attribute.IsDefined(prop, typeof(RequiredAttribute)))
{
object value = prop.GetValue(o, null);
if (value == null)
throw new RequiredFieldException(prop.Name);
}
}
}
In other words, you're examining the attributes of an instance that was given to you but which you don't necessarily know anything about the type of. XML attributes, Data Contract attributes, even Attribute attributes - almost all attributes in the .NET Framework are used this way, to implement some functionality that is dynamic with respect to the type of an instance but not with respect to the state of the program or what happens to be on the stack. It is very unlikely that you are actually in control of this at the point where you create the stack trace.
So I'm going to recommend again that you don't use the stack-walking approach unless you have an extremely good reason to do so which you haven't told us about yet. Otherwise you are likely to find yourself in a world of hurt.
If you absolutely must (don't say we didn't warn you), then use two attributes, one that can apply to methods and one that can apply to properties. I think you'll find that to be much easier to work with than a single super-attribute.
GetMethod will always return you the function name. If it is a property, you will get either get_PropertyName or set_PropertyName.
A property is basically a type of method, so when you implement a property, the compiler creates two separate functions in the resulting MSIL, a get_ and a a set_ methods. This is why in the stack trace you receive these names.
custom attributes are activated by some code calling the GetCustomAttributes method on the ICustomAttributeProvider (reflection object) that represents the location where the attribute is applied. So in the case of a property, some code would obtain the PropertyInfo for the property and then call GetCustomAttributes on that.
If you want to build out some validation framework you would need to write the code that inspects types & members for custom attributes. You could for example have an interface that attributes implement to participate in your validation framework. Could be as simple as the following:
public interface ICustomValidationAttribute
{
void Attach(ICustomAttributeProvider foundOn);
}
Your code could look for this inteface on (for example) a Type:
var validators = type.GetCustomAttributes(typeof(ICustomValidationAttribute), true);
foreach (ICustomValidationAttribute validator in validators)
{
validator.Attach(type);
}
(presumably you would walk the whole reflection graph and do this for each ICustomAttributeProvider). For an example of a similar approach in action in the .net FX you can look at WCF's 'behaviors' (IServiceBehavior, IOperationBehavior, etc).
Update: the .net FX does have a sort-of general purpose, but basically undocumented interception framework in the form of ContextBoundObject and ContextAttribute. You can search the web for some examples of using it for AOP.
Consider the following attribute.
internal class NiceAttribute : Attribute
{
private string _stuff;
public string Stuff
{
set { _stuff = value; }
}
}
When I try to use the attribute [Nice(Stuff = "test")] the compiler gives the following error.
'Stuff' is not a valid named attribute argument. Named attribute
arguments must be fields which are not readonly, static, or const, or
read-write properties which are public and not static.
What is the rational behind the requirement for the property to be readable?
Update
I will try to sketch my use case for having write-only properties on attributes.
interface ISettingsBuilder
{
Settings GetSettings();
}
class SettingsAttribute : Attribute, ISettingsBuilder
{
private readonly IDictionary<string, object> _settings =
new Dictionary<string, object>();
public Settings GetSettings()
{
// Use _settings to create an immutable instance of Settings
}
public string Stuff
{
set { _settings["Stuff"] = value; }
}
// More properties ...
}
There may be other implementations of ISettingsBuilder. For example one that offers a nice API to build settings through code.
I ended up with implementing my getters by throwing a NotImplementedException.
public string Stuff
{
get { throw new NotImplementedException(); }
set { _settings["Stuff"] = value; }
}
Can you think of a nicer way to do something like this?
I suspect the compiler is using a slightly misguided check to see whether you are accessing a private property here
Edit "we" have now located the actual source. For informational purposes, here is the full breakdown, but feel free to skip to the bottom.
(note how bug should be filed against the Mono compiler. I'll think that one over for a while)
Compiler Error CS0617
http://msdn.microsoft.com/en-us/library/978b3z1b(v=vs.71).aspx
'reference' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static or const, or read-write properties which are not static.
An attempt was made to access a private member of an attribute class.
It could seem that it is using some kind of lookup (akin to reflection) to make sure that the getter is accessible and if it isn't, concludes that it must be private.
Which, of course, it doesn't need to be :)
Mono Compatibility:
For fun, observe that the mono compiler has no problem whatsoever accepting this attribute: https://ideone.com/45fCX
Because of Reflection:
Of course it could be that the compiler requires attribute parameters to have reflectable values. If the property wasn't publicly readable, you could only use reflection to 'observe' that the attribute is present, not with what parameter it was initialized.
I don't know exactly, why such a design choicde would have been made, but it does make sense if you factor in reflection usage.
Update #Arun posted the relevant quote that confirms this conjecture (thanks!):
Accessing Attributes Through Reflection Once attributes have been associated with program elements, reflection can be used to query their existence and values. The main reflection methods to query attributes are contained in the System.Reflection.MemberInfo class (GetCustomAttributes family of methods).
So the reason must be: Attribute parameters must have reflectible values
Prize question: How does that work with positional parameters? How would one reflect those?
This link is a reference from Visual Studio 2003, but I guess it hardly changed.
Relevant portion from that link:
Accessing Attributes Through Reflection
Once attributes have been associated with program elements, reflection can be used to query their existence and values. The main reflection methods to query attributes are contained in the System.Reflection.MemberInfo class (GetCustomAttributes family of methods).
I need to create a proxy which intercepts properties in a class. I know how to create a dynamic proxy with Emit from an interface, but what if I don't have an interface? I've seen samples which use RealProxy (like this one: Is there a way to call a method when any property of a class is set?) but is it possible to use type generation and emit to achieve the same thing? I don't want the "owner" of the concrete class to see any traces of MarshalByRefObject if possible (see below)...
I believe Castle is able to do this, but maybe it's using RealProxy under the covers?
User user = Create<User>();
public class User
{
public string Name { get; set; }
}
public T Create<T>()
{
//magic happens here... :)
return (T)GenerateInterceptingProxyFromT(typeof(T));
}
I just started messing with postshrp, one of the AOP tools Miguel mentioned, do functionally what you are trying to do. It uses "static weaving" to inject code at compile time so should be invisible to consumers. Obviously, you need to modify the code that you want to instrument for this to work.
The answer to This question suggests using the profiler API which may be an option for you if PostSharp, or Castle won't do what you need.
There are some options on intercepting things in .Net:
If it is an interface, you can implement a new type from that dynamically, and make a proxy, that would re-call the other inner object.
If it is an abstract class or a class that allows overrides, you can inherit from it and override the desired members dynamically, and do whatever you want.
If the type you want to intercept has no interfaces, nor overridable methods, or properties, then you must change the assembly that constains that type, before it loads. You cannot change the code of an assembly after it has been loaded. I think that PostSharp works this way.
Most of the mocking tools, used for testing purposes uses the first/second alternatives, but that makes them work only with member of the classes that are overridable, or implemented through an interface.
Aspect Oriented Programming tools use the third alternative, but it is more work to do, because you need to process the assembly before it is loaded.
Since this is a very common problem and a great reason to choose an AOP approach as Miguel suggested, I created an example for Afterthought that demonstrates implementing INotifyPropertyChanged (intercepting property sets to raise an event).
Afterthought lets you describe interceptions for properties very easily, and specifically makes property set interception simple by providing you the before and after values of the property. You would do something like this to identify the properties to intercept:
public override void Amend<TProperty>(Property<TProperty> property)
{
// Raise property change notifications
if (property.PropertyInfo.CanRead && property.PropertyInfo.CanWrite)
property.AfterSet = NotificationAmender<T>.OnPropertyChanged<TProperty>;
}
Which in this case calls a static method OnPropertyChanged which looks like this:
public static void OnPropertyChanged<P>(INotifyPropertyChangedAmendment instance, string property, P oldValue, P value, P newValue)
{
// Only raise property changed if the value of the property actually changed
if ((oldValue == null ^ newValue == null) || (oldValue != null && !oldValue.Equals(newValue)))
instance.OnPropertyChanged(new PropertyChangedEventArgs(property));
}
So if your original property looked like this:
string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
It would look like this after applying the above amendment using Afterthought:
string name;
public string Name
{
get
{
return name;
}
set
{
string oldValue = Name;
name = value;
NotificationAmender<ConcreteClass>.OnPropertyChanged<string>(
this, "Name", oldValue, value, Name);
}
}
In your case, the static method called after (or before) the setter could be named anything you want and do anything you want. This is just an example of a concrete and well known reason to intercept property setters. Given that you know the properties are non-virtual, it is not possible to create proxy subclasses to perform the interception, so I think AOP approaches like Afterthought or PostSharp are your best bet.
Also, with Afterthought you can implement the interception such that the resulting assemblies do not have any references or dependencies on Afterthought and if your interception logic does not actually add/change the API for your target types, there is no reason the "owner" of the concrete class would have a problem with the result.
See the code:
class DataItem
{
public DataItem(int num, string s)
{
Number = num;
Str = s;
}
public int Number { get; set; }
public string Str { get; set; }
}
static void Main(string[] args)
{
var data = new DataItem(2, "hi");
var provider = TypeDescriptor.AddAttributes(typeof(DataItem),
new SerializableAttribute());
var another = provider.CreateInstance(null, typeof(DataItem),
new Type[] { typeof(int), typeof(string) },
new object[] { 100, "hello" }) as DataItem;
var newProperty = TypeDescriptor.CreateProperty(another.GetType(), "Str",
typeof(string),
new DescriptionAttribute("new property"));
//newProperty.SetValue(another, "new one");
Console.WriteLine(newProperty.GetValue(another));
Console.Read();
}
And I have several questions for the code:
(1) I added a SerializableAttribute to the Type of DataItem, what is this "change" applied to? I can't get this attribute by typeof(DataItem).GetCustomAttributes(true).It seems that the change is not applied to the "essential DataItem", it is stored in the TypeDescriptionProvider temporarily?
(2) The instance another is created by the provider(where we added the attribute), I think now this variable is the same as the one created by the constructor of SerializableAttributed DataItem? even if we can't still get the attribute by another.GetType().GetCustomAttributes.
(3) Another reason I believe the change is temporarily stored in the provider is that I tried to create a property with its name Str and type string, which actually already exists in DataItem. The code will output hello. And if I uncomment the SetValue method, the output will be new one. Do I have any misunderstandings?
The attributes are added to the instance (data) not the type. Have you tried TypeDescriptor.AddAttributes(typeof(DataItem)) instead?
TypeDescriptor, being in System.ComponentModel, is a part of a large but isolated ecosystem of components and related technologies. The purpose of this class is to manipulate design-time (unlike reflection which is compile-time, or run-time DLR) members of a type or instance. This is the case when you create or edit a component in the Visual Studio designer, or in controls like PropertyGrid, where you might need to tweak or customize the properties for easier editing.
Similarly, TypeConverter can be used when setting property values in the designer.
While these classes are exteremely useful, it is only in situations where you are working with code that already uses and understands them, therefore...
This change is visible only to code that also uses TypeDescriptor to retrieve the attributes. In my experience, they are not used much in the runtime outside of System.ComponentModel and related namespaces, so specifically your SerializableAttribute example will not actually make the type serializable (it doesn't affect Type.IsSerializable). This may seem limited, but these classes are extremely useful once the whole system uses them (and it is a sort of standard way to extend arbitrary types).
The change is also permanent, unless you remove the attributes or the associated provider.
The instance is equivalent to the one created before. In addition, both instances have SerializableAttribute, since TypeDescriptor.AddAttributes has global effects.
The confusion is the result of the fact that TypeDescriptor.CreateProperty does not actually create a property, merely a property descriptor from an existing property. Accesing it through the descriptor will simply modify the real property of the object.
All in all, TypeDescriptor is used to describe a new system (components) using standard language (types, properties, events, attributes), but they are otherwise unrelated.