boxing and unboxing in int and string - c#

I am little bit confused in boxing and unboxing. According to its definition
Boxing is implicit conversion of ValueTypes to Reference Types (Object).
UnBoxing is explicit conversion of Reference Types (Object) to its equivalent ValueTypes.
the best example for describing this is
int i = 123; object o = i; // boxing
and
o = 123; i = (int)o; // unboxing
But my question is that whether int is value type and string is reference type so
int i = 123; string s = i.ToString();
and
s = "123"; i = (int)s;
Is this an example of boxing and unboxing or not???

Calling ToString is not boxing. It creates a new string that just happens to contain the textual representation of your int.
When calling (object)1 this creates a new instance on the heap that contains an int. But it's still an int. (You can verify that with o.GetType())
String can't be converted with a cast to int. So your code will not compile.
If you first cast your string to object your code will compile but fail at runtime, since your object is no boxed int. You can only unbox an value type into the exactly correct type(or the associated nullable).
Two examples:
Broken:
object o=i.ToString();// o is a string
int i2=(int)o;//Exception, since o is no int
Working:
object o=i;// o is a boxed int
int i2=(int)o;//works

int i = 2;
string s = i.ToString();
This is NOT boxing. This is simply a method call to Int32.ToString() which returns a formatted string representing the value of the int.
i = (int)s;
This code will not compile as there is no explicit conversion defined between System.String and System.Int32.
Think of it in the following way to understand what is and what is not boxing and unboxing:
Boxing: Its when you take a value type and just "stick" it in a reference variable. There is no need of any type specific conversion logic for this operation to work. The variable type will still be the same if you use GetType().
Unboxing: Its just the opposite operation. Take a value type stuck in a reference object and assign it to a value type variable. Again there is no need for any type specific conversion logic for this operation to work.
So if (int)s were valid, it would simply be a explicit conversion and not a unboxing operation, becuase s.GetType() would return System.String, not System.Int32.

Boxing/Unboxing: Conversion of Value Types to its object representation and vice versa (e.g. int and object).
The ToString() method in contrast is an operation which generated a new string, is has nothing to do with boxing/cast/type conversation.

Late to the party on this, but...... I don't like simply reading answers and without proofs behind them. I like to understand the problem and analyse the possible solution and see if it ties in with my understanding. This copy and paste text from the rightly acclaimed excellent 'CLR via C#' by the god Jeff Richter explains this:
Even though unboxed value types don’t have a type object pointer, you can still call virtual methods (such as Equals, GetHashCode, or ToString) inherited or overridden by the type. If your value type overrides one of these virtual methods, then the CLR can invoke the method nonvirtually because value types are implicitly sealed and cannot have any types derived from them. In addition, the value type instance being used to invoke the virtual method is not boxed. However, if your override of the virtual method calls into the base type's implementation of the method, then the value type instance does get boxed when calling the base type's implementation so that a reference to a heap object get passed to the this pointer into the base method. However, calling a nonvirtual inherited method (such as GetType or MemberwiseClone) always requires the value type to be boxed because these methods are defined by System.Object, so the methods expect the this argument to be a pointer that refers to an object on the heap.
Mr Richter should be given a medal for this book. If you haven't got it, get it!! Then you'll get it :)

Related

Why explicit conversion from object to long (Unboxing) is not allowed in C#? [duplicate]

We can cast int to long.
Why is the following piece of code gives a run time error.
object o = 9;
long i = (long)o;
Console.WriteLine(i);
I am new to C#.
The existing answers rightly explain why you get an exception, but don't really show what you could do instead. First casting to int is the typical answer, but only works if you know that the original value was an int. If the original value could be either int or long, then unboxing as int could fail just as well.
The simple way to change your code to something that works is by not attempting to do it yourself. .NET Framework already has a method to do exactly what you want: Convert.ToInt64. So just write
long i = Convert.ToInt64(o);
and let the runtime worry about any internally required intermediate type conversions.
Per this bit of documentation:
For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox null or a reference to an incompatible value type will result in an InvalidCastException.
So, you have to unbox to int first and then convert to long (an implicit conversion exists):
object o = 9;
long i = (int)o;
Since both int and long are value types, they are copied by value, and not by reference like reference types (e.g. object). So o is of a reference type, so the int object is stored by reference. In order to put it in a new variable of a value type, you need to have some value which you can actually copy into that.
So you need to cast the object to its actual type (int) first before you can perform a type conversion to long:
object o = 9;
long i = (long)(int)o;
You don’t necessarily need to do the (long) though as that happens implicitely when storing the value in the long.

