Retrieving a member's SizeConst value

  • Thread starter Thread starter MLM450
  • Start date Start date
M

MLM450

Is it possible to retrieve an item's "sizeconst" value dynamically?

I have the following member defined in a class:
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
private char[] units;

I want the code that values the units member to know the value of
SizeConst. I know I can define the size in another member but
accessing the SizeConst would make things much cleaner for what I am
trying to do.

Thanks,
Mike
 
Mike,

You can get the Type for the field, then get the FieldInfo for the units
field. Once you have that, you can call the GetCustomAttributes method on
the FieldInfo instance. You would pass in typeof(MarshalAsAttribute).

From the return value, you would then access the first member of the
array (there should be only one element in the array, if the attribute is
applied) and then access the SizeConst property of the attribute.
 
Thank you, Nicholas. That works very well. One more question. This
requires me to know the name of the field. I am working with many
fields so is there a way I can get a variable's field name dynamically?
 
You can call the GetFields method on the Type instance and it will
return all the fields for that type. You can then cycle through the fields
and look for the MarshalAsAttribute on each of them.
 
Thanks Nicholas, but I don't think I explained my problem very well. I
am putting together a function that gets a member variable and the
value that is to be assigned to it. I need the SizeConst info for that
member variable so I need its field name. Is that possible?

Thanks again,
Mike
 
Mike,

Some clarification first. The "SizeConst info" is actually a property
on the MarshaAsAttribute class. Attributes can be attached to methods,
fields, etc, etc.

All of this is metadata about the type. You can not get default values
that are assigned to a type as that is a run-time operation, something that
reflection does not handle (the only option there is to use the DefaultValue
attribute and set the value in the attribute, and the code, and reflect to
get that).

If you are creating a method which is going to get a field (which is
what I assume you mean by member variable) then you need to know the name of
the field, or you have to cycle through all the fields, using some mechanism
to identify the field that you want to use. From there, you can get the
attribute information, and then the SizeConst property value.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top