I'm new to attributes so what I'm trying to achieve might not be possible. From my understanding, attributes are used to bind data at compile time to specific methods, properties, classes, etc.
My attribute is very simple and defined as follows:
public class NowThatsAnAttribute : Attribute
{
public string HeresMyString { get; set; }
}
I have two properties that are using the same custom attribute like so:
public class MyClass
{
[NowThatsAnAttribute(HeresMyString = "A" )]
public string ThingyA
{
get;
set;
}
[NowThatsAnAttribute(HeresMyString = "B" )]
public string ThingyB
{
get;
set;
}
}
That is all working fine and dandy, but I am trying to access the attributes of these properties from another method and set certain data based on the attribute's value.
Here is what I am doing right now:
private void MyMethod()
{
string something = "";
var props = typeof (MyClass).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(NowThatsAnAttribute)));
//this is where things get messy
//here's sudo code of what I want to do
//I KNOW THIS IS NOT VALID SYNTAX
foreach(prop in props)
{
//my first idea was this
if(prop.attribute(NowThatsAnAttribute).HeresMyString == "A")
{
something = "A";
}
else if(prop.attribute(NowThatsAnAttribute).HeresMyString == "B")
{
something = "B";
}
//my second idea was this
if(prop.Name == "ThingyA")
{
something = "A";
}
else if(prop.Name == "ThingyB")
{
something = "B";
}
}
//do stuff with something
}
The problem is that something is always being set to "B" which I know is due to looping through the properties. I'm just unsure how to access the value associated with the attribute of a specific property. I have a feeling there's a painfully obvious way of doing this that I'm just not seeing.
I've tried using the StackFrame but ended in near the same spot I'm at now.
NOTE: Using .Net 4.0.
NOTE2: MyMethod is part of an interface which I am unable to edit so I can't pass in any parameters or anything.
Any help is appreciated.
[NowThatsAn(HeresMyString = "A" )]