IS4
IS4

Reputation: 13207

Pointer of generic type

Why is the use of pointers to generic types invalid in C#? int?* is invalid, whereas typeof(int?).MakePointerType() doesn't produce an exception.

According to MSDN, a pointer can be of:

sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.

Any enum type.

Any pointer type.

Any user-defined struct type that contains fields of unmanaged types only.

I don't see any limitation relating to generics. int? looks valid, as it contains only a bool and int field.

Upvotes: 5

Views: 670

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127603

To quote the C# 5.0 specification §18.2 Pointer Types

Unlike references (values of reference types), pointers are not tracked by the garbage collector—the garbage collector has no knowledge of pointers and the data to which they point. For this reason a pointer is not permitted to point to a reference or to a struct that contains references, and the referent type of a pointer must be an unmanaged-type.

An unmanaged-type is any type that isn’t a reference-type or constructed type, and doesn’t contain reference-type or constructed type fields at any level of nesting. In other words, an unmanaged-type is one of the following:

  • sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.
  • Any enum-type.
  • Any pointer-type.
  • Any user-defined struct-type that is not a constructed type and contains fields of unmanaged-types only.

The key section that is stopping you is a the constructed type restriction.

from §1.6.3 Type parameters (emphasis mine)

A generic type with type arguments provided, like Pair<int,string> above, is called a constructed type.

Any generic type where you specify the type parameters is considered a constructed type and constructed types are not allowed to be in pointers. That is why Nullable<int> is not allowed.

Upvotes: 8

Related Questions