C# Error
CS1919 – Unsafe type ‘{0}’ cannot be used in object creation
Reason for the Error & Solution
Unsafe type ‘type name’ cannot be used in object creation.
The new
operator creates objects only on the managed heap. However, you can create objects in unmanaged memory indirectly by using the interoperability capabilities of the language to call native methods that return pointers.
To correct this error
-
Use a safe type in the new object creation expression. For example, use
char
orint
instead ofchar*
orint*
. -
If you must create objects in unmanaged memory, use a Win32 or COM method or else write your own function in C or C++ and call it from C#.
Example
The following example generates CS1919 because a pointer type is unsafe:
// cs1919.cs
// Compile with: /unsafe
unsafe public class C
{
public static int Main()
{
var col1 = new int* { }; // CS1919
var col2 = new char* { }; // CS1919
return 1;
}
}