C# Reflection

bchip

Expert Member
Joined
Mar 12, 2013
Messages
1,324
Reaction score
418
Hi
I'm trying to list all the sub-classes automatically but not sure how to do this.

If I had a class Shapes, and within that I have a function that returns all the shapes List<Shapes>
I have to manually add it each time I add a new shape, I was wondering if its possible to do this through reflection somehow,
that it automatically gets all the subclassess and adds it?


Example
class Shapes
public static class AllShapes
public static List<Shapes> getAllShapes()
{
List<aShape> newList= new List<aShape> {}
newlist.add(new Square());
newlist.add(new Rectangle());
//---manually add more here---
return newList;
}

public class Square() : iShape {}
public class Rectange() : iShape {}
public class Circle() : iShape {}
public class Diamond() : iShape {}
 
Dumb question, but why do you want to do this? There's probably a better solution than this.
But in regards to the question, you want a list of parent type that then has each child type added to it as an entry?

Look at:

Or do you want to load stuff out of a DB or something and don't know the object until you run the program?

If it's for something like a program and you need it for dropdown entries or something like that, it's still better to manually add each/have a main list with what types are available than do it programmatically imho, takes a few seconds and can then easily be controlled as to when you retire some of them without removing the capability completely from the program (e.g. historic entries).
 
You could have Square, Rectangle etc extend an abstract base class, AbstractShape, and AbstractShape and then be responsible for registering that instance of the shape with the Shapes class that represents the collection of shapes. Because AllShapes is static, you could do this fairly easily.

You may have to be careful with deleting Shapes though, since you may have to make sure that they are removed from the AllShapes collection.

EDIT: As @Johnatan56 says, there are multiple ways of doing this. Perhaps tell us what the actual requirement is?

Generally, try to avoid reflection if you can. Its pretty slow.
 
Dumb question, but why do you want to do this? There's probably a better solution than this.
But in regards to the question, you want a list of parent type that then has each child type added to it as an entry?

Look at:

Or do you want to load stuff out of a DB or something and don't know the object until you run the program?

If it's for something like a program and you need it for dropdown entries or something like that, it's still better to manually add each/have a main list with what types are available than do it programmatically imho, takes a few seconds and can then easily be controlled as to when you retire some of them without removing the capability completely from the program (e.g. historic entries).

Open to any suggestions, but the situation is that I have objects (unique calculation objects) in a separate class to the main app that I edit.

I create a class/object, I use it, at some point I take it out as its no longer needed (permanently after recompiling)
In the application you must be able to select any of these calculations, so I need to get the new objects in.

So it takes me a day or 2 to create a new object, I add it to the list manually each time,
I recompile the app, select it from my menu, and then get the answers and no longer need the object
so I comment it out and remove if from the list (as I dont want to see 100s of these things).


So I have to constantly add the new class in manually...so trying to figure out how to automate the part where I have to constantly manage the list
 
Look at:

Thanks the link helped a lot!

List<aShape> bList = new List<aShape> { };

var subclasses =
from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.IsSubclassOf(typeof(aShape))
select type;

foreach (Type obj in subclasses)
{
aShape test = (aShape)Activator.CreateInstance(obj);
bList.Add(test);
}
 
Open to any suggestions, but the situation is that I have objects (unique calculation objects) in a separate class to the main app that I edit.

I create a class/object, I use it, at some point I take it out as its no longer needed (permanently after recompiling)
In the application you must be able to select any of these calculations, so I need to get the new objects in.

So it takes me a day or 2 to create a new object, I add it to the list manually each time,
I recompile the app, select it from my menu, and then get the answers and no longer need the object
so I comment it out and remove if from the list (as I dont want to see 100s of these things).


So I have to constantly add the new class in manually...so trying to figure out how to automate the part where I have to constantly manage the list
Why not define your object as a JSON schema then? Then use a ToObject dictionary, as long as they use the same general attributes? If it's something like a form, build it from the JSON object.
 
Why not define your object as a JSON schema then? Then use a ToObject dictionary, as long as they use the same general attributes? If it's something like a form, build it from the JSON object.

Can a person run the code in the JSON object during runtime?

If I created a textbox would a person be able to convert this text (typed during runtime)
into code that refers to variables within compiled application?
(Hope my question makes sense)
 
Can a person run the code in the JSON object during runtime?

If I created a textbox would a person be able to convert this text (typed during runtime)
into code that refers to variables within compiled application?
(Hope my question makes sense)
Not 100% sure, you could probably set up a dictionary with a key/value mapping whereby the key would be the string/variable that the user would type, break the user's string into variables and actions.

Can't really say without knowing the full use case. You might also end up writing yourself out of a job if this is your primary job. :p

