I'm using reflection on the assembly of a public API I am working with along with System.CodeDOM to generate some code that will extract information through the API.
In part of my auto-generated code I am referencing the values of a number of properties of types in the API assembly. However, I keep ending up with references to properties that don't actualy exist in my generated code. I used Type.GetProperties() which from what I understand should only return public properties.
I looked into it further and found that when I had a missing property, say called SampleProperty there were instead two methods in the class called get_SampleProperty and set_SampleProperty but no actual SampleProperty property.
What's going on here? Why does intellisense treat these methods as separate methods, but when when returned through reflection they show up as a property?
I used PropertyInfo.GetProperties() which from what I understand should only return public properties.
That might be your first hang-up, the PropertyInfo class doesn't have a GetProperties method. The Type class does. Your question otherwise indicates that you are actually using Type.GetMethods(). Yes, that returns the get_Blah and set_Blah property accessor methods for a property. Under the hood, properties are actually implemented as methods.
Use Type.GetProperties() to reflect properties.
Related
I'm reflecting over an Assembly and there are some types which have been generated by yield return, is there a reliable way to filter them out?
There's no default constructor for the Type generated by yield return. It is a class and not a value type. How to make an instance of this class?
The generated type-name looks like this:
SomeNamespace.RootMode+<GetMouseArrow>d__1, where RootMode is the class name and GetMouseArrow is the function which has yield-return in it.
Use case: Serialization of complete state of a running application, including the state of yield-return statements
UPDATE:
Types generated by the yield return have a single public constructor which takes int as parameter. This is the state variable used to determine where in the function the IEnumerator is.
The generated classes are private and sealed, they implement a set of IEnumerator*/IEnumerable* interfaces.
The generated class has [CompilerGenerated] attribute set to it.
The [CompilerGenerated] is most likely what you want. It's used not just for "iterator methods" (the name of the feature you're describing), but if you're looking to filter out types, you probably want to filter out all compiler-generated types (which would also include types generated for anonymous methods, and for async methods).
As far as instantiating an instance of such a class, you can use reflection, but of course you'll have to identify the parameter to pass and use the appropriate constructor overload. Without the default constructor, the usual serialization techniques won't work; you'll have to implement something yourself to handle this explicitly. I.e. get the appropriate value from within the class instance when serializing, and then pass it to the constructor…of course, to fully restore the state of the class, you'll need to serialize all the private fields and restore those again on deserialization, all via reflection.
I hope the value of implementing this is very high to you, because the cost sure will be. :)
In FluentAssertions, you can make various claims in various formats.
x.Should().BeEquivalentTo(y);
x.ShouldBeEquivalentTo(y);
are both valid assertions.
Why is Should a method and not a property? I haven't seen any examples in which Should takes a parameter, so it seems to me like it could have easily been a property.
You can also assert that
x.Should().NotBeNull().And.BeEquivalentTo(y);
Here, And is a property instead of a method. Shouldn't And and Should each be the same type of element (methods/properties)?
TL;DR
Was there a valid reason behind the design choice to make Should a method in FluentAssertions instead of a property?
Should() is an extension method being added onto the class of x. You can only add extension methods -- C# doesn't have extension properties.
And is a property on whatever class NotBeNull() returns. There we have control over the class, and can add real properties to it.
Should() is a method because of the limitations of the C# language. It's an extension method; a method that is defined in the FluentAssertions library to be available to call on any type (hence x.Should()) - even though the original code for the class doesn't implement the method.
You can't implement extension properties, so Should has to be a method.
That method returns an object defined within FluentAssertions, as does NotBeNull(), and so these objects can include properties where it's relevant/useful/meaningful to do so.
In short: the valid reason is that it's the only choice available.
Is there a way for an attribute that has been applied to a method to know what method it was applied to at run time?
[AttributeUsage(AttributeTargets.Method)]
public class CustomAttribute : Attribute {}
public class Foo
{
[Custom]
public void Method() {}
}
Then I query the attribute at run time
var attribute = typeof(Foo)
.GetMethod("Method")
.GetCustomAttributes(false)
.OfType<CustomAttribute>()
.First();
Can "attribute" tell it was applied to the "Method" method on the "Foo" class?
I believe not, but if it could it would not be helpful.
I'll explain.
Attributes are only created once you query for them. If you just open a dll, none of the attributes that you added will be created. You will first have to get a pointer to the object that the attributes apply to, and then, once you ask for it's attributes, the .net framework will create them for you. So by the time they are instantiated and your code gets to evaluate them you already know what they apply to.
Because of this, I believe it is reccommended to not put too much magic in the attributes themselves.
Not in a built-in fashion. If an attribute contains method logic that requires knowledge of what it's decorating, the method should take a MemberInfo parameter (or a more derived type like MethodInfo, PropertyInfo, FieldInfo etc.), or an Object if the instance should be passed directly. Then, when invoking the logic on the attribute, it can be given the instance, or the appropriate metadata class, from which it was gotten by the controlling code in the first place.
I can use TypeDescriptor.AddAttributes to add an attribute to a type in runtime. How do I do the same for a method and parameter? (maybe 2 separate questions...)
TypeDescriptor.AddAttributes only affects a very specific use-case; i.e. from within System.ComponentModel. For the rest of reflection, it knows nothing about the extra attribute. And indeed, System.ComponentModel doesn't really apply to methods or parameters.
So in short; you can't. You will need to store this information somewhere else (bespoke), or add it at compile-time.
As I see from analyzing the TypeDescriptor class in Reflector, the .AddAttributes method internally calls the .AddProvider method. The TypeDescriptionProvider instance passed to it is actually responsible for providing meta-data. You could try adding the [TypeDescriptionProviderAttribute] attribute to your class and implement your own provider by deriving from the TypeDescriptionProvider class. As the documentation says, by overriding TypeDescriptionProvider.CreateInstance, you could provide a substitute object whose type has all necessary attributes. I suspect that the attributes applied to methods inside the substitution type will also take effect. However, I haven't tried that myself, so feel free to experiment...
Has anyone else seen people do this:
private string _name;
public string Name{ get{ return _name; } set{ _name = value;}}
I understand using accessors if you are going to exercise some sort of control over how it gets set or perform some sort of function on it when there is a get. But if you are just going to do this, why not just make the variable public to begin with? Am I missing something?
If you make the member a public field, then you can't later refactor it into a property without changing the interface to your class. If you expose it as a property from the very beginning, you can make whatever changes to the property accessor functions that you need and the class's interface remains unchanged.
Note that as of C# 3.0, you can implement a property without creating a backing field, e.g.:
public string Name { get; set; }
This removes what is pretty much the only justification for not implementing public fields as properties in the first place.
If you define a public interface with a property in assembly A, you could then use this interface in assembly B.
Now, you can change the property's implementation (maybe fetching the value from a database instead of storing it in a field). Then you can recompile assembly A, and replace an older one. Assembly B would carry on fine because the interface wouldn't have changed.
However, if you'd started off initially with a public field, and decided this wasn't suitable and wanted to change the implementation and to do that you needed to convert it to a property, then this would mean you'd have to change assembly A's public interface. Any clients of that interface (including assembly B) would also have to be recompiled and replaced to be able to work with this new interface.
So, you're better off starting with a property initially. This encapsulates the implementation of the property, leaving you free to change it in the future without having to worry what clients (including assembly B) are already out in the world using assembly A. Because, if there are any clients already out in the world making use of assembly A, changing the interface would break all clients. If they're used by another team in your company, or another company, then they are going to be not happy if you break their assemblies by changing the interface of yours!
The idea is that if you use accessors, the underlying implementation can be changed without changing the API. For example, if you decide that when you set the name, you also need to update a text box, or another variable, none of your client code would have to change.
It might be worth noting that DataBinding in .NET also refuses to work off public fields and demands properties. So that might be another reason.
Good programming practice. This is a very common pattern that fits with OO design methodologies. By exposing a public field you expose the internals of how that data is being stored. Using a public property instead allows you more flexibility to change the way the data is stored internally and not break the public interface. It also allows you more control over what happens when the data is accessed (lazy initialization, null checks, etc.)
Variables are part of the implementation of a class. Properties more logically represent the interface to it. With C# 3.0, automatically implemented properties make this a breeze to do from the start.
I've written more thoughts on this, including the various ways in which changing from a variable to a property breaks not just binary compatibility but also source compatibility, in an article on the topic.
Preparation. You never know when you'll want to removed the set accessor down the road, perform additional operations in the setter, or change the data source for the get.
Publicly accessible members should typically be methods and not fields. It's just good practice, and that practice helps you ensure that the encapsulated state of your objects is always under your control.
For encapsulation, it is not recommended to use public fields.
http://my.safaribooksonline.com/9780321578815/ch05lev1sec5?displaygrbooks=0
As Chris Anderson said later in this book, it would be ideal would be if the caller were blind to the difference of field vs. property.
To retain a high degree of extensibility without the pain of re-compiling all your assemblies, you want to use public properties as accessors. By following a "contract" or a defined mechanism that describes how your objects will exchange data a set of rules will be put in place. This contract is enforced with an interface and fulfilled by the getters and setters of your class that inherits this interface.
Later on, should you create additional classes from that interface, you have flexibility of adhering to the contract with the use of the properties, but since you are providing the data via the getters and setters, the implementation or process of assembling data can anything you want, as along as it returns the type that the "contract" expects.