C# - Does casting preserve the reference to the original object?

If I cast an object in C#, does it still reference the original object cast?
As an example, if I create a method to change an object and then cast that object depending on specific implementation called, does the original object get preserved?
public bool CallChangeString()
{
String str = "hello";
ChangeObject(str);
return String.Equals("HELLO", str);
}
public void ChangeObject(Object obj)
{
String str = obj as String;
str.ToUpper(); // pretend for the sake of this that this changes str to upper case
}
In this case, would the String.Equals return true or false?
Are there any situations where casting would cause the new object to not preserve it's reference?
Depends on what cast you are doing. You can think of two main groups of casting:
Those that preserve identity
Those that don't
Well, thats not very helpful, that is precisely what you are asking.
What casts don't preserve identity? All those that entail a representational change in the object itself, that is, the bits that make up the object change.
Examples? All casts between value types: int to long, int to double, etc., any boxing or unboxing conversion, etc. The bits that make up a long are very different from those that make up an int.
More examples? Any user defined cast operator, explicit or implicit. Why? Because user defined casts that preserve identity are disallowed by the compiler simply because the compiler already does them for you:
class Foo : IFoo
{
public static implicit operator object(Foo foo) => return foo; //Compile time error
public static implicit operator IFoo(Foo foo) => return foo; //compile time error.
public static explicit operator Bar(Foo foo) => return new Bar(foo);
}
Note the general pattern of user defined casts:
any valid operator will always have a new lurking
around in whatever it returns. Thats telling you right away that the
cast can not preserve identity... you are returning a new object.
There is no way you can implement a user defined identity preserving conversion. Thats not a problem because there is no need, those conversions are already provided by C#'s type system.
So, what are identity preserving casts or conversions? Well, those that don't touch the object all; reference conversions.
Huh? But wait, The whole point is that I'm casting the object, how can that be?
In reference conversions you are only "casting" the reference pointing to the object. The object is always the same. This, of course, only makes sense in reference types and that is why value types don't have identity preserving conversions; there are no references to value types unless they are boxed.
Examples? object to string, Foo to IFoo, Giraffe to Animal, etc.
Do note that reference types can very well implement user defined casts too, but these will not preserve identity.
All that said, this is the rule of the thumb:
Any cast provided/allowed by the language type system itself preserves identity. These are, exclusively, reference conversions and only apply to reference types.
Any user defined cast, explicit or implicit, does not preserve identity (rememeber, (long)2 is a user defined cast, somebody had to implement it in the class System.Int64).
So, answering your question, var str = obj as string is a reference conversion, which means that ReferenceEquals(str, obj) is true; str and obj point to exactly the same object, the only difference is the type of the reference.
strings are immutable, so you can't change them. However you can create new instances:
myString = myString.Replace("", ".");
Be aware that myString is a completely new instance which is not related to the original string. Thus even if you assign something different to myString this won't affect your calling code that relies on the original instance.
In your example str.ToUpper() won't change anything, as ToUpper returns a new string instead of changing the current (str) instance.
casting creates a new reference to the same instance. Thus modifications to an instance are reflected in all of its references, be it casted instances or just re-references
var a = (MyType) myInstance;
a.MyProperty = 4;
After the last statement both a and myInstance have the property MyProperty set to 4, because both variables a and myInstance reference the same instance of MyType.
Change your method like this and see result )
public bool CallChangeString()
{
String str = "hello";
ChangeObject(str);
return String.Equals("HELLO", str);
}

What is the difference between casting and coercing?

