-
Notifications
You must be signed in to change notification settings - Fork 4.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Prefer sizeof over Marshal.SizeOf #33802
Comments
How do we determine they will produce the same answer? |
AFAIK @stephentoub wrote this one. I think the idea is that we can know this statically either by having a list of hardcoded types or when the type has the right characteristic based on the data in the reference assembly. |
What about the |
Estimates:
|
@Gnbrkm41 There's a proposal to mark methods that do "unsafe" things but lack doing things with actual pointers to force that they are called from an |
So we would warn for all primitives used in Marshal.Sizeof() except for char and bool as they differ from sizeof. This could probably also be extended to value types, but then the analyzed would become quite a lot more complicated. I assume the baseline request covers simply known primitives? |
Also, which Marshal.SizeOf options to we aim to find with the analyzer? I assume only the invocations with one type argument, as the overloads accepting either a type or an object are already flagged as obsolete? |
@Mrnikbobjeff can you please explain how you determined that only @Gnbrkm41 would you mind sharing examples of What is the condition to require unsafe code in the project? For example, these don't require to enable unsafe code in my project: int x = sizeof(char);
int y = sizeof(bool);
int z = sizeof(int); But these cases do: int w = sizeof(z);
int r = sizeof(5);
int v = 4;
int s = sizeof(v); |
It's only safe to replace
|
I get |
Because it isn't a "primitive', its a user-defined struct and the C# language makes no substantial inferences about user-defined structs.
As far as the language is concerned, Likewise, in cases of other structs the field contents might stay the same but the actual physical layout could change. For example, So its easiest in those cases to not allow it to be a C# constant and instead make it a JIT time constant instead ( |
sizeof
is much more efficient thanMarshal.SizeOf
. In cases where they'll produce the same answer, the former should be preferred (it'll generally require usingunsafe
, though, so this should only fire ifunsafe
is allowed in the project).Category: Performance
The text was updated successfully, but these errors were encountered: