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

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

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...