I've seen both terms be used almost interchangeably in various online explanations, and most text books I've consulted are also not entirely clear about the distinction.
Is there perhaps a clear and simple way of explaining the difference that you guys know of?
Type conversion (also sometimes known as type cast)
To use a value of one type in a context that expects another.
Nonconverting type cast (sometimes known as type pun)
A change that does not alter the underlying bits.
Coercion
Process by which a compiler automatically converts a value of one type into a value of another type when that second type is required by the surrounding context.
Type Conversion:
The word conversion refers to either implicitly or explicitly changing a value from one data type to another, e.g. a 16-bit integer to a 32-bit integer.
The word coercion is used to denote an implicit conversion.
The word cast typically refers to an explicit type conversion (as opposed to an implicit conversion), regardless of whether this is a re-interpretation of a bit-pattern or a real conversion.
So, coercion is implicit, cast is explicit, and conversion is any of them.
Few examples (from the same source) :
Coercion (implicit):
double d;
int i;
if (d > i) d = i;
Cast (explicit):
double da = 3.3;
double db = 3.3;
double dc = 3.4;
int result = (int)da + (int)db + (int)dc; //result == 9
Usages vary, as you note.
My personal usages are:
A "cast" is the usage of a cast operator. A cast operator instructs the compiler that either (1) this expression is not known to be of the given type, but I promise you that the value will be of that type at runtime; the compiler is to treat the expression as being of the given type, and the runtime will produce an error if it is not, or (2) the expression is of a different type entirely, but there is a well-known way to associate instances of the expression's type with instances of the cast-to type. The compiler is instructed to generate code that performs the conversion. The attentive reader will note that these are opposites, which I think is a neat trick.
A "conversion" is an operation by which a value of one type is treated as a value of another type -- usually a different type, though an "identity conversion" is still a conversion, technically speaking. The conversion may be "representation changing", like int to double, or it might be "representation preserving" like string to object. Conversions may be "implicit", which do not require a cast, or "explicit", which do require a cast.
A "coercion" is a representation-changing implicit conversion.
Casting is the process by which you treat an object type as another type, Coercing is converting one object to another.
Note that in the former process there is no conversion involved, you have a type that you would like to treat as another, say for example, you have 3 different objects that inherit from a base type, and you have a method that will take that base type, at any point, if you know the specific child type, you can CAST it to what it is and use all the specific methods and properties of that object and that will not create a new instance of the object.
On the other hand, coercing implies the creation of a new object in memory of the new type and then the original type would be copied over to the new one, leaving both objects in memory (until the Garbage Collectors takes either away, or both).
As an example consider the following code:
class baseClass {}
class childClass : baseClass {}
class otherClass {}
public void doSomethingWithBase(baseClass item) {}
public void mainMethod()
{
var obj1 = new baseClass();
var obj2 = new childClass();
var obj3 = new otherClass();
doSomethingWithBase(obj1); //not a problem, obj1 is already of type baseClass
doSomethingWithBase(obj2); //not a problem, obj2 is implicitly casted to baseClass
doSomethingWithBase(obj3); //won't compile without additional code
}
obj1 is passed without any casting or coercing (conversion) because it's already of the same type baseClass
obj2 is implicitly casted to base, meaning there's no creation of a new object because obj2 can already be baseClass
obj3 needs to be converted somehow to base, you'll need to provide your own method to convert from otherClass to baseClass, which will involve creating a new object of type baseClass and filling it by copying the data from obj3.
A good example is the Convert C# class where it provides custom code to convert among different types.
According to Wikipedia,
In computer science, type conversion, type casting, type coercion, and type juggling are different ways of changing an expression from one data type to another.
The difference between type casting and type coercion is as follows:
TYPE CASTING | TYPE COERCION
|
1. Explicit i.e., done by user | 1. Implicit i.e., done by the compiler
|
2. Types: | 2. Type:
Static (done at compile time) | Widening (conversion to higher data
| type)
Dynamic (done at run time) | Narrowing (conversion to lower data
| type)
|
3. Casting never changes the | 3. Coercion can result in representation
the actual type of object | as well as type change.
nor representation. |
Note: Casting is not conversion. It is just the process by which we treat an object type as another type. Therefore, the actual type of object, as well as the representation, is not changed during casting.
I agree with #PedroC88's words:
On the other hand, coercing implies the creation of a new object in
memory of the new type and then the original type would be copied over
to the new one, leaving both objects in memory (until the Garbage
Collectors takes either away, or both).
Casting preserves the type of objects. Coercion does not.
Coercion is taking the value of a type that is NOT assignment compatible and converting to a type that is assignment compatible. Here I perform a coercion because Int32 does NOT inherit from Int64...so it's NOT assignment compatible. This is a widening coercion (no data lost). A widening coercion is a.k.a. an implicit conversion. A Coercion performs a conversion.
void Main()
{
System.Int32 a = 100;
System.Int64 b = a;
b.GetType();//The type is System.Int64.
}
Casting allows you to treat a type as if it were of a different type while also preserving the type.
void Main()
{
Derived d = new Derived();
Base bb = d;
//b.N();//INVALID. Calls to the type Derived are not possible because bb is of type Base
bb.GetType();//The type is Derived. bb is still of type Derived despite not being able to call members of Test
}
class Base
{
public void M() {}
}
class Derived: Base
{
public void N() {}
}
Source: The Common Language Infrastructure Annotated Standard by James S. Miller
Now what's odd is that Microsoft's documentation on Casting does not align with the ecma-335 specification definition of Casting.
Explicit conversions (casts): Explicit conversions require a cast
operator. Casting is required when information might be lost in the
conversion, or when the conversion might not succeed for other
reasons. Typical examples include numeric conversion to a type that
has less precision or a smaller range, and conversion of a base-class
instance to a derived class.
...This sounds like Coercions not Casting.
For example,
object o = 1;
int i = (int)o;//Explicit conversions require a cast operator
i.GetType();//The type has been explicitly converted to System.Int32. Object type is not preserved. This meets the definition of Coercion not casting.
Who knows? Maybe Microsoft is checking if anybody reads this stuff.
From the CLI standard:
I.8.3.2 Coercion
Sometimes it is desirable to take a value of a type that is not assignable-to a location, and convert
the value to a type that is assignable-to the type of the location. This is accomplished through
coercion of the value. Coercion takes a value of a particular type and a desired type and attempts
to create a value of the desired type that has equivalent meaning to the original value. Coercion
can result in representation change as well as type change; hence coercion does not necessarily
preserve object identity.
There are two kinds of coercion: widening, which never loses information, and narrowing, in
which information might be lost. An example of a widening coercion would be coercing a value
that is a 32-bit signed integer to a value that is a 64-bit signed integer. An example of a
narrowing coercion is the reverse: coercing a 64-bit signed integer to a 32-bit signed integer.
Programming languages often implement widening coercions as implicit conversions, whereas
narrowing coercions usually require an explicit conversion.
Some coercion is built directly into the VES operations on the built-in types (see §I.12.1). All
other coercion shall be explicitly requested. For the built-in types, the CTS provides operations
to perform widening coercions with no runtime checks and narrowing coercions with runtime
checks or truncation, according to the operation semantics.
I.8.3.3 Casting
Since a value can be of more than one type, a use of the value needs to clearly identify which of
its types is being used. Since values are read from locations that are typed, the type of the value
which is used is the type of the location from which the value was read. If a different type is to
be used, the value is cast to one of its other types. Casting is usually a compile time operation,
but if the compiler cannot statically know that the value is of the target type, a runtime cast check
is done. Unlike coercion, a cast never changes the actual type of an object nor does it change the
representation. Casting preserves the identity of objects.
For example, a runtime check might be needed when casting a value read from a location that is
typed as holding a value of a particular interface. Since an interface is an incomplete description
of the value, casting that value to be of a different interface type will usually result in a runtime
cast check.
Below is a posting from the following article:
The difference between coercion and casting is often neglected. I can see why; many languages have the same (or similar) syntax and terminology for both operations. Some languages may even refer to any conversion as “casting,” but the following explanation refers to concepts in the CTS.
If you are trying to assign a value of some type to a location of a different type, you can generate a value of the new type that has a similar meaning to the original. This is coercion. Coercion lets you use the new type by creating a new value that in some way resembles the original. Some coercions may discard data (e.g. converting the int 0x12345678 to the short 0x5678), while others may not (e.g. converting the int 0x00000008 to the short 0x0008, or the long 0x0000000000000008).
Recall that values can have multiple types. If your situation is slightly different, and you only want to select a different one of the value’s types, casting is the tool for the job. Casting simply indicates that you wish to operate on a particular type that a value includes.
The difference at the code level varies from C# to IL. In C#, both casting and coercion look fairly similar:
static void ChangeTypes(int number, System.IO.Stream stream)
{
long longNumber = number;
short shortNumber = (short)number;
IDisposable disposableStream = stream;
System.IO.FileStream fileStream = (System.IO.FileStream)stream;
}
At the IL level they are quite different:
ldarg.0
conv.i8
stloc.0
ldarg.0
conv.i2
stloc.1
ldarg.1
stloc.2
ldarg.1
castclass [mscorlib]System.IO.FileStream
stloc.3
As for the logical level, there are some important differences. What’s most important to remember is that coercion creates a new value, while casting does not. The identity of the original value and the value after casting are the same, while the identity of a coerced value differs from the original value; coersion creates a new, distinct instance, while casting does not. A corollary is that the result of casting and the original will always be equivalent (both in identity and equality), but a coerced value may or may not be equal to the original, and never shares the original identity.
It’s easy to see the implications of coercion in the examples above, as the numeric types are always copied by value. Things get a bit trickier when you’re working with reference types.
class Name : Tuple<string, string>
{
public Name(string first, string last)
: base(first, last)
{
}
public static implicit operator string[](Name name)
{
return new string[] { name.Item1, name.Item2 };
}
}
In the example below, one conversion is a cast, while the other is a coercion.
Tuple<string, string> tuple = name;
string[] strings = name;
After these conversions, tuple and name are equal, but strings is not equal to either of them. You could make the situation slightly better (or slightly more confusing) by implementing Equals() and operator ==() on the Name class to compare a Name and a string[]. These operators would “fix” the comparison issue, but you would still have two separate instances; any modification to strings would not be reflected in name or tuple, while changes to either one of name or tuple would be reflected in name and tuple, but not in strings.
Although the example above was meant to illustrate some differences between casting and coercion, it also serves as a great example of why you should be extremely cautious about using conversion operators with reference types in C#.

