C# Error CS1919 – Unsafe type ‘{0}’ cannot be used in object creation

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

  1. Use a safe type in the new object creation expression. For example, use char or int instead of char* or int*.

  2. 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;  
    }  
}  

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...