I have very simple struct as below:
public struct ShFileInfo
{
public int hIcon;
public int iIcon;
public int dwAttributes;
}
I have enabled warning as error. Now for all three int
getting error
Field is never assigned to,and will always have its default value 0
Obviously I will get error if I try to initialize the int
to 0
. Is there any way to handle this without disabling warning as error.
Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).
We use structures to overcome the drawback of arrays. We already know that arrays in C are bound to store variables that are of similar data types. Creating a structure gives the programmer the provision to declare multiple variables of different data types treated as a single entity.
'Struct' keyword is used to create a structure. A structure can contain variables, methods, static constructor, parameterized constructor, operators, indexers, events, and property. A structure can not derive/inherit from any structure or class. A structure can implement any number of interfaces.
Syntax of struct For example, struct Person { char name[50]; int citNo; float salary; }; Here, a derived type struct Person is defined. Now, you can create variables of this type.
If your struct is inside internal class then you get this warrning
internal class WrapperClass
{
public struct ShFileInfo
{
public int hIcon;
public int iIcon;
public int dwAttributes;
}
}
when you change internal access to public then warnings gone:
public class WrapperClass
{
public struct ShFileInfo
{
public int hIcon;
public int iIcon;
public int dwAttributes;
}
}
I had been receiving the warning when I copy pasted author's code.
You can define a constructor for the Struct like this
public struct ShFileInfo
{
public int hIcon;
public int iIcon;
public int dwAttributes;
public ShFileInfo(int x,int y, int z)
{
hIcon = x;
iIcon = y;
dwAttributes = z;
}
}
You can also use a constructor with just one parameter and initialize all
public ShFileInfo(int x)
{
hIcon = x;
iIcon = 0;
dwAttributes = 0;
}
Since you are using this structure for P/Invoke only, I'd simply disable the warning locally:
#pragma warning disable 0649
public struct ShFileInfo
{
public int hIcon;
public int iIcon;
public int dwAttributes;
}
#pragma warning restore 0649
The compiler has no way of knowing that your structure is assigned in the unmanaged code, but since you know, there's little hurt in simply disabling the warning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With