C# - Issues with boxing / unboxing / typecasting ints. I don't understand

I'm having a hard time understanding this. Consider the following example:
protected void Page_Load(object sender, EventArgs e)
{
// No surprise that this works
Int16 firstTest = Convert.ToInt16(0);
int firstTest2 = (int)firstTest;
// This also works
object secondTest = 0;
int secondTest2 = (int)secondTest;
// But this fails!
object thirdTest = Convert.ToInt16(0);
int thirdtest2 = (int)thirdTest; // It blows up on this line.
}
The specific error that I get at runtime is Specified cast is not valid. If I QuickWatch (int)thirdTest in Visual Studio, I get a value of Cannot unbox 'thirdTest' as a 'int'.
What the heck is going on here?
Unboxing checks the exact type as explained in the documentation.
Unboxing is an explicit conversion from the type object to a value
type or from an interface type to a value type that implements the
interface. An unboxing operation consists of:
Checking the object instance to make sure that it is a boxed value of
the given value type.
Copying the value from the instance into the value-type variable.
As you can see the first step is to check that the object instance matches the target type.
Also quote from the documentation:
For the unboxing of value types to succeed at run time, the item being
unboxed must be a reference to an object that was previously created
by boxing an instance of that value type. Attempting to unbox null
causes a NullReferenceException. Attempting to unbox a reference to an
incompatible value type causes an InvalidCastException.
So to fix this error make sure that the type matches before attempting to unbox:
object thirdTest = Convert.ToInt16(0);
short thirdtest2 = (short)thirdTest;
What's going on is exactly what it says.
In the first case, you have a short, unboxed, that you are then explicitly typecasting to an int. This is a valid conversion that the compiler knows how to do, so it works.
In the second case, you have an int, boxed, that are are assigning back to an int. This is a simple unboxing of an integer, which also valid, so it works.
In the third case, you have a short, boxed, that are you trying to unbox into a variable that is not a short. This isn't a valid operation: you can't do this in one step. This is not an uncommon problem, either: if you are using, for example, a SqlDataReader that contains a SMALLINT column, you cannot do:
int x = (int)rdr["SmallIntColumn"];
Either of the following should work in your third example:
object thirdTest = Convert.ToInt16(0);
int thirdTest2 = Convert.ToInt32(thirdTest);
int thirdTest3 = (int)(short)thirdTest;
Int16 is a fancy way to write short; there is no boxing/unboxing going on there, just the plain CLR conversion between 16-bit and 32-bit integers.
The second case boxes and unboxes to the same type, which is allowed: value type int gets wrapped in an object, and then gets unwrapped.
The third case tries to unbox to a different type (int instead of short) which is not allowed.

