Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
My query is related to getting attributes of the instance from within the type of that instance. I can explain it better with an example.
Consider a simple class called "MyClass" with just one string type property called "Description".
C#
public class MyClass
{
    private System.String mDescription;
    public System.String Description
    {
        get
        {
            return mDescription;
        }
        set
        {
            mDescription = value;
        }
    }
}

The MyClass type is instantiated as a property in another class called "MyDeclaringClassA".
C#
public class MyDeclaringClassA
{
    private MyClass mMyClassInstance;
    public MyClass MyClassInstance
    {
        get
        {
            return mMyClassInstance;
        }
        private set
        {
            mMyClassInstance = value;
        }
    }
}

Now, I have a custom attribute called "DescriptionAttribute" that has just one string type property called "Description".
C#
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
sealed class DescriptionAttribute : Attribute
{
    readonly string description;
    public DescriptionAttribute(string description)
    {
        this.description = description;
    }

    public string Description
    {
        get { return description; }
    }
}

The purpose of the attribute is to decorate a property declartion with the same and specifying the description of that property *in the class it is declared in*. Like this;
C#
public class MyDeclaringClassA
{
    private MyClass mMyClassInstance;
    [Description("This is the MyClass instance declared in MyDeclaringClassA..")]
    public MyClass MyClassInstance
    {
        get
        {
            return mMyClassInstance;
        }
        private set
        {
            mMyClassInstance = value;
        }
    }
}

Now all I want to do is this;
C#
MyDeclaringClassA myDeclaringClassInstance = new MyDeclaringClassA();
var description = myDeclaringClassInstance.MyClassInstance.Description;

and get "This is the MyClass instance declared in MyDeclaringClassA.." in the variable, 'description'.
The place where I am trying to make the action happen is this;
C#
public class MyClass
{
    private System.String mDescription;
    public System.String Description
    {
        get
        {
            if (mDescription == null)
            {
                //mDescription = %I need to get the description from the attribute
                //declared for the instance of this type in MyDeclaringClass%
            }
            return mDescription;
        }
        set
        {
            mDescription = value;
        }
    }
}

I know how we can get custom attributes (MemberInfo.GetCustomAttributes Method) of a type or its members, using reflection. I could do it inside 'MyDeclaringClassA'. But I need to do it in 'MyClass' class, otherwise I'll have to repeat the same code over an over for every class I declare the 'MyClass' instance in. Any help will be greatly appreciated.
Posted

First, let's look just at the title of this question. It looks you are missing something important.

Let's look at all possible targets of the attributes. Please read this: http://msdn.microsoft.com/en-us/library/system.attributetargets.aspx[^].

All those targets are classified into Assembly, Module, all types, members of some types and parameters (I include return here). Five groups, 15 different targets. There are no instances of anything. The members can be static or not, it does not matter. Now, why? Because these objects exist before run-time is even started and are described as meta-data. These objects are created by the end of the loading and exist before JIT compiler (http://en.wikipedia.org/wiki/JIT_compiler[^]) starts its work. No instances of any objects are created, and no code is compiled into the native instruction set yet, but the meta-data is already there.

Everything else is created later, during run time. The run time is unable to modify any meta-data of the code. (Not exactly; this is so if we forget about System.Reflection.Emit: you can add some code during run-time and hence add to meta-data. Likewise, you can load another assembly, and that assembly will have its own types, which is trivial though. Let's not consider such cases for simplicity — they are pretty much irrelevant.) At the same time, run-time code can retrieve any meta-data from the very beginning of it.

So, the thing is: attributes are meta-data, nothing else. This is a custom "additional" meta-data. They can be applied to anything which can be used as meta-data, but nothing else.

So, here is a quick answer to your question: what you are trying to achieve is not possible in principle, makes no sense.

Perhaps your approach should be different: you have to explain the ultimate goal of your activity. What kind of functionality do you hope to provide? Maybe the solution can be found, but it should be pretty far from the line you are trying to think along.

—SA
 
Share this answer
 
v2
Comments
VermaManish 8-Feb-12 5:28am    
One more question before I start getting into details; is it possible to get the type of the instance in which my type "MyClass" is declared as property? I want to get this inside the "MyClass" class.

public class MyClass
{
private System.String mDescription;
public System.String Description
{
get
{
var stack1DeclaringType = //???
// stack1DeclaringType is expected to be typeOf(MyDeclaringClassA)
return mDescription;
}
set
{
mDescription = value;
}
}
}
Sergey Alexandrovich Kryukov 8-Feb-12 10:36am    
Yes, of course:

System.Type myType = self.GetType(); //run-time type
object[] attributes = myType.GetCustomAttributes(
typeof(MyAttributeClass),
false); // all attributes, but not inherited
if (attribute.Length > 0)
string description = ((MyAttributeClass)attributes[0]).Description;

But those are attributes (or other meta-data) of the type, not instance.
They will be the same when taken from other instance if the run-time
of the instance is the same. And hence, the same description.

--SA
VermaManish 8-Feb-12 13:03pm    
I may not be clear enough in my last question. What I was trying to ask is, whether I can get reference of the type object of the class in which "MyClass" is declared as property?
Espen Harlinn 8-Feb-12 9:16am    
Good points - emit can be used, but it's seldom worth it :)
Sergey Alexandrovich Kryukov 8-Feb-12 10:27am    
Agree, but I think Emit is irrelevant in this case.
Again, I would prefer to know OP's ultimate goal.
Thank you, Espen.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900