My answer to one of the question on SO was commented by Valentin Kuzub, who argues that inlining a property by JIT compiler will cause the reflection to stop working.
The case is as follows:
class Foo
{
public string Bar { get; set; }
public void Fuzz<T>(Expression<Func<T>> lambda)
{
}
}
Fuzz(x => x.Bar);
Fuzz function accepts a lambda expression and uses reflection to find the property. It is a common practice in MVC in HtmlHelper extensions.
I don't think that the reflection will stop working even if the Bar property gets inlined, as it is a call to Bar that will be inlined and typeof(Foo).GetProperty("Bar") will still return a valid PropertyInfo.
Could you confirm this please or my understanding of method inlining is wrong?
JIT compiler operates at runtime and it can't rewrite metadata information stored in the assembly. And reflection reads assembly to access this metadata. So there are no impact from JIT-compiler to reflection.
EDIT:
Actually there are couple of places when C# compiler itself "inlines" some information during compilation. For example, constants, enums and default arguments are "inlined" so you can't access them during reflection. But it definitely not related to your particular case.
Yeah when I think about it more I guess only way inlining properties could fail INotifyPropertyChanged interface correct work would be if you were using a reflection based method used like
public Count
{
get {return m_Count;}
set { m_Count=value;
GetCurrentPropertyNameUsingReflectionAndNotifyItChanged();}
}
If used like you suggest indeed metadata exists in assembly and property name will be successfully taken from there.
Got us both thinking though.
I personally agree with #Sergey:
Considering that inlining happens on JIT compiler side, but metadata generated before, it shouldn't inpact on reflection in any way. By the way, good question, like it +1
Expression trees can't be in-lined anyway since they are a representation of the expression (abstract syntax tree) rather than the expression itself.
Delegates, even if they can be in-lined, will still carry the data about the method and target being called in their properties.
Related
class my_class
{
public int add_1(int a, int b) {return a + b;}
public func<int, int, int> add_2 = (a, b) => {return a + b;}
}
add_1 is a function whereas add_2 is a delegate. However in this context delegates can forfill a similar role.
Due to precedent and the design of the language the default choice for C# methods should be functions.
However both approaches have pros and cons so I've produced a list. Are there any more advanteges or disadvantages to either approach?
Advantages to conventional methods.
more conventional
outside users of the function see named parameters - for the add_2 syntax arg_n and a type is generally not enough information.
works better with intellisense - ty Minitech
works with reflection - ty Minitech
works with inheritance - ty Eric Lippert
has a "this" - ty CodeInChaos
lower overheads, speed and memory - ty Minitech and CodeInChaos
don't need to think about public\private in respect to both changing and using the function. - ty CodeInChaos
less dynamic, less is permitted that is not known at compile time - ty CodeInChaos
Advantages to "field of delegate type" methods.
more consistant, not member functions and data members, it's just all just data members.
can outwardly look and behave like a variable.
storing it in a container works well.
multiple classes could use the same function as if it were each ones member function, this would be very generic, concise and have good code reuse.
straightforward to use anywhere, for example as a local function.
presumably works well when passed around with garbage collection.
more dynamic, less must be known at compile time, for example there could be functions that configure the behaviour of objects at run time.
as if encapsulating it's code, can be combined and reworked, msdn.microsoft.com/en-us/library/ms173175%28v=vs.80%29.aspx
outside users of the function see unnamed parameters - sometimes this is helpfull although it would be nice to be able to name them.
can be more compact, in this simple example for example the return could be removed, if there were one parameter the brackets could also be removed.
roll you'r own behaviours like inheritance - ty Eric Lippert
other considerations such as functional, modular, distributed, (code writing, testing or reasoning about code) etc...
Please don't vote to close, thats happened already and it got reopened. It's a valid question even if either you don't think the delegates approach has much practical use given how it conflicts with established coding style or you don't like the advanteges of delegates.
First off, the "high order bit" for me with regards to this design decision would be that I would never do this sort of thing with a public field/method. At the very least I would use a property, and probably not even that.
For private fields, I use this pattern fairly frequently, usually like this:
class C
{
private Func<int, int> ActualFunction = (int y)=>{ ... };
private Func<int, int> Function = ActualFunction.Memoize();
and now I can very easily test the performance characteristics of different memoization strategies without having to change the text of ActualFunction at all.
Another advantage of the "methods are fields of delegate type" strategy is that you can implement code sharing techniques that are different than the ones we've "baked in" to the language. A protected field of delegate type is essentially a virtual method, but more flexible. Derived classes can replace it with whatever they want, and you have emulated a regular virtual method. But you could build custom inheritence mechanisms; if you really like prototype inheritance, for example, you could have a convention that if the field is null, then a method on some prototypical instance is called instead, and so on.
A major disadvantage of the methods-are-fields-of-delegate-type approach is that of course, overloading no longer works. Fields must be unique in name; methods merely must be unique in signature. Also, you don't get generic fields the way that we get generic methods, so method type inference stops working.
The second one, in my opinion, offers absolutely no advantage over the first one. It's much less readable, is probably less efficient (given that Invoke has to be implied) and isn't more concise at all. What's more, if you ever use reflection it won't show up as being a method so if you do that to replace your methods in every class, you might break something that seems like it should work. In Visual Studio, the IntelliSense won't include a description of the method since you can't put XML comments on delegates (at least, not in the same way you would put them on normal methods) and you don't know what they point to anyway, unless it's readonly (but what if the constructor changed it?) and it will show up as a field, not a method, which is confusing.
The only time you should really use lambdas is in methods where closures are required, or when it's offers a significant convenience advantage. Otherwise, you're just decreasing readability (basically the readability of my first paragraph versus the current one) and breaking compatibility with previous versions of C#.
Why you should avoid delegates as methods by default, and what are alternatives:
Learning curve
Using delegates this way will surprise a lot of people. Not everyone can wrap their head around delegates, or why you'd want to swap out functions. There seems to be a learning curve. Once you get past it, delegates seem simple.
Perf and reliability
There's a performance loss to invoking delegates in this manner. This is another reason I would default to traditional method declaration unless it enabled something special in my pattern.
There's also an execution safety issue. Public fields are nullable. If you're passed an instance of a class with a public field you'll have to check that it isn't null before using it. This hurts perf and is kind of lame.
You can work around this by changing all public fields to properties (which is a rule in all .Net coding standards anyhow). Then in the setter throw an ArgumentNullException if someone tries to assign null.
Program design
Even if you can deal with all of this, allowing methods to be mutable at all goes against a lot of the design for static OO and functional programming languages.
In static OO types are always static, and dynamic behavior is enabled through polymorphism. You can know the exact behavior of a type based on its run time type. This is very helpful in debugging an existing program. Allowing your types to be modified at run time harms this.
In both static OO and function programming paradigms, limiting and isolating side-effects is quite helpful, and using fully immutable structures is one of the primary ways to do this. The only point of exposing methods as delegates is to create mutable structures, which has the exact opposite effect.
Alternatives
If you really wanted to go so far as to always use delegates to replace methods, you should be using a language like IronPython or something else built on top of the DLR. Those languages will be tooled and tuned for the paradigm you're trying to implement. Users and maintainers of your code won't be surprised.
That being said, there are uses that justify using delegates as a substitute for methods. You shouldn't consider this option unless you have a compelling reason to do so that overrides these performance, confusion, reliability, and design issues. You should only do so if you're getting something in return.
Uses
For private members, Eric Lippert's answer describes a good use: (Memoization).
You can use it to implement a Strategy Pattern in a function-based manner rather than requiring a class hierarchy. Again, I'd use private members for this...
...Example code:
public class Context
{
private Func<int, int, int> executeStrategy;
public Context(Func<int, int, int> executeStrategy) {
this.executeStrategy = executeStrategy;
}
public int ExecuteStrategy(int a, int b) {
return executeStrategy(a, b);
}
}
I have found a particular case where I think public delegate properties are warrented: To implement a Template Method Pattern with instances instead of derived classes...
...This is particularly useful in automated integration tests where you have a lot of setup/tear down. In such cases it often makes sense to keep state in a class designed to encapsulate the pattern rather than rely on the unit test fixture. This way you can easily support sharing the skeleton of the test suite between fixtures, without relying on (sometimes shoddy) test fixture inheritance. It also might be more amenable to parallelization, depending on the implementation of your tests.
var test = new MyFancyUITest
{
// I usually name these things in a more test specific manner...
Setup = () => { /* ... */ },
TearDown = () => { /* ... */ },
};
test.Execute();
Intellisense Support
outside users of the function see unnamed parameters - sometimes this is helpfull although it would be nice to be able to name them.
Use a named delegate - I believe this will get you at least some Intellisense for the parameters (probably just the names, less likely XML docs - please correct me if I'm wrong):
public class MyClass
{
public delegate int DoSomethingImpl(int foo, int bizBar);
public DoSomethingImpl DoSomething = (x, y) => { return x + y; }
}
I'd avoid delegate properties/fields as method replacements for public methods. For private methods it's a tool, but not one I use very often.
instance delegate fields have a per instance memory cost. Probably a premature optimization for most classes, but still something to keep in mind.
Your code uses a public mutable field, which can be changed at any time. That hurts encapsulation.
If you use the field initializer syntax, you can't access this. So field initializer syntax is mainly useful for static methods.
Makes static analysis much harder, since the implementation of that method isn't known at compile-time.
There are some cases where delegate properties/fields might be useful:
Handlers of some sort. Especially if multi-casting (and thus the event subscription pattern) doesn't make much sense
Assigning something that can't be easily described by a simple method body. Such as a memoized function.
The delegate is runtime generated or at least its value is only decided at runtime
Using a closure over local variables is an alternative to using a method and private fields. I strongly dislike classes with lots of fields, especially if some of these fields are only used by two methods or less. In these situations, using a delegate in a field can be preferable to conventional methods
class MyClassConventional {
int? someValue; // When Mark() is called, remember the value so that we can do something with it in Process(). Not used in any other method.
int X;
void Mark() {
someValue = X;
}
void Process() {
// Do something with someValue.Value
}
}
class MyClassClosure {
int X;
Action Process = null;
void Mark() {
int someValue = X;
Process = () => { // Do something with someValue };
}
}
This question presents a false dichotomy - between functions, and a delegate with an equivalent signature. The main difference is that one of the two you should only use if there are no other choices. Use this in your day to day work, and it will be thrown out of any code review.
The benefits that have been mentioned are far outweighed by the fact that there is almost never a reason to write code that is so obscure; especially when this code makes it look like you don't know how to program C#.
I urge anyone reading this to ignore any of the benefits which have been stated, since they are all overwhelmed by the fact that this is the kind of code that demonstrates that you do not know how to program in C#.
The only exception to that rule is if you have a need for one of the benefits, and that need can't be satisfied in any other way. In that case, you'll need to write more comment than code to explain why you have a good reason to do it. Be prepared to answer as clearly as Eric Lippert did. You'd better be able to explain as well as Eric does that you can't accomplish your requirements and write understandable code at the same time.
I've made this mistake a number of times - it happens when I'm working quickly and using code completion. I end up with code like the following:
public class Model : IModel
{
public PropertyNames PropertyNames { get; set; }
public Model(PropertyNames propertyNames)
{
PropertyNames = PropertyNames;
}
}
Then a test fails in a slightly less than obvious way, and I get bummed out.
I'm just curious if there's a valid reason to write code like that, ever, and if not, then does it make for a good candidate to generate a warning?
I'm just curious if there's a valid reason to write code like that, ever
Depending on how you look at, unfortunately yes there is. Because the identifier we are talking about is a property, assigning a property to a property sounds like a no-op but it actually invokes methods, the getter and the setter, and those methods might have side effects.
A specific case that is very common is if the setter does something like property notification or calls an observer but anything could happen when you call either the getter or the setter. This is why the code does not generate a warning: because this coding style is actually useful and used in production code.
Edit:
By comparison, if the identifier is a field and not a property, it does generate this warning:
warning CS1717: Assignment made to same variable; did you mean to assign something else?
Use FxCop (aka Code Analysis), it will give you the warning:
Warning 3 CA1801 : Microsoft.Usage : Parameter 'propertyNames' of 'Model.Model(string)' is never used. Remove the parameter or use it in the method body.
Other than "it counts as a valid instruction", there's no reason to ever use this. That said, it's also not wrong: it conforms the syntax for assignment.
If you are writing a code validator, then this is a good candidate for a warning, although of course it should never hamper actual compiling; most compilers already catch this kind of operation during bytecode optimisation, where instructions that do not perform any control logic and don't actually modify registers are removed.
This question already has answers here:
Why is there not a `fieldof` or `methodof` operator in C#? [closed]
(4 answers)
Closed 9 years ago.
There is sizeof() and typeof(), but why not a memberinfo() returning an instance of System.Reflection.MemberInfo for the part of code selected in order to aid in reflection code.
Example:
Program()
{
Type t = typeof(Foo);
Foo foo = new Foo();
PropertyInfo pi = memberinfo(Foo.Name) as PropertyInfo;
// or shall it be like this
// PropertyInfo pi = memberinfo(foo.Name) as PropertyInfo;
string name = pi.GetValue(foo, null);
}
I am trying to understand if there is a fundamental reason why this could be implemented in the C# spec.
I am not bashing anything, I am just doing some wishful thinking, so be kind please.
Eric Lippert talks about this extensively on his blog
To quote directly from that post:
Just off the top of my head, here are a few {reasons why this hasn't been done}. (1) How do you unambiguously specify that you want a method info of an specific explicit interface implementation? (2) What if overload resolution would have skipped a particular method because it is not accessible? It is legal to get method infos of methods that are not accessible; metadata is always public even if it describes private details. Should we make it impossible to get private metadata, making the feature weak, or should we make it possible, and make infoof use a subtly different overload resolution algorithm than the rest of C#? (3) How do you specify that you want the info of, say, an indexer setter, or a property getter, or an event handler adder?
There are a couple of items which make this type of feature difficult. One of the primary ones being overloaded methods.
class Example {
public void Method() {}
public void Method(int p1) {}
}
Which MethodInfo would the following return?
var info = memberinfo(Example.Method);
As Wesley has pointed out though, Eric Lippert's Blog has the full discussion on this issue.
There are numerous reasons why compile-time member reflection has not yet been implemented in C# - but most of them basically boil down to opportunity cost - there are many other languages features and enhancements that offer more benefit to more users. There's also the consideration that an infoof syntax could be complicated, confusing, and ultimately less powerful than using string-based reflection. It also wouldn't be a complete replacement for reflection since in many instances the metadata being manipulated isn't known at compile time.
However, all is not lost, there are a number of tricks that you can employ to perform slightly safer reflection that leverages capabilities of the C# language. For instance, we can take advantage of lambda expressions and expression trees to extract MemberInfo information. A simple example is:
public static class MethodExt {
static MethodInfo MemberInfo(Action d) {
return d.Method;
}
// other overloads ...
}
which works when you pass in a (non-anonymous) action delegate:
MethodInfo mi = MethodExt.MemberInfo( Object.ToString );
An implementation of the above using expression trees can more robust and flexible, but also substantially more complicated. It could be used to represent member and property access, indexers, etc.
The main issue with all such "fancy" approaches, is that they are confusing to developers who are used to seeing traditional reflection code. They also can't handle all cases, which often results in an unfortunate mixture of traditional reflection code and fancy expression tree code. Personally, while such techniques are interesting and inventive, it's probably best to avoid it in production code.
I myself use an approach that reads the IL from an anonymous method (using Mono.Reflection namespace) and grabs the info of the last token found in the anonymous method. This tends to be the only way to get information about things like the add_EventHandler or set_Property or captured local variables. To actual get properties I use expression trees.
The syntax that I use is Reflect.Member<T>.InfoOf<TMember>(Func<T,TMember> memberfunc) where Member is replaced with the type I'm interested in. It's verbose sure, but it lets a user know exactly what the code is trying to do. I also have Reflect.Member styles for things like statics and constructors.
Here is the relevant code snippet::
internal static MemberInfo GetLastMemberOfType(MethodBase method, MemberTypes memberType)
{
var instructions = method.GetInstructions();
var operandtype = memberType == MemberTypes.Field ? OperandType.InlineField : OperandType.InlineMethod;
for (int i = instructions.Count-1; i > -1 ; i--)
{
if (instructions[i].OpCode.OperandType == operandtype)
{
return instructions[i].Operand as MemberInfo;
}
}
return null;
}
Does it replace string based reflection? Absolutely not. Does it make my code safer while I'm refactoring interfaces and what not? Absolutely.
Will it ship with the product I'm working on? Probably not.
Say, for example, I've got this simple class:
public class MyClass
{
public String MyProperty { get; set; }
}
The way to get the PropertyInfo for MyProperty would be:
typeof(MyClass).GetProperty("MyProperty");
This sucks!
Why? Easy: it will break as soon as I change the Name of the Property, it needs a lot of dedicated tests to find every location where a property is used like this, refactoring and usage trees are unable to find these kinds of access.
Ain't there any way to properly access a property? Something, that is validated on compile time?
I'd love a command like this:
propertyof(MyClass.MyProperty);
The closest you can come at the moment is to use an expression tree:
GetProperty<MyClass>(x => x.MyProperty)
and then suck the PropertyInfo out in GetProperty (which you'd have to write). However, that's somewhat brittle - there's no compile-time guarantee that the expression tree is only a property access.
Another alternative is to keep the property names that you're using somewhere that can be unit tested easily, and rely on that.
Basically what you want is the mythical infoof operator which has been talked about many times by the C# team - but which hasn't made the cut thus far :(
In the time since this question was posted, C# 6 has been released with the nameof operator. This allows a property to be accessed with the following
PropertyInfo myPropertyInfo = typeof(MyClass).GetProperty(nameof(MyClass.MyProperty));
If you rename the property, this code will not compile (actually it will, since the rename will change this line of code as well if the rename is done properly).
The whole point of reflection is to be able to access stuff at runtime. If we assume your operator would work, you already have the class information and thus the property, making the whole thing completely useless.
I use Stylecop for Resharper and whenever I call something in my class, Stylecop tells me to use the this keyword. But the IDE says this is redundant code (which it sure is), so why should I use the this keyword?
Does redundant code mean its not needed (obviously) and the compiler won't even do anything with the this keyword? So I assume the this keyword is just for clarity.
Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET? I assume it is all for clarity as stylecop keeps an eye on this and Fxcop (which I will use later on) keeps an eye on my code's quality from a technical point of view.
Thanks
It's for clarity and to prevent any ambiguity between a class member and a local variable or parameter with the same name.
The IL it compiles to will not be any different.
Most of the time is just for clarity but some times it is required.
using System;
class Foo
{
String bar;
public Foo(String bar)
{
this.bar = bar;
}
}
Here you will need this as it serves to disambiguate between the field bar and the constructor parameter bar. Obviously changing the name of the parameter or field could accomplish the same thing.
In all cases, there is no performance difference with/without the this - the compiler still does it implicitly, injecting a ldarg.0 into the IL.
Just for completeness, there is one other mandatory use of this (excluding disambiguation, ctor-chaining, and passing this to other methods): extension methods. To call an extension method on the current instance, you must qualify with this (even though for a regular method it would be implicit).
Of course, in most cases, you would simply add a regular instance method to the class or a base-class...
class Foo {
void Test() {
this.Bar(); // fine
Bar(); // compiler error
}
}
static class FooExt {
public static void Bar(this Foo foo) { }
}
In C# this is a reference to the current instance of the class (it's me in VB.NET). It's used generally to fully qualify a class member. For example, consider this C# class:
public class MyClass
{
int rate;
private void testMethod()
{
int x;
x = this.rate;
}
}
this isn't required in the code above, but adds instant clarity when reading the code that rate belongs to the class rather than the method (search SO, you'll find lots of opinions about the use of this). It's semantic behavior is the same in VB--and its use doesn't impose a performance penalty.
Apart from the clarity examples provided the only other valid usage of the "this" keyword is to pass the current instance of an object as a paremeter.
It is just for clarity, and one can argue about what is better. Python doesn't support omitting the "self" identifier at all.
Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET?
In JVM for sure (and also for CLR, I'm almost sure) the code for the "this" keyword is always generated, even if that is omitted from the source - so it's like if the this keyword is always added. So, I don't think that any .NET compiler could generate different output, so there can't be a performance penalty.
Then, it depends on the language. For instance JScript (and even JScript.NET) does not allow to omit "this", like Python, because there are functions (so "this.a()" is a method invocation, "a()" is a function invocation), and because the compiler does not know the members of any types - they're only known at runtime (well, this is not an impossible problem to solve indeed, the other issue is more relevant).