4

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 .

Toto
  • 7,491
  • 18
  • 50
  • 72

4 Answers4

1

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.

Ether
  • 53,118
  • 13
  • 86
  • 159
Jan Jongboom
  • 26,598
  • 9
  • 83
  • 120
  • 1
    Because you should create a whole new ToString method, because an expression tree doesn't have the same structure every time. You can have things like: l=>l==LengthUnits.FEET ; l=>LengthUntits.Feet==l ; l=>l>2 && l != LengthUnits.FEET etc. etc. – Jan Jongboom Sep 10 '09 at 17:04
0
Enum.GetName(Type MyEnumType,  object enumvariable)

From this question: C# String enums

Hope this is what you are looking for.

Community
  • 1
  • 1
James Lawruk
  • 30,112
  • 19
  • 130
  • 137
0
myEnumValue.ToString ( "G" );

Taken from here

[Edit]

string isFeetFunctinoAsString = isFeet.ToString("G");
Binoj Antony
  • 15,886
  • 25
  • 88
  • 96
  • 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 Sep 10 '09 at 15:30
  • 1
    this does not work , there is no overload for the expression.ToString() method – Toto Sep 10 '09 at 15:46
  • LInk from this answer appears to be broken. Microsoft documentation regarding format strings for enumerations can be found here: https://msdn.microsoft.com/en-us/library/c3s1ez6e(v=vs.110).aspx (retrieved at time of writing). Method ToString(string format) is available for Enumeration but not for Expression. – Manfred Feb 18 '17 at 02:51
0

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
  • 344,730
  • 71
  • 640
  • 635