C# - Implement Pointer as a Data Member

Here, we will learn how to implement pointer as a data member in C#?
Submitted by Nidhi, on November 01, 2020 [Last updated : March 23, 2023]

Here, we will demonstrate the pointer as a data member. To use pointer we need to write unsafe code, to compile unsafe code we need to allow unsafe code by clicking on properties in solution explorer and then "Allow Unsafe Code" from the Build tab.

C# program to demonstrate the example of pointer as a data member

The source code to demonstrate the pointer as a data member is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# - Implement Pointer as a Data Member.

using System;
unsafe class UnsafeEx
    int* p;
    int val;

    public UnsafeEx(int v)
        val = v;
        p = &v;

        Console.WriteLine("Val : " + *p);
    static void Main(string[] args)
        UnsafeEx U1 = new UnsafeEx(10);
        UnsafeEx U2 = new UnsafeEx(20);
        UnsafeEx U3 = new UnsafeEx(30);


Val : 10
Val : 20
Val : 30
Press any key to continue . . .


In the above program, we created class UnsafeEx that contains two data members val and an integer pointer p.  Here we defined a parameterized constructor to initialized the data member val and then assign the address of data member val to the pointer p and print the value of val using pointer within the constructor of the class. Here we used the unsafe keyword with the class definition.

C# Basic Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.