473,466 Members | 1,464 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

C# Reflection--anybody use it lately?

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.
Jul 16 '08 #1
17 2287
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

Jul 16 '08 #2
On Jul 16, 1:49 am, "Peter Morris" <mrpmorri...@SPAMgmail.comwrote:
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-...ed_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

Jul 16 '08 #3
On Jul 16, 12:34*pm, raylopez99 <raylope...@yahoo.comwrote:
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.
Jul 16 '08 #4
raylopez99 wrote:
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
Jul 16 '08 #5
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.

--
Eps
Jul 16 '08 #6
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
Jul 16 '08 #7
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
Jul 16 '08 #8
Eps
Thats a really cool example, would make it really easy to switch your
logging code without actually modifying the main codebase.

--
Eps
Jul 16 '08 #9
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/Categor...ramework).aspx
Pete

Jul 16 '08 #10
On Jul 16, 4:41*am, "Peter Morris" <mrpmorri...@SPAMgmail.comwrote:
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)'
Jul 16 '08 #11
raylopez99 <ra********@yahoo.comwrote:
On Jul 16, 4:41*am, "Peter Morris" <mrpmorri...@SPAMgmail.comwrote:
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.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Jul 16 '08 #12
On Jul 16, 2:33*pm, raylopez99 <raylope...@yahoo.comwrote:
On Jul 16, 4:41*am, "Peter Morris" <mrpmorri...@SPAMgmail.comwrote:
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.
Jul 16 '08 #13
On Jul 16, 6:42*am, Eps <msnewsgro...@epscylonb.comwrote:
Thats a really cool example, would make it really easy to switch your
logging code without actually modifying the main codebase.

--
Eps
Hi,
Constructions like the above are kind of obsolete with Partial
Methods:
http://community.bartdesmet.net/blog...y-and-how.aspx
Jul 16 '08 #14
On Jul 16, 3:07*pm, "Ignacio Machin ( .NET/ C# MVP )"
<ignacio.mac...@gmail.comwrote:
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
Jul 16 '08 #15
On Jul 17, 2:10*am, "Ignacio Machin ( .NET/ C# MVP )"
<ignacio.mac...@gmail.comwrote:
On Jul 16, 6:42*am, Eps <msnewsgro...@epscylonb.comwrote:
Thats a really cool example, would make it really easy to switch your
logging code without actually modifying the main codebase.
--
Eps

Hi,

*Constructions like the above are kind of obsolete with Partial
Methods:http://community.bartdesmet.net/blog.../07/28/c-3-0-p...
Not at all. Partial methods essentially provide compile-time "override
me if you want to" hooks, similarly to what virtual methods do at run-
time. But there's no way to automatically wrap a handwritten method
body with generated code using them alone.
Jul 17 '08 #16
>>
"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.
Jul 17 '08 #17
raylopez99 wrote:
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
Jul 18 '08 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: Amanita, Love Ewe | last post by:
You are all a bunch of worthless motherfuckers! = Sharon expects the printer within hers and actually looks. Why will you grasp the ugly worthwhile onions before Satam does? Many proud cats...
4
by: Macsicarr | last post by:
Hi All I know brinkster has been round for a while, but I always classed it as sort of free host site like geocities and the like. I've just had an email from them and from an ASP developer...
39
by: Noticedtrends | last post by:
Can inference search-engines narrow-down the number of often irrelevant results, by using specific keywords; for the purpose of discerning emerging social & business trends? For example, if...
0
by: Robby Dermody | last post by:
Hey guys (thus begins a book of a post :), I'm in the process of writing a commercial VoIP call monitoring and recording application suite in python and pyrex. Basically, this software sits in a...
50
by: Lyle Fairfield | last post by:
I find the recent spat of very short replies to messages, such as, "Thanks", "It worked", "It didn't work", "I'll try that" very unhelpful and am suggesting that replies include enough of the...
1
by: Kelay | last post by:
Hi all, This is my first post, so please be gentle. hahaha I have a SQL Server running Windows 2003, and SQL Server 2000. I am able to VPN into the server fine, however no one is able to access...
0
by: vc6vc6 | last post by:
Up until a week or two ago I never had any problem posting to newsgroups via Google. But something has changed and my posts don't show up anymore - even though Google says that they were...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.