Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

c# - Enum Size in Bytes

What is the size of the enum below in bytes?

public enum MMTPCnxNckRsn 
{
    MMTPCnxNckRsnNoAnswer = -2, 
    MMTPCnxNckRsnSendError = -1, 
    MMTPCnxNckRsnOk = 0, 
    MMTPCnxNckRsnInvalidMember = 1, 
    MMTPCnxNckRsnHubNotReady = 2, 
    MMTPCnxNckRsnUnknownMember = 3, 
    MMTPCnxNckRsnLastCnxTooRecent = 4, 
    MMTPCnxNckRsnInvalidVersion = 5, 
    MMTPCnxNckRsnInvalidOptions = 6, 
    MMTPCnxNckRsnTooManyCnx = 7 
};

I've used the code below to find it but I think it is not enough. It is a string array with 10 elements. Should I count the chars in each element, assume each char to be 1 byte, and add all bytes of elements? What about unsigned numbers?

var size = Enum.GetNames(typeof(MMTPCnxNckRsn)).Length;
var arr = Enum.GetNames(typeof (MMTPCnxNckRsn));

I'm not sure if it is important to mention that I am in the middle of marshaling a native Win32 code to C#, and it is CRUCIAL to find the size of the enum for managing addresses in memory.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The documentation says:

The default underlying type of enumeration elements is int.

Therefore, your data type will have the size of 4 bytes, which is the size of an int.
You can confirm this by using the following command:

Marshal.SizeOf(Enum.GetUnderlyingType(typeof(MMTPCnxNckRsn)));

Whilst you refer to the enum values in source code using a name, they are represented in the code that runs on the machine as integer values. So your comment about string arrays is quite wide of the mark.

I also think you are over-thinking the issue of size. Looking at your other recent question, you seem to be translating a C++ structure to C# for pinvoke. Well, the C# enum will map straight onto the C++ enum. The pinvoke marshaller will look after the sizes and lay them out for you. You do not need to handle that explicitly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...