stupid issue with struct

  • Thread starter Thread starter Alcibiade
  • Start date Start date
A

Alcibiade

Hi guys, I have a problem with fileInfo struct
the following code works fine but I think it s not correct to use keywork
new for a struct

fileInfo informazioni_file=new fileInfo() ;
if (!file_valido(file,ref informazioni_file ))

How should I write it?
Thanks
 
* Alcibiade said:
Hi guys, I have a problem with fileInfo struct
the following code works fine but I think it s not correct to use keywork
new for a struct

In C#, structs are not what you'd expect (just plain structured data).
Contrary to C/C++, they are objects, too. But just like in C/C++, they
/can/ be used as value types. So, instantiating a C# struct with new is
perfectly valid, but maybe not necessary. If you just declare a variable
of a struct type, you will get a locally (i.e. stack)-allocated struct.

Be aware that when you allocate a struct locally, there won't be any
constructor invocation so the fields are uninitialized, probably
containing random garbage.
fileInfo informazioni_file=new fileInfo() ;
if (!file_valido(file,ref informazioni_file ))

How should I write it?

probably, the following would work as well:
| fileInfo informazioni_file;
| if (!file_valido(file,ref informazioni_file ))
(no need to initialize the fileInfo struct when file_valido() will write
to it)

Regards,
Felix
 
Back
Top