peter
peter

Reputation: 8652

what is the actual difference between reference variable and object

I have been reading a lot and now i really confused. Consider an ordinary instantiation:

Sampleclass  instance1  = new Sampleclass();

After reading a lot I came to know that instance1 is a reference variable stored in a stack which contains the memory address of the object's data which is stored in heap.

If this is correct then where is object? instance1 is also a object. Sometimes I have seen only declaration like new Sampleclass(). Is that sufficient for object instantiation?

Upvotes: 2

Views: 4868

Answers (4)

Kashif Faraz
Kashif Faraz

Reputation: 331

1) Sampleclass (Type) > Container type

2) instance1 (Identifier) > user-friendly name of reference (01010101010) of data which is stored in memory (heap) and "instance1" itself stored in the stack with reference (01010101010)

3) = (operator) > to asign left side value to right side

4) new (keyword) > Purchase a new space to stored data

5) Sampleclass(); (Constructor ) > make a copy of Type "Sampleclass" and stored in newly purchased space (this is actually an object or instance) and this accessed by its name "instance1" because "instance1" know the actual location of stored data in heap memory.

Upvotes: 0

ispiro
ispiro

Reputation: 27643

The expression new Sampleclass() creates an object. It also has a value which is a pointer to that object. You can do something with this pointer such as store it in a variable (e.g. Sampleclass instance1 = new Sampleclass(); ) or you can ignore it.

Why create something and ignore it? Because its constructor might have beneficial side effects for example.

Upvotes: 1

swcraft
swcraft

Reputation: 2112

instance1 contains the copy of the reference which points to the memory where new objet Sampleclass() is created. What's confusing is instance1 is mere a copy of a reference, which is different from reference ref (C# Reference), which might confuse you as it confused me.

Upvotes: 1

SLaks
SLaks

Reputation: 887285

instance1 is a variable.

Because its type is a reference type, it is a reference to an object instance that lives on the heap.

new SampleClass() is a constructor call that creates a new object on the heap and returns a reference to it.

Upvotes: 8

Related Questions