ADVERTISEMENT
ADVERTISEMENT

C# program to demonstrate the pointer as a data member

Here, we are going to demonstrate the pointer as a data member in C#?
Submitted by Nidhi, on November 01, 2020

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.

Program:

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# program to demonstrate the 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);
    }
}

Output:

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

Explanation:

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 »


ADVERTISEMENT




ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.