C# Reflection--anybody use it lately?

R

raylopez99

What good is C# Reflection, other than to find out what types are in
an assembly? And to dynamically invoke methods in an assembly (.dll
or .exe)?

Also, bonus question, can you use Reflection to build a compiler? One
that will construct a user defined class "on the fly" (literally, the
user defines a class, instantiates it, and runs it from the console
mode, all the while prompted by the program)?

I guess so, but my final question is whether anybody has used
Reflection. Seems that some people use reflection to dynamically
invoke methods in an assembly (.dll or .exe), which might be useful
for using old non-C# unmanaged code.

RL

The Reflection API allows a C# program to inspect and manipulate
itself. It can be used to effectively find all the types in an
assembly and/or dynamically invoke methods in an assembly. It can at
times even be used to emit Intermediate Language code on the fly so
that the generated code can be executed directly.
 
P

Peter Morris

Google for PostSharp, then you will see that reflection isn't all about
creating instances and invoking methods. Additionally I used an object
persistence framework which describes the UML model using .NET attributes
(www.capableobjects.com) so I find reflection very useful there too.

As for creating classes you want to use AssemblyBuilder etc.



Pete
 
R

raylopez99

Google for PostSharp, then you will see that reflection isn't all about
creating instances and invoking methods. Additionally I used an object
persistence framework which describes the UML model using .NET attributes
(www.capableobjects.com) so I find reflection very useful there too.

As for creating classes you want to use AssemblyBuilder etc.

Pete

Thanks "Pete Morris". I checked out the page on AOP in
http://en.wikipedia.org/wiki/Aspect-oriented_programming, and it seems
like gobblygook. A specific example would have helped, but it seems
that the concern is over security. For example, somebody who
maliciously hacks into a system should be stopped from doing other bad
stuff if the programs written therein are written in AOP, which uses
reflection a lot to dynamically examine, akin to packet sniffing, all
translation units, classes, blocks of code etc being run in real
time. The hacker can then be stopped because he might not have the
right permission (i.e., thread permission) to do anything bad after
successfully logging into a network.

In short, much ado about nothing. I'll cross it off my list of things
to study.

RL
 
P

Pavel Minaev

What good is C# Reflection, other than to find out what types are in
an assembly?  And to dynamically invoke methods in an assembly (.dll
or .exe)?

You don't dynamically invoke methods in an assembly, you dynamically
invoke methods of a class (or, more often, of an object).

And yes, this is useful. A few things in the standard library that use
it are data binding (all of it - WinForms, ASP.NET, WPF) and
serialization (both binary and XML). Third-party inversion of control
containers (such as Unity) also typically use it

On my own side, I once wrote code that displayed a tree of objects
(all of different types) in a TreeView via reflection - it read custom
attributes off properties to figure out which properties were supposed
to be displayed in a tree and how, and which properties could be used
to retrieve visible children of object.
Also, bonus question, can you use Reflection to build a compiler?  One
that will construct a user defined class "on the fly" (literally, the
user defines a class, instantiates it, and runs it from the console
mode, all the while prompted by the program)?

Yes. See System.Reflection.Emit.
I guess so, but my final question is whether anybody has used
Reflection. Seems that some people use reflection to dynamically
invoke methods in an assembly (.dll or .exe), which might be useful
for using old non-C# unmanaged code.

You cannot use reflection to invoke "methods" (you mean, functions) in
an unmanaged DLL.
 
P

Pete Kane

raylopez99 said:
What good is C# Reflection, other than to find out what types are in
an assembly? And to dynamically invoke methods in an assembly (.dll
or .exe)?

Also, bonus question, can you use Reflection to build a compiler? One
that will construct a user defined class "on the fly" (literally, the
user defines a class, instantiates it, and runs it from the console
mode, all the while prompted by the program)?

I guess so, but my final question is whether anybody has used
Reflection. Seems that some people use reflection to dynamically
invoke methods in an assembly (.dll or .exe), which might be useful
for using old non-C# unmanaged code.

RL

The Reflection API allows a C# program to inspect and manipulate
itself. It can be used to effectively find all the types in an
assembly and/or dynamically invoke methods in an assembly. It can at
times even be used to emit Intermediate Language code on the fly so
that the generated code can be executed directly.
Hi there, I use Reflection to dynamically add TabPages to a TabControl -
I scan a known directory for Dll's , check whether a class implements a
known Interface, and, if it does, load it using Reflection - very useful
in my book

