-1

I have a class called Person

class Person
{
    public string name;
    public int age;

    public Person(string name, int age)
    {
        this.name = name;
        this.age = age;
    }
}

I created an object.

Person person = new Person("Sam", 20);

Now I want to print the address inside the person reference.

Now if anyone is thinking what I want to do with the address I just want to understand the concept of references.

By concept of references I mean

  • Does a reference variable (here, person) contains address of the object.
  • If it does contain the address than I want to know it's value.
gamerdev
  • 65
  • 6
  • 2
    You never defined an 'address' variable in your class, you can access 'name' or 'age' like this `person.name` / `person.age`, you cannot however access an object that doesn't exist; we're programmers not wizards! – Prime Nov 01 '17 at 15:50
  • Are you asking about memory address? Or address of where this person lives? – Crescent Fresh Nov 01 '17 at 15:50
  • What's "the address"? What "concept" of references are you trying to understand? – David Nov 01 '17 at 15:51
  • 1
    If you mean "the memory address of the object", [that's not something you can easily do](https://stackoverflow.com/q/4994277/4137916) -- and that's entirely on purpose, since managed objects can move. – Jeroen Mostert Nov 01 '17 at 15:51
  • Just FYI, you shouldn't need to know the actual memory address of an object to understand how references work. At least I never did. :) – Rufus L Nov 01 '17 at 15:54
  • You want to print the address of a *reference*? This means the adress of an adress. I suppose you want the address of the *instance*, don´t you? Anyway there´s not much use for this address in .NET. Why do you even care on it? – MakePeaceGreatAgain Nov 01 '17 at 15:58
  • It will be more useful to read a good tutorial [Value vs Reference Types](http://www.albahari.com/valuevsreftypes.aspx) – Steve Nov 01 '17 at 16:01
  • I want to print the address of the object whose reference is person. And I want to know does a reference contains an address. – gamerdev Nov 01 '17 at 16:38

1 Answers1

-2

I think this is what you need:

&person -> gives you the pointer to the person variable

Try reading through this and see if it helps: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/unsafe-code-pointers/

user2887596
  • 641
  • 5
  • 15
  • 1
    That will give you the address of the `person` variable, not the address of the object that the person variable refers to. – Servy Nov 01 '17 at 15:54
  • Just typing the code you've provided will give a compile error: `Cannot take the address of, get the size of, or declare a pointer to a managed type ('Person')` – Rufus L Nov 01 '17 at 15:59
  • But I want the address of the object that person variable refers to. – gamerdev Nov 01 '17 at 16:50