15

I was reading an article about how to use the sizeof operator in C#.

They say: "Used to obtain the size in bytes for an unmanaged type."

I know the difference between managed and unmanaged code. But my understanding is that all code I write in C# (including all predefined and user-defined types) is managed by the CLR. So what do they mean by "unmanaged types"?

Zer0
  • 7,191
  • 1
  • 20
  • 34
TGY
  • 303
  • 3
  • 10
  • 2
    You can of course use types from a library written in C/C++ in your .NET-program. Those are called "unmanaged types". – MakePeaceGreatAgain Feb 20 '19 at 15:52
  • 1
    Possible duplicate of https://stackoverflow.com/questions/3563870/difference-between-managed-and-unmanaged –  Feb 20 '19 at 15:53
  • 1
    There is actually definition on the page you are referring to. In a simple words: strict that contains no references itself and in all the containing types, all the way down. It's called unmanaged because it doesn't contain or refer to any data which is managed by the garbage collector. – Vlad Feb 20 '19 at 15:59
  • 1
    @Amy: Not exactly a duplicate: a struct completely defined in managed code can be an unmanaged struct according to the definition at OP's link. – Vlad Feb 20 '19 at 16:01

1 Answers1

20

The term "unmanaged type" is a little bit misleading: is not a type which is defined in unmanaged code. It's rather a type which doesn't contain references managed by the garbage collector.

In C# 7.3 there is even a generic constraint unmanaged:

[...] must not be a reference type and must not contain any reference type members at any level of nesting.


If you have experience with WinAPI: the originally proposed name for unmanaged types was blittable.

Vlad
  • 35,022
  • 6
  • 77
  • 199
  • 1
    Here is the list of all unmanaged types: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/unmanaged-types – gonzobrains Jan 13 '21 at 21:53
  • @gonzobrains: Well, it's not exactly a _list_, it's a self-recursive definition, but it contains a list of primitive unmanaged types. – Vlad Jan 13 '21 at 23:25