float a = 3f; // presumably the same as float a = new float(3f);
float b = a;
I want 'b' to be a brand new float and not now be a reference to 'a'.
How do I do this?
float a = 3f; // presumably the same as float a = new float(3f);
float b = a;
I want 'b' to be a brand new float and not now be a reference to 'a'.
How do I do this?
floats are value types not reference types so b is a new float and changing a won't affect b.
check this one: C# value types
Since float
type is a Value Type it will be a completely separate variable and does not reference a
in any way. Refernce
term does not makes sense for Value Types.
See Value Types on MSDN:
The value types consist of two main categories:
- Structs
- Enumerations
Structs fall into these categories:
- Numeric types
- Integral types
- Floating-point types
- decimal
- bool
- User defined structs.
I am going to demonstrate using your own code, that this already works the way you want it to:
using System;
public sealed class Program{
public static void Main()
{
float a = 3f; // presumably the same as float a = new float(3f);
float b = a;
a = a + 1;
Console.WriteLine("A:{0}", a);//prints 4
Console.WriteLine("B:{0}", b);//prints 3
}
}
And yes, as other people have pointed out, this works this way because float is a value type. Value types are stack allocated. This means that each variable that you declare and define as a value type will have its own space on the stack. On the reference types are heap allocated. This means that these variables dont really have the actual values that they represent on the stack. But they are just pointers to the actual objects on the heap. Look at MSDN's System.ValueType class for more clarity.
EDIT 1: I was wrong about how value types are ALWAYS stored on the stack. Anyone reading this should also read this question and this post by Eric Lippert to understand what actually happens under the covers. In this one case, the official Microsoft documentation (link shared above) seems to be wrong or at least capable of misinterpretation.
Just go ahead with your code.
Numeric values are copied when a new variable is assigned to an existing one.
Do this in LinqPad
float a = 3f;
float b = a;
b = 3.1f;
a.Dump();
b.Dump();
This is the result:
3
3.1