Is there any way to create some codes which compiler will generate some another code like below?

Agung Pratama

Let say I have this kind of class in c# language:

public class ABC {
    public int var_1;
    public int var_2;
    public int var_3;
    //... until 100
    public int var_100;


    public int GetData_WithBasicIfElse (int id) {
        if(id == 1)
            return var_1;
        else if(id == 2)
            return var_2;
        else //and so on until
        else if(id == 100)
            return var_100;
    }

    public int GetData_WithReflection(int id){
        string key = "var_" + id.ToString ();
        FieldInfo info = GetType ().GetField (key);
        return info != null ? (int)info.GetValue (this) : 0;
    }

    public int GetData_WithSpecialCode(int id){
        //put the simple codes here, then compilers compile it, it will generate code like the method     GetData_WithBasicIfElse
    }
}

Actually in most cases, I can use the array to hold var_n variable, but I am just curious if there is another way. I do not want to use GetData_WithBasicIfElse (not elegant), but I am wondering if there is another solution beside using reflection.

What I mean with GetData_WithSpecialCode is, it contains the special code that will be transformed by compiler (when compile time, where it will be binary file) into some pattern like GetData_WithBasicIfElse.

UPDATED This technique's called Template metaprogramming, as you can see in here: http://en.wikipedia.org/wiki/Template_metaprogramming, in the factorial source code.

JotaBe

T4 Template

A T4 Template can generate that desired C# code, that will be later compiled into IL code, as if you have written that code yourself. If you want to use this technique, the most natural way is to use partial classes. The first partial defines all the class except the auto-generated method. The second partial would be generated by a simple T4 template. (In the compiled code there's no difference between a class defined in a single file or in several partials).

Reflection.Emit

If you really want to generate code at runtime, it's much harder to do, but you can do it using Reflection.Emit This allow to directly emit IL at run time.

Expression Trees

This also allows to generate and compile code at run time. It's easier than the second option. See an introudction here.

Reflection

If you want to use your original Reflection solution you should store the FieldInfos in an static structure (array, list, dictionary or whatever) so that you only have the overhead of reflecting the fields once. This will improve the performace.

What to choose

Unless there is a good reason not to do so, I'd prefer the T4 template. It's the easier to implement, and you leave the compiler the reponsibility to compile and optimize your code. besides you don't have to work with "obscure, unusual" concepts.

In general I wouldn't advice you the second option. Between other things, I think this requires full trust. And, you need a good knowledge of what you're doing. You also miss the compiler optimizations.

Using expression trees is not as hard as using Reflection.Emit, but it's still hard to do.

And reflection always add a little overhead, specially if you don't cache the FieldInfos (or PropertyInfos or whatever). I would leave it for cases where is the only solution. For example checking if a property exists or accessing a private or protected member of a class from ouside.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Is there any way for console programs to change their execution way, due to some event, like e.g. key press or some event in code?

From Dev

Is there any way to auto run some code in DLL?

From Dev

How to generate javadoc for some codes with persian characters?

From Dev

Any way to create Here Documents that substitute some variables but not others in bash?

From Dev

Is this code encrypted in some way?

From Dev

Below Code is compiling in some IDE and not in some IDE "Java is Unsound"

From Dev

The below code wont execute with some inputs

From Dev

Django - Is there any way to generate some HTML parts on the fly without using the minidom or lxml libs?

From Dev

Is there some way of getting sysname in libusb like edev?

From Dev

Android issues-ui with logs like some below

From Dev

Android issues-ui with logs like some below

From Dev

Is there any way to invoke some script or alerts in aerospike

From Dev

Is there any way to async post some data with twisted?

From Dev

How to detect in runtime if some Compiler Option (like Optimization) is on?

From Dev

Is there any way we can execute some java code when a jvm process is killed?

From Dev

Is there any other compiler like typescript which compile to javascript

From Dev

Is there some easy way to add another HDD to a volume?

From Dev

NSArray create with some elements plus another NSArray

From Dev

What's problems will have with below code on some devices?

From Dev

AWK: Divide any element of any row by some element of another row

From Dev

Generate movie with some effects on server side like Facebook lookback

From Dev

Is it some way to do async code for write to Stream?

From Dev

Why does compiler build return unreachable code in some cases

From Dev

Which way of using Application.Run() is a better practice in code below?

From Dev

Is there a quick way to create an array of return codes from another array?

From Dev

Is there a way to generate some set of rows exactly once on demand in Postgres?

From Dev

Is there any better way to re-write the below code?

From Dev

jQuery function that run some codes

From Dev

Some of these codes don't run

Related Related

  1. 1

    Is there any way for console programs to change their execution way, due to some event, like e.g. key press or some event in code?

  2. 2

    Is there any way to auto run some code in DLL?

  3. 3

    How to generate javadoc for some codes with persian characters?

  4. 4

    Any way to create Here Documents that substitute some variables but not others in bash?

  5. 5

    Is this code encrypted in some way?

  6. 6

    Below Code is compiling in some IDE and not in some IDE "Java is Unsound"

  7. 7

    The below code wont execute with some inputs

  8. 8

    Django - Is there any way to generate some HTML parts on the fly without using the minidom or lxml libs?

  9. 9

    Is there some way of getting sysname in libusb like edev?

  10. 10

    Android issues-ui with logs like some below

  11. 11

    Android issues-ui with logs like some below

  12. 12

    Is there any way to invoke some script or alerts in aerospike

  13. 13

    Is there any way to async post some data with twisted?

  14. 14

    How to detect in runtime if some Compiler Option (like Optimization) is on?

  15. 15

    Is there any way we can execute some java code when a jvm process is killed?

  16. 16

    Is there any other compiler like typescript which compile to javascript

  17. 17

    Is there some easy way to add another HDD to a volume?

  18. 18

    NSArray create with some elements plus another NSArray

  19. 19

    What's problems will have with below code on some devices?

  20. 20

    AWK: Divide any element of any row by some element of another row

  21. 21

    Generate movie with some effects on server side like Facebook lookback

  22. 22

    Is it some way to do async code for write to Stream?

  23. 23

    Why does compiler build return unreachable code in some cases

  24. 24

    Which way of using Application.Run() is a better practice in code below?

  25. 25

    Is there a quick way to create an array of return codes from another array?

  26. 26

    Is there a way to generate some set of rows exactly once on demand in Postgres?

  27. 27

    Is there any better way to re-write the below code?

  28. 28

    jQuery function that run some codes

  29. 29

    Some of these codes don't run

HotTag

Archive