tags:

views:

115

answers:

4

How to convert this code:

MYCLASS ebt = new MYCLASS();
ebt.cbStruct = Marshal.SizeOf(ebt);

into this:

MYCLASS ebt = new MYCLASS(cbStruct = Marshal.SizeOf('What comes here?'));
A: 

Use a MYCLASS constructor that takes a cbStruct parameter.

Kaleb Brasee
+2  A: 

Get the size of the type instead:

MYCLASS ebt = new MYCLASS { cbStruct = Marshal.SizeOf(typeof(MYCLASS)) };

Also note braces rather than parentheses to use initialiser syntax.

itowlson
Oops! I did the same earlier before asking the question, without any typos that for sure and it was not working, now it is.
Priyank Bolia
Also you guess it very right, MYCLASS is a struct so all Constructor answers are wrong. +10 more for this.
Priyank Bolia
A: 

maybe you could make the cbStruct property a getter?

public object cbStruct { get { return Marshal.SizeOf(this); }}
hunter
cbStruct usually implies a type from the Win32 C API, where cbStruct is a data member. If that's the case, cbStruct has to remain a data member -- implementing it as a property won't work for marshalling.
itowlson
+3  A: 

modify the MYCLASS ctor,

public MYCLASS()
{
   cbStruct = Marshall.SizeOf(this);
}
Charles Bretana
Nice variation of itowlson's example.
Chris
Just to add, this is permitted only if MYCLASS is a class. Many interop types are structs, and the default constructor for a struct can't be specified in C# -- it always initialises all fields to 0.
itowlson