Casting, unboxing, conversion..?

Recently I am learning value types and I am bit confused. Also both casting and unboxing uses the same syntax - (expected type)(object), right?
And what about simple conversion between types, that is casting or just conversion?
int x = (int)2.5; //casting?
object a=x;
int Y=(int)a; //unboxing I think
Random r=new Random();
object X=r;
Random R=(Random)X; // casting
There's a lot of things to consider here, but let's tackle the simplest first:
What is the syntax (type)expression?
Well, in its basic form, it is considered casting. You cast the expression from one type, to another. That's it.
However, what exactly happens, that depends on the type, and a lot of other things.
If casting a value type to something else, you depend on one of the two types involved to declare a casting operator that handles this. In other words, either the value type need to define a casting operator that can cast to that other type, or that other type need to define a casting operator that can cast from the original type.
What that operator does, is up to the author of that operator. It's a method, so it can do anything.
Casting a value type to some other type gives you a different value, a separate value type, or a new reference type, containing the new data after casting.
Example:
int a = (int)byteValue;
Boxing and unboxing comes into play when you're casting a value type to and from a reference type, typically object, or one of the interfaces the value type implements.
Example:
object o = intValue; // boxing
int i = (int)o; // unboxing
Boxing also comes into play when casting to an interface. Let's assume that "someValueType" is a struct, which also implements IDisposable:
IDisposable disp = (IDisposable)someValueType; // boxed
Casting a reference type, can do something else as well.
First, you can define the same casting operators that were involved in value types, which means casting one reference type to another can return a wholly new object, containing quite different type of information.
Boxing does not come into play when casting a reference type, unless you cast a reference type back to a value type (see above.)
Example:
string s = (string)myObjectThatCanBeConvertedToAString;
Or, you can just reinterpret the reference, so that you still refer to the same object in question, but you are looking at it through a different pair of type glasses.
Example:
IDisposable disp = (IDisposable)someDisposableObject;
One important restriction on unboxing is that you can only unbox to the exact value-type(or its nullable equivalent) and not to another value-type the original value-type is convertible to.
int myInt = 1;
object x = myInt; // box
int unbox1 = (int)x; // successful unbox
int? unbox2 = (int?)x; // successful unbox
long unbox3 = (long)x; // error. Can't unbox int to long
long unbox4 = (long)(int)x; // works. First it unboxes to int, and then converts to long
Another interesting bit is that a nullable value-type gets boxed as its non nullable type, and can be unboxed as both the nullable and the non nullable type. Since a nullable that has the value null boxes to the reference null the information about its type is lost during the boxing.
A cast is one form of conversion, basically.
All the comments in your code are correct.
It's important to note the difference between a reference conversion and other conversions, however. The final conversion you've shown is a reference conversion - it maintains representational identity, so the values of X and R are both references to the same object.
Compare this with a double to int conversion (changes form significantly) and unboxing (copies the value from inside the box to the variable).
The difference is important for some topics such as generic variance - that only works with reference types because of the reference conversions available. Basically the CLR checks that it all the types are appropriate, and then runs the appropriate code without ever having to perform any actual conversions on the references themselves.
Boxing and Unboxing specifically refer to casting value types to reference types and back again. Check out this link for more Boxing and Unboxing (C# Programming Guide).
Boxing and unboxing is done behind the scenes by compiler. So correct comments would be
int x = (int)2.5; //casting with conversion
object a=x; //casting with boxing
int Y=(int)a; //casting with unboxing
Random r=new Random();
object X=r;
Random R=(Random)X; //casting without unboxing
about casting vs conversion check this question: What is the difference between casting and conversion?

Categories

Resources