![]() |
Data Types in C#
C# allows you to define two types of variables: value types and reference types. The value types hold actual values, while reference types hold references to values stored somewhere in memory.
Also value types are allocated on the stack and are available in most programming languages. Reference types are allocated on the heap and typically represent class instances. Predefined C# value types
Predefined C# reference types
SummaryProper utilization of correct data types allows developers to make the most of the language, but may take some time for those who have used different programming languages prior to switching to C#. For more information about each type, visit the Microsoft Web site. |
Re: Data Types in C#
Can you tell me why string is reference type and not as value type. I never understood this.
|
Re: Data Types in C#
Reference types actually hold the value of a memory address occupied by the object they reference. Consider the following piece of code, in which two variables are given a reference to the same object (for the sake of the example, this object is taken to contain the numeric property 'myValue').
Code: CSharp
This code illustrates how changing a property of an object using a particular reference to it is reflected in all other references to it. Note, however, that although strings are reference types, they work rather more like value types. When one string is set to the value of another, eg Code: CSharp
Then s2 does at this point reference the same string object as s1. However, when the value of s1 is changed, for instance with Code: CSharp
what happens is that a new string object is created for s1 to point to. Hence, following this piece of code, s1 equals "goodbye", whereas s2 still equals "hello". The reason for this behaviour is that string objects are 'immutable'. That is, the properties of these objects can't themselves change. So in order to change what a string variable references, a new string object must be created. |
Re: Data Types in C#
I am not sure and would like to know if this can be done.
Code:
int a = new int(); |
Re: Data Types in C#
string is an Object, that's why we instantiate it! int is not any class/object so, we can't do "new int();"
|
Re: Data Types in C#
Code:
int i = new int(); |
Re: Data Types in C#
How come?
|
Re: Data Types in C#
Test it and see.
|
Re: Data Types in C#
string is pretty much what is told but why you are able to do this
Code:
int i = new int(); |
Re: Data Types in C#
A data type can be described as being either:
A built-in data type such as an int or char OR A user-defined data type such as a class or interface. Data types can also be defined as being either: Value Types : which store values Reference Types: which store references to the actual Pointer types :Which can be used only in unsafe mode |
| All times are GMT +5.5. The time now is 14:34. |