(http://tomasp.net/blog/dynamic-linq-queries.aspx/)
 
Can a person run the code in the JSON object during runtime?

If I created a textbox would a person be able to convert this text (typed during runtime)
into code that refers to variables within compiled application?
(Hope my question makes sense)

Not impossible, but... why?

Kinda goes against the paradigm of C#. Use an interpreted language if that is what you want.
 
Why not have each shape as a separate assembly. Then you can extend without recompiling.
 
Not impossible, but... why?

Kinda goes against the paradigm of C#. Use an interpreted language if that is what you want.
My guess is speed, given his earlier posts on Python vs C# perf, but then something like Julia that JITs would be better.
 
A wider explanation of the program - its a private project.
What it does is -
- I get data in, in the main app through making selections, this part of the model stays the same (the engine)
- I then do a calc on the selected data (this calc changes literally hour to hour)
- It then gives me a report (report is standardized)

For those familiar with this its basically a backtesting engine on Equity data, so you write different systems.
So like Metatrader isnt suppose to change/get recompiled everytime a person tries to backtest a new idea.

So imagine pulling in the data of some share price over the past 10 years then this time I calc how often does Close > Open happen
I notice the idea is bad and then I change it to ' Close > Open and Close[1] > Open[1]', each time printing a new report.
The calculation uses data in the main app - Close,Open, etc
I only need to recompile the calc portion not the whole system.
It would be great if I could simply write in a small textbox without restarting the whole app each time as to what the calc should be.
Most backtesting systems have a "recompile" button while the app is running, somehow this is quite possible to do.

In something like Python this was quite simple, I just built a Framework, and then just referenced it.

Most of my calculations take 25 - 40 seconds in C# and quite a bit longer in python,
C# also has the GUI which I like, but Python has been much more flexible with what I can pull in and change.
Im guessing python might be a better route in the long run, but I havent spent to time to get the speeds the same on the calcs.
(which could take quite some time).
 
Ive seen a few articles written on DOM
and articles like this


Might investigate this a bit
 
Interesting. But how long does it take you to write a new calc? I would have thought that takes longer than the process of recompiling and starting up again.

You could also investigate genetic algorithms for this sort of thing. It depends on how much difference there is between your calcs. If they differ mostly in things like constant values, then genetic algorithms are fantastic at optimizing that.

Theoretically, you could have a genetic algorithm generate simple coding statements (if you're calcs are not that involved), and then test those. But you'd have to take pains to ensure that the coding statements are valid, and you'd also have to think about how you'd select the fittest of the population and then use them for the next generation.
 
Interesting. But how long does it take you to write a new calc? I would have thought that takes longer than the process of recompiling and starting up again.

You could also investigate genetic algorithms for this sort of thing. It depends on how much difference there is between your calcs. If they differ mostly in things like constant values, then genetic algorithms are fantastic at optimizing that.

Theoretically, you could have a genetic algorithm generate simple coding statements (if you're calcs are not that involved), and then test those. But you'd have to take pains to ensure that the coding statements are valid, and you'd also have to think about how you'd select the fittest of the population and then use them for the next generation.

This is a bit over my head :) but I appreciate the advice and will look into it
Recompiling is just a schlep, also I would prefer having these calcs into small files that I can save and move out if I no longer need them.
The other issue is that if I ever work with somebody else I dont necessarily want to give them the whole projects code, but just the engine.

Often the calcs are relatively simple and the time to write them is more limited by your thoughts than by the coding.
A basic example would be - if Im looking at testing what happens when theres a new high and the price is relatively low (relative to the past few days)
the code would look something like

private void CheckBuySignals()
{
bool buySignal = false;
double highst = indicator.Highest( High, 20 ); - get the highest value of the past 20 days
double stchs = indicator.Stochastics( Close, 14 ); - get the stochs/relative range in the past 14 days

if (Close[0] > highst && stchs < 50) { buySignal = true; }

return buySignal;
}


These are all pre-populated by my selections:
Open[0]...Open[n]
High[0]...High[n]
Low[0]...Low[n]
Close[0]...Close[n]
Volume[0]...Volume[n]
 
This is a bit over my head :) but I appreciate the advice and will look into it
Recompiling is just a schlep, also I would prefer having these calcs into small files that I can save and move out if I no longer need them.
The other issue is that if I ever work with somebody else I dont necessarily want to give them the whole projects code, but just the engine.

Often the calcs are relatively simple and the time to write them is more limited by your thoughts than by the coding.
A basic example would be - if Im looking at testing what happens when theres a new high and the price is relatively low (relative to the past few days)
the code would look something like

private void CheckBuySignals()
{
bool buySignal = false;
double highst = indicator.Highest( High, 20 ); - get the highest value of the past 20 days
double stchs = indicator.Stochastics( Close, 14 ); - get the stochs/relative range in the past 14 days

if (Close[0] > highst && stchs < 50) { buySignal = true; }

return buySignal;
}


These are all pre-populated by my selections:
Open[0]...Open[n]
High[0]...High[n]
Low[0]...Low[n]
Close[0]...Close[n]
Volume[0]...Volume[n]
Interesting.

So, ignore my comment about using genetic algorithms to generate the code itself - that won't work. But you can use genetic algorithms to optimize the constants of 14, 20 and 50. Its relatively easy to do.

Lastly, you might want to look at using C#'s functional programming support for this kind of thing. It might give you a little more flexibility, although I suspect not in the direction that you crave. Functional programming allows you to define function pointers. You wouldn't need interfaces as much - you might for example have a factory class, that instantiates a calc class with the functions set to whatever you want them to be.

I'm not explaining it well I think. But look up functional programming in C#, you might find it interesting.
 
Maybe some DSL that then uses reflectiom.emit to emit c# code and compile at runtime. for smplcity sake i would use a ‘plugin’ type concept where you compile each calc as its own asembly and deploy/load at runtime
 
Top
Sign up to the MyBroadband newsletter
X