tags:

views:

420

answers:

4

Hello,

When I call the ToString() methods on an expression, the enum value are printed as integers. Is there some format overload ?

Maybe I can create an derviedclass from expression and override some ToString Method. Any thoughts ?

Here is a sample :

    public enum LengthUnits { METRES, FEET };

    Expression<Func<LengthUnits, bool>> isFeet = l => l == LengthUnits.FEET;
    string isFeetFunctinoAsString = isFeet.ToString();

The value of isFeetFunctinoAsString is :

    u => (Convert(u) = 1)

I do not want the 1 but FEET .

A: 
Enum.GetName(Type MyEnumType,  object enumvariable)

From this question: http://stackoverflow.com/questions/424366/c-string-enums

Hope this is what you are looking for.

James Lawruk
A: 
myEnumValue.ToString ( "G" );

Taken from here

[Edit]

string isFeetFunctinoAsString = isFeet.ToString("G");
Binoj Antony
I think the question should answer whether this is available within the convertion from an expression tree to a string, not just the general .NET version.
Jan Jongboom
this does not work , there is no overload for the expression.ToString() method
Toto
+1  A: 

This is not possible in an expression, as even before you can interfere with the expression, the enum has already been converted to an integer.

You might want to check when there is a binaryexpression with the parameter on the left or right side, and convert by hand, but I won't recommend that.

Jan Jongboom
Why not recommanded that ?
Toto
Jan Jongboom
A: 

Here is what you would need to do to extract the integer value and parse it as the enumeration type:

BinaryExpression binaryExpression = (BinaryExpression)isFeet.Body;

LengthUnits units 
    = (LengthUnits)Enum.Parse
        (typeof(LengthUnits), 
        binaryExpression.Right.ToString());

But that won't give you exactly what you want. C# enumerations are like constants in the way that their values are literally transplanted into the source whenever they are referenced. The expression you have is demonstrating this as the literal value of the enumeration is embedded in the expression's string representation.

Andrew Hare