0

can someone please explain , is value types and reference types are just c#.net concepts or it does apply to other variety of languages like c, c++, java. Thanks

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
Muneeb
  • 51
  • 2
  • 7
  • It is a universal concept in languages that don't ignore the way the processor works. You just don't always have to utter the words because the language designer made the choice for you. In Java everything is a reference type except for the primitives, the natural choice for a language with a garbage collector. In C and C++ everything is a value type with explicit syntax to manage references and copy values. In C# you get the choice. What you choose is very important, you can 't ignore the differences either in the declaration or in your code. – Hans Passant Oct 18 '15 at 10:55

2 Answers2

2

In Java, quoting from Does Java make distinction between value type and reference type:

In Java, all objects and enums are reference types, and all primitives are value types. The distinction between the two is the same as in C# with respect to copy semantics, but you cannot define a new value type in Java.

In C and C++, there is no concept of value type and reference type. C++ has references but that is not the same thing as reference types.

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

It applies to many programming languages.

Usually, value types can be stored in the stack (see this Eric Lippert's article for C# details) and reference types in the heap. Or, at least, value types are the ones that create a copy of themselves when they're assigned to a new variable or passed as arguments to a method.

For example:

// In C# a struct is a value type
public struct A 
{
    public string Text;

    public A(string text) 
    {
        Text = text;
    }
}

A a = new A("hello world");

// This creates a copy, instead of assigning the same "object" to a new reference
A a1 = a; 

See what Wikipedia says:

Some programming languages—notably C#, D, and Swift—use the term value type to refer to the types of objects for which assignment has deep copy semantics (as opposed to reference types, which have shallow

And also says:

Other programming languages—e.g., Java—do not formally define the term value type, but their practitioners informally use the term to refer to types with deep copy semantics (such as Java's primitive types). copy semantics

Another interesting Q&A can be stack and heap in V8 ( JavaScript).

Community
  • 1
  • 1
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206