regards
 
E

Eps

I have seen reflection used to good effect in a database access layer
(think nhibernate and you will be close). It was actually used to save
different objects (each representing a table with the properties mapping
to the fields). It was very cool cos it handled saving pretty much any
object without any hassles in one code file.

Its worth saying that if you were to approach the same problem today you
are probably better off using a different approach, LINQ springs to mind.
 
P

pieter

Hi,

Have you ever used the serialisation (http://msdn.microsoft.com/en-us/
library/90c86ass.aspx) in .NET? Do you use IoC or dependency injection
(http://www.hanselman.com/blog/
ListOfNETDependencyInjectionContainersIOC.aspx)? Do you use an ORM
tool like NHibernate (http://www.hibernate.org/343.html)?

All of these tools / frameworks use Reflection extensively to achieve
the required functionality. "What good is C# Reflection, other than to
find out what types are in
an assembly? And to dynamically invoke methods in an assembly (.dll
or .exe)?". In essence that is what Reflection is built for, the
question is how you use the "basic" operations to build "useful"
functionality.

I must agree the Wikipedia article is long and goes on a bit, but as
far as I understand AOP (which uses Reflection) is to implement cross
cutting concern across the whole system. A simple (contrived) example
would be logging functionality. You could write code to do logging at
the beginning and end of each method. Using AOP you could "inject"
this code into your methods. The AOP configuration can then be removed
or changed from outside your application without changing the core
method code. A more practical example that I have seen, is the use of
AOP (using Interceptors in NHibernate) to ensure an object can be
saved to the database by the current user. The interceptor would be
called dynamically and executed before NHibernate will save the object
to the database. The interceptor would then check the state of the
object and ensure the current user has the appropriate authorisation
to save the object to the database. If the user does not have the
appropriate authorisation the interceptor will stop NHibernate to save
the object to the database. This functionality is achieved using
Reflection.

With regards to the bonus question. I guess you could write a compiler
(or part of it) using Reflection using the Emit method (http://
msdn.microsoft.com/en-us/library/3y322t50.aspx, http://www.ddj.com/windows/184416570).
You might want to have a look at the boo compiler as how that works
(http://boo.codehaus.org/)

pieter
 
P

Peter Morris

Example...

public class SomeClass
{
[Log]
public void DoSomething()
{
...
}

[Log]
public void DoSomethingElse()
{
...
}

public void DoSomethingElseButDontLog()
{
...
}
}

In this example when you compile your project PostSharp will use a
post-compile hook in the IDE to reflect over the classes/members etc. It
sees the [Log] attribute which you yourself have written and changes the
code from this

{
...
}

to this

{
System.Diagnostics.Debug.WriteLine("Entering method DoSomething");
try
{
...
}
finally
{
System.Diagnostics.Debug.WriteLine("Leaving method DoSomething");
}
}


You can write what code you like in your PostSharp attribute ("Log" in this
case), the attribute may then be applied to assemblies, classes, or
individual members. This is one good example of how .NET attributes are
used in combination with Reflection (post-compile) to alter the code you
have written. This AOP approach only uses reflection during compile time
and not runtime, additionally I will say that if you think AOP is only
related to security then either that URL is no good or you misunderstood it.

In short, much ado about nothing. I'll cross it off my list of things
to study.

Tut tut. With this kind of attitude towards learning there's no wonder why
you don't understand the benefits of such a simple thing such as Reflection.



Pete
 
E

Eps

Thats a really cool example, would make it really easy to switch your
logging code without actually modifying the main codebase.
 
P

Peter Morris

Another good example I saw went something like

[BusinessObject("Person")]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}


The BusinessObjectAttribute implements INotifyPropertyChanged + executes
after FirstName and LastName are modified, it also implements
IEditableObject allowing you to cancel changes, and finally it implemented
all of the code required to work with the Entity Framework. However, the
author had also written a disconnected client so had the same attribute
implement old/new values etc when compiled for the client application.

All looked pretty interesting. Take a look at his blog here:

http://www.sitechno.com/Blog/CategoryView,category,EF+(Entity+Framework).aspx


Pete
 
R

raylopez99

Another good example I saw went something like

OK, so reflection is like attributes [Serialization] etc that
tell .NET to use the Serialization class. Fine. That's nice, sort of
like a glorified macro or message map from days of old.

The rest of reflection seems just code designed to be too clever by
half. Why depend on the compiler / optimizer/ interpreter do write try/
catch blocks? Just do it yourself up front.

And the blog by the programming guru you referenced confirms
reflection is slow and not optimal, see quotes below. The guru works
around reflection, so why should I bother learning it?

"Thanks" but I think I'll pass. In the case of reflection, what you
don't know about it can't hurt you.

RL

There is a strong optimization for speed. I, for instance, generate a
method 'SetValue(string propname, object val)' and corresponding
GetValue so that the framework does not need to use reflection or
dynamic method generation.

I also had to somehow get hold of a list of properties in your type
that are complexTypes (in this case Address). When the system injects
your entitytype with a changetracker, it should notify all complex
types. I could have done that with reflection, but we all know that's
really slow. So I actually generate a method in your entity:
'UpdateComplexTypes(tracker)'
 
J

Jon Skeet [C# MVP]

raylopez99 said:
Another good example I saw went something like

OK, so reflection is like attributes [Serialization] etc that
tell .NET to use the Serialization class. Fine. That's nice, sort of
like a glorified macro or message map from days of old.

No, that's just one potential use of reflection, in one very specific
scenario.
The rest of reflection seems just code designed to be too clever by
half. Why depend on the compiler / optimizer/ interpreter do write try/
catch blocks? Just do it yourself up front.

The point (and this is AOP, not reflection per se) is that writing

[Log]

is less error-prone than having to write the logging code in each
method. It also means that when the details of that logging code
change, you only need to change it in the aspect, not everywhere the
aspect is applied.
And the blog by the programming guru you referenced confirms
reflection is slow and not optimal, see quotes below. The guru works
around reflection, so why should I bother learning it?

Yes, reflection is often slower than the alternatives, when there are
any. On the other hand, often reflection opens up possibilities which
are otherwise too cumbersome - or even impossible - to achieve.
"Thanks" but I think I'll pass. In the case of reflection, what you
don't know about it can't hurt you.

Why bother learning *anything* then? Seriously, sticking your head in
the sand and just ignoring the benefits of reflection isn't a good
long-term strategy.
 
I

Ignacio Machin ( .NET/ C# MVP )

Another good example I saw went something like

OK, so reflection is like attributes [Serialization] etc that
tell .NET to use the Serialization class.  Fine.  That's nice, sort of
like a glorified macro or message map from days of old.

not really, attributes only add with info that you can later query.
I fail to see a similarity with macros though.
The rest of reflection seems just code designed to be too clever by
half. Why depend on the compiler / optimizer/ interpreter do write try/
catch blocks?  Just do it yourself up front.

again, you fail to see the "big picture"
And the blog by the programming guru you referenced confirms
reflection is slow and not optimal, see quotes below.  The guru works
around reflection, so why should I bother learning it?

it's slower , it does not mean it's useless.
"Thanks" but I think I'll pass.  In the case of reflection, what you
don't know about it can't hurt you.

I have another suggestion for you, Threading is VERY complex, you have
to worry about too many things, so do not learn or use it.
 
R

raylopez99

OK, so reflection is like attributes [Serialization] etc that
tell .NET to use the Serialization class.  Fine.  That's nice, sortof
like a glorified macro or message map from days of old.

not really, attributes only add with info that you can later query.
I fail to see a similarity with macros though.

Yes, I probably mean reflection is like "conditional statements" used
during compile, but instead you do this at run time.

Anyway, I've got my plate full, and too much to study right now
anyway. Like your 'partial classes' example, it's a receipe for name
collision it seems to me.

RL
 
P

Peter Morris

"Thanks" but I think I'll pass. In the case of reflection, what you
don't know about it can't hurt you.
<<

I am sure many micro-biologists would disagree.
 
A

Arne Vajhøj

raylopez99 said:
I guess so, but my final question is whether anybody has used
Reflection. Seems that some people use reflection to dynamically
invoke methods in an assembly (.dll or .exe), which might be useful
for using old non-C# unmanaged code.

You use reflection to access managed code no unmanaged.

The ability to use reflection for this is critical
for plugins, DI and encapsulation in general.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top