Skip to content

Instantly share code, notes, and snippets.

@jaymedavis
Created October 13, 2017 23:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jaymedavis/b1d773064d860dec0408fffe2ed30a5b to your computer and use it in GitHub Desktop.
Reading the StripeBilling Attribute
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace SmoothNumerator
{
class Program
{
public enum StripeBilling
{
[EnumMember(Value = "charge_automatically")]
ChargeAutomatically,
[EnumMember(Value = "send_invoice")]
SendInvoice,
}
public class SomeStripeEntity
{
public StripeBilling Billing { get; set; }
}
static void Main(string[] args)
{
var foo = new SomeStripeEntity
{
Billing = StripeBilling.ChargeAutomatically
};
// passed to the middleware Parse() as the `property` argument
var property = foo.Billing.GetType().GetProperty(nameof(StripeBilling));
// passed to the middleware Parse() as the 'propertyValue' argument
var propertyValue = foo.Billing.GetType().GetField(foo.Billing.ToString());
// grab the attributes from the property (line 20, you know it's an enum already)
var attributes = propertyValue.GetCustomAttributes(false);
// if it has a value attribute, read it
dynamic attribute = attributes.ElementAt(0);
Console.WriteLine(attribute?.Value ?? "I couldn't find that!");
//// outputs: charge_automatically
// keep the terminal open
Console.ReadLine();
}
}
}
@jaymedavis
Copy link
Author

The System.Linq reference isn’t needed here, unless you want to try attributes.Any(), to be on the defensive side.

@ob-stripe
Copy link

Thanks @jaymedavis! I gave this a try, however it seems I cannot call GetCustomAttributes because propertyValue has been downcast to an object in the parser function:

error CS1929: 'object' does not contain a definition for 'GetCustomAttributes' and the best extension method overload 'CustomAttributeExtensions.GetCustomAttributes(Assembly, Type)' requires a receiver of type 'Assembly'

Any idea how I could fix that? It's probably simple but I can't seem to figure it out...

@jaymedavis
Copy link
Author

propertyValue.GetType() maybe?

@jaymedavis
Copy link
Author

Also could try...

typeof(propertyValue).GetTypeInfo().GetCustomAttribute<>() ....

might work too.

@jaymedavis
Copy link
Author

jaymedavis commented Oct 15, 2017

You might be able to create a base type for all StripeEnums called StripeEnum. Then, all your enums could inherit from there. That way, the last example could become .GetCustomAttribute<StripeEnum> to avoid potential problems in the case of having more than one attribute on the property.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment