c# - Can't Access Declared Structure with an Object -


i using structure shown below

public struct tpcanmsg {     /// <summary>     /// 11/29-bit message identifier     /// </summary>     public uint id;     /// <summary>     /// type of message     /// </summary>     [marshalas(unmanagedtype.u1)]     public tpcanmessagetype msgtype;       /// <summary>     /// data length code of message (0..8)     /// </summary>     public byte len;           /// <summary>     /// data of message (data[0]..data[7])     /// </summary>     [marshalas(unmanagedtype.byvalarray, sizeconst = 8)]     public byte[] data;    } 

then declared object structure in below

using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; using peak.can.basic;  namespace rctoonboardpc {     class communication     {        // can status decalaration        tpcanstatus gstatus;        // list of can messages        tpcanmsg msg1 = new tpcanmsg();            msg1.id = 0x100;       } } 

i following error"error 1 invalid token '=' in class, struct, or interface member declaration." can not understand why can not access structure respective object. please guide.

as question involves simple typographical error, should closed such, , may eventually.

in meantime, here commenters trying tell you…

the basic problem have written program statement outside of method. in c# (and indeed, similar language) not allowed. program statements required contained within method (aka "function").

you can resolve problem in 1 of 2 ways. easiest understand put statement in method (i.e. comply directly language rule you're running against):

class communication {    // can status decalaration    tpcanstatus gstatus;    // list of can messages    tpcanmsg msg1 = new tpcanmsg();     public communication()    {        msg1.id = 0x100;     } } 

the second way address issue relies on fact while program statements can't exist outside of method, can use expressions in variety of contexts, including initializers. , c# has initializer syntax allows include assignment statements part of initialization. i.e. technically writing initialization expression, in context you're allowed write little block of code that, long type of program statement includes assignment, legal though it's outside of method

that approach this:

class communication {    // can status decalaration    tpcanstatus gstatus;    // list of can messages    tpcanmsg msg1 = new tpcanmsg { id = 0x100 }; } 

note when using syntax, allowed omit parens () invocation of parameterless constructor. not required; if prefer writing new tpcanmsg() { id = 0x100 }, that's allowed too.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -