I have an issue with passing a struct definition to a function. Not an instance of a struct, but the definition.
We are open to alternative methods of doing what we want, but for right now, this is what we're trying to do -
We are writing a user control. This control is to display data in list form with headers, but what "list" it might be asked to display is unknown at design time. Right now we're taking the approach that, in order to keep things lightweight, we're going to pass to a Constructor and/or GetHeaders function a Struct definition. The headers would be pulled from the field names found in a passed structure definition, with data later coming in in both individual objects and lists of objects of that structure type.
Example. On the Control side:
private void GetHeaders( dynamic _strc )
{
//Type _str_type = ((ObjectHandle) _str).Unwrap().GetType();
FieldInfo[] fi = _strc.GetFields( BindingFlags.Public | BindingFlags.Instance );
int _i = 0;
foreach (FieldInfo _f in fi)
{
textBox1.Lines[_i] = _f.Name;
}
textBox1.Refresh();
}
-Please note, I'm just trying to make sure I can parse the structure. We don't know if this will actually work yet since we can't get test to compile because of what is below.
The user will have their own struct definition to which the Control will not have direct access.
public struct MineStruct
{
String ID; // So we know who they are
String Name; // What we call them to their face
String Nickname;// What we call them behind their back
String Address; // We know where they live
int Mileage; // How far they've gone
int Millage; // How much they'll pay. Oh, they'll pay...
}
It will be passed at run-time, we had hoped, in something along these lines:
private void button1_Click(object sender, EventArgs e)
{
GetHeaders( MineStruct ); //<-Error messaage here
}
The error message we are getting is "'Form1.MineStruct' is a type. which is not valid in the given context" I've tried changing the GetHeaders function to take "Type", among other things, but nothing helps there.
So, my questions, in order are...
1) Is this a good way to approach the issue? We're completely open to doing another way, even passing a whole Class, but we'd like to keep it lightweight, which we believe this would be.
2) Is it even possible?
3) Is this actually lightweight?
4) If so, how do we pass a Struct Definition to a function in C#?
What you're calling a "definition" is known as a Type
in C#. If you know the name of the type you want information about (as is your case), you can use typeof(MineStruct)
to get a Type
object (which you mentioned you tried as the parameter of GetHeaders
), from which you can call GetFields
to get its fields. If you had an object that you wanted to get type information about, you'd need to call myObj.GetType()
instead.
As an aside, the struct's fields are private
(the default situation in C#), so you'll need to use BindingFlags.NonPublic
as in this answer.