Confusion regarding boxing of value types - c#

In the following code...
int i=5;
object o = 5;
Console.WriteLine(o); //prints 5
I have three questions:
1) What additional/useful functionality is acquired by the 5 residing in the variable o that the 5 represented by the variable i does not have ?
2) If some code is expecting a value type then we can just pass it the int i , but if its expecting a reference type , its probably not interested in the 5 boxed in o anyway . So when are boxing conversions explicitly used in code ?
3) How come the Console.WriteLine(o) print out a 5 instead of System.Object ??

What additional/useful functionality is acquired by the 5 residing in the variable o that the 5 represented by the variable i does not have ?
It's rare that you want to box something, but occasionally it is necessary to do so. In older versions of .NET boxing was often necessary because some methods only worked with object (e.g. ArrayList's methods). This is much less of a problem now that there is generics, so boxing occurs less frequently in newer code.
If some code is expecting a value type then we can just pass it the int i, but if its expecting a reference type, its probably not interested in the 5 boxed in o anyway . So when are boxing conversions explicitly used in code ?
In practice boxing usually happens automatically for you. You could explicitly box a variable if you want to make it more clear to the reader of your code that boxing is happening. This might be relevant if performance could be an issue.
How come the Console.WriteLine(o) print out a 5 instead of System.Object ??
Because ToString is a virtual method on object which means that the implementation that is called depends on the runtime type, not the static type. Since int overrides ToString with its own implementation, it is int.ToString that is called, not the default implementation provided by object.
object o = 5;
Console.WriteLine(o.GetType()); // outputs System.Int32, not System.Object

1) On its own, there is not much point. But imagine you wish to store something in a generic way, and you don't know whether that thing is a value or an object. With boxing, you can convert the value into an object, and then treat everything as an object. Wihtout it, you would need a special case to be able to hold a value or an object. (THis is most useful in containers such as lists, allowing you to mix values like 5 with references to objects like a FileStream).
2) Boxing conversions usually only happen implicitly, except in example code illustrating boxing.
3) The WriteLine code probably calls the virtual Object.ToString() method. If the class of the Object it calls this on does not override ToString, then it will call the base class (object) implementation, but most types (including System.Int although int is a value type, it is still derived from System.Object) override this to provide a more useful context-specific result.

What additional/useful functionality is acquired by the 5 residing in the variable o that the 5 represented by the variable i does not have ?
There is no additional functionality acquired by a boxed value type, apart from the fact that it can be passed by referenced to code that requires that.
So when are boxing conversions explicitly used in code ?
I can't spontaneously think of a scenario when you would need to explicitly box an int to an object, since there is always an implicit conversion in that direction (although I would not be surprised if there are cases when an explicit conversion is required).
How come the Console.WriteLine(o) print out a 5 instead of System.Object ??
It calls ToString on the object passed. In fact, it starts by trying to convert the object to an IFormattable and, if successful (which it will be in the case of an int) then calls the ToString overload that is defined in that interface. This will return "5".

Additional functionality: The object is a full-fledged object. You can call methods on it and use it as you would any other object:
System.Console.WriteLine("type: {0}", o.GetType());
System.Console.WriteLine("hash code: {0}", o.GetHashCode());
The int variable is a value type, not an object.
XXX: This is incorrect; see comments. I would venture instead that the one difference in how you might use the two is that object o = 5 is nullable (you can set o = null), while the value type is not - if int i = 5, then i is always an int.
Explicit boxing: As you said, the boxed version is used by coding manipulating objects as objects rather than integers in particular. This is what enables non-type-safe generic data structures. Now that type-safe generic data structures are available, you are unlikely to be doing much casting and boxing/unboxing.
Why "5": Because the object knows how to print itself using ToString().

Related

Which is the best practice in C# for type casting? [duplicate]

This question already has answers here:
Direct casting vs 'as' operator?
(16 answers)
Difference between is and as keyword
(13 answers)
Closed 7 years ago.
Which method is best practice to type casting and checking ?
Employee e = o as Employee;
if(e != null)
{
//DO stuff
}
OR
if(o is Employee)
{
Employee e = (Employee) o;
//DO stuff
}
At least there are two possibilities for casting, one for type checking and a combination of both called pattern matching. Each has its own purpose and it depends on the situation:
Hard cast
var myObject = (MyType)source;
You normally do that if you are absolutely sure if the given object is of that type. A situation where you use it, if you subscribed to an event handler and you cast the sender object to the correct type to work on that.
private void OnButtonClick(object sender, EventArgs e)
{
var button = (Button)sender;
button.Text = "Disabled";
button.Enabled = false;
}
Soft cast
var myObject = source as MyType;
if (myObject != null)
// Do Something
This will normally be used if you can't know if you really got this kind of type. So simply try to cast it and if it is not possible, simply give a null back. A common example would be if you have to do something only if some interface is fullfilled:
var disposable = source as IDisposable;
if(disposable != null)
disposable.Dispose();
Also the as operator can't be used on a struct. This is simply because the operator wants to return a null in case the cast fails and a struct can never be null.
Type check
var isMyType = source is MyType;
This is rarely correctly used. This type check is only useful if you only need to know if something is of a specific type, but you don't have to use that object.
if(source is MyType)
DoSomething();
else
DoSomethingElse();
Pattern matching
if (source is MyType myType)
DoSomething(myType);
Pattern matching is the latest feature within the dotnet framework that is relevant to casts. But you can also handle more complicated cases by using the switch statement and the when clause:
switch (source)
{
case SpecialType s when s.SpecialValue > 5
DoSomething(s);
case AnotherType a when a.Foo == "Hello"
SomethingElse(a);
}
I think this is a good question, that deserves a serious and detailed answer. Type casts is C# are a lot of different things actually.
Unlike C#, languages like C++ are very strict about these, so I'll use the naming there as reference. I always think it's best to understand how things work, so I'll break it all down here for you with the details. Here goes:
Dynamic casts and static casts
C# has value types and reference types. Reference types always follow an inheritance chain, starting with Object.
Basically if you do (Foo)myObject, you're actually doing a dynamic cast, and if you're doing (object)myFoo (or simply object o = myFoo) you're doing a static cast.
A dynamic cast requires you to do a type check, that is, the runtime will check if the object you are casting to will be of the type. After all, you're casting down the inheritance tree, so you might as well cast to something else completely. If this is the case, you'll end up with an InvalidCastException. Because of this, dynamic casts require runtime type information (e.g. it requires the runtime to know what object has what type).
A static cast doesn't require a type check. In this case we're casting up in the inheritance tree, so we already know that the type cast will succeed. No exception will be thrown, ever.
Value type casts are a special type of cast that converts different value types (f.ex. from float to int). I'll get into that later.
As, is, cast
In IL, the only things that are supported are castclass (cast) and isinst (as). The is operator is implemented as a as with a null check, and is nothing more than a convenient shorthand notation for the combination of them both. In C#, you could write is as: (myObject as MyFoo) != null.
as simply checks if an object is of a specific type and returns null if it's not. For the static cast case, we can determine this compile-time, for the dynamic cast case we have to check this at runtime.
(...) casts again check if the type is correct, and throw an exception if it's not. It's basically the same as as, but with a throw instead of a null result. This might make you wonder why as is not implemented as an exception handler -- well, that's probably because exceptions are relatively slow.
Boxing
A special type of cast happens when you box a value type into an object. What basically happens is that the .NET runtime copies your value type on the heap (with some type information) and returns the address as a reference type. In other words: it converts a value type to a reference type.
This happens when you have code like this:
int n = 5;
object o = n; // boxes n
int m = (int)o; // unboxes o
Unboxing requires you to specify a type. During the unboxing operation, the type is checked (like the dynamic cast case, but it's much simpler because the inheritance chain of a value type is trivial) and if the type matches, the value is copied back on the stack.
You might expect value type casts to be implicit for boxing -- well, because of the above they're not. The only unboxing operation that's allowed, is the unboxing to the exact value type. In other words:
sbyte m2 = (sbyte)o; // throws an error
Value type casts
If you're casting a float to an int, you're basically converting the value. For the basic types (IntPtr, (u)int 8/16/32/64, float, double) these conversions are pre-defined in IL as conv_* instructions, which are the equivalent of bit casts (int8 -> int16), truncation (int16 -> int8), and conversion (float -> int32).
There are some funny things going on here by the ways. The runtime seems to work on multitudes of 32-bit values on the stack, so you need conversions even on places where you wouldn't expect them. For example, consider:
sbyte sum = (sbyte)(sbyte1 + sbyte2); // requires a cast. Return type is int32!
int sum = int1 + int2; // no cast required, return type is int32.
Sign extension might be tricky to wrap your head around. Computers store signed integer values as 1-complements. In hex notation, int8, this means that the value -1 is 0xFF. So what happens if we cast it to an int32? Again, the 1-complement value of -1 is 0xFFFFFFFF - so we need to propagate the most significant bit to the rest of 'added' bits. If we're doing unsigned extensions, we need to propagate zero's.
To illustrate this point, here's a simple test case:
byte b1 = 0xFF;
sbyte b2 = (sbyte)b1;
Console.WriteLine((int)b1);
Console.WriteLine((int)b2);
Console.ReadLine();
The first cast to int is here zero extended, the second cast to int is sign extended. You also might want to play with the "x8" format string to get the hex output.
For the exact difference between bit casts, truncation and conversion, I refer to the LLVM documentation that explains the differences. Look for sext/zext/bitcast/fptosi and all the variants.
Implicit type conversion
One other category remains, and that's the conversion operators. MSDN details how you can overload the conversion operators. Basically what you can do is implement your own conversion, by overloading an operator. If you want the user to explicitly specify that you intend to cast, you add the explicit keyword; if you want implicit conversions to happen automagically, you add implicit. Basically you'll get:
public static implicit operator byte(Digit d) // implicit digit to byte conversion operator
{
return d.value; // implicit conversion
}
... after which you can do stuff like
Digit d = new Digit(123);
byte b = d;
Best practices
First off, understand the differences, which means implementing small test programs until you understand the distinction between all of the above. There's no surrogate for understanding How Stuff Works.
Then, I'd stick to these practices:
The shorthands are there for a reason. Use the notation that's the shortest, it's probably the best one.
Don't use casts for static casts; only use casts for dynamic casts.
Only use boxing if you need it. The details of this go well beyond this answer; basically what I'm saying is: use the correct type, don't wrap everything.
Notice compiler warnings about implicit conversions (f.ex. unsigned/signed) and always resolve them with explicit casts. You don't want to get surprises with strange values due to sign/zero extension.
In my opinion, unless you know exactly what you're doing, it's best to simply avoid the implicit/explicit conversion -- a simple method call is usually better. The reason for this is that you might end up with an exception on the loose, that you didn't see coming.
With the second method, if the cast fails an exception is thrown.
When casting using as, you can only use reference types. so if you are typecasting to a value type, you must still use int e = (int) o; method.
a good rule of thumb, is : if you can assign null as a value to the object, you can type cast using as.
that said, null comparison is faster than throwing and catching an exception, so in most cases, using as should be faster.
I can't honestly say with certainty if this applies with your is check in place though. It could fail under some multi threading conditions where another thread changes the object you're casting.
I would use the as (safe-cast) operator if I need to use the object after casting. Then I check for null and work with the instance. This method is more efficient than is + explicit cast
In general, the as operator is more efficient because it actually returns the cast value if the cast can be made successfully. The is operator returns only a Boolean value. It can therefore be used when you just want to determine an object's type but do not have to actually cast it.
(more information here).
I am not sure about it but I think that is is using as under the hood and just returns if the object after casting is null (in case of reference types) / an exception was thrown (in case of value types) or not.
Well, it's a matter of taste and specifics of problem that you're dealing with. Let's have a look at two examples with generic methods.
For generic method with 'class' constraint (the safest approach with double cast):
public void MyMethod<T>(T myParameter) where T : class
{
if(myParameter is Employee)
{
// we can use 'as' operator because T is class
Employee e = myParameter as Employee;
//DO stuff
}
}
Also you can do someting like this (one cast operation here but defined variable of type that may or may not be correct) :
public void MyMethod<T>(T myParameter) where T : class
{
Employee e;
if((e = myParameter as Employee) != null)
{
//DO stuff with e
}
}
For generic method with 'struct' constraint :
public void MyMethod<T>(T myParameter) where T : struct
{
if(myParameter is int)
{
// we cant use 'as' operator here because ValueType cannot be null
// explicit conversion doesn't work either because T could be anything so :
int e = Convert.ToInt32(myParameter);
//DO stuff
}
}
Simple scenario with explicit cast:
int i = 5;
object o = (object)i; // boxing
int i2 = (int)o; // unboxing
We can use explicit cast here because we are 100% sure of what types do we use.

Repeated boxing makes different references?

I try to understand this code:
double b = 3;
object o = b;
Console.WriteLine(o.Equals(3));//false
Console.WriteLine(o.Equals(b));//true
Console.WriteLine( o == (object)b );//false
Each new boxing makes different references of object b?
If 1. is true, why o.Equals(b) is true?
If Equals does not check references, why o.Equals(3) is false?
Thanks.
Yes, each time you box a value type, a new object is created. More on boxing here.
Equals check for value equality, not reference equality. Both o and b are the same: a double with a value of 3.0.
3 here is an int, not a double, and Equals for different types doesn't do any conversion to make them compatible, like the compiler is usually doing. o.Equals(3.0) will return true.
double b = 3;
creates a new variable in stack with value 3
object o = b;
creates an object in the heap which reference the same place of b in the stack so you have the same variable with two references this is boxing
o.Equals(3)
is false because it creates a new anonymous variable with value 3 not b
o.Equals(b)
is true because it's the same variable
o == (object)b
is false because == is comparing references in memory addresess but Equals compares the value of the variable itself
See this
It explains all about equals behavior.
Every time an effort is made to convert a value type into a reference type, it must be boxed to a new object instance. There is no way the system could do anything else without breaking compatibility. Among other things, while one might expect that boxed value types would be immutable(*), none of them are. Every value type, when boxed, yields a mutable object. While C# and vb.net don't provide any convenient way to mutate such objects, trusted and verifiable code written in C++/CLI can do so easily. Even if the system knew of a heap object that holds an Int32 whose value is presently 23, the statement Object foo = 23; would have to generate a new Int32 heap object with a value of 23, since the system would have no way of knowing whether something might be planning to change the value of that existing object to 57.
(*)I would argue that they should be; rather than making all boxed objects mutable, it would be much better to provide a means by which struct types like List<T>.Enumerator could specify customizable boxing behavior. I'm not sure if there's any way to fix that now without totally breaking compatibility with existing code, though.

Which is more correct in the sense of performance

I have one question..
Which has more effective performance? Or which take less time to execute and Why?
session["var"].ToString()
or
(string)session["var"]
ToString() is a method and (string) is casting (Explicit). IMO casting is always fast
A cast operation between reference types does not change the run-time
type of the underlying object; it only changes the type of the value
that is being used as a reference to that object.
Source: Explicit Conversions
.ToString() can be called from any object. This method is inherited from object class and can be overloaded
.(string) is a cast, Its not a function call. It should be used when it is sure that the object is already in string, it will throw an exception when it can't convert to string including null
Depends on the type of object this session var is, if you know it is a string, option 2 is best.
The latter performs better, simply casting the value to a different type. The former involves a method call and/or a new object creation.
These 2 calls are performing very different actions (unless you knwow for sure that the value is string). So asking which one is faster is not completely correct.
There are arguments both ways which one will be faster since both operations require call to a function. The right approach is to prototype and measure.
Note that it is unlikley that accessing data from Session will be your main performance botleneck (especially in case of SQL or other out-of-process session state).
ToString() raise exception when the object is null. So in the case of object.ToString(), if object is null, it raise NullReferenceException. Convert.ToString() return string.Empty in case of null object. (string) cast assign the object in case of null. So in case of
MyObject o = (string)NullObject;
But when you use o to access any property, it will raise NullReferenceException.
Convert.ToString internally uses value.ToString. Casting to a String is cheaper since that doesn't require an external function call, just internal type checking. It is at least twice as fast to cast Object to String than to call Object.toString()

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#.

Boxing and unboxing: when does it come up?

So I understand what boxing and unboxing is. When's it come up in real-world code, or in what examples is it an issue? I can't imagine doing something like this example:
int i = 123;
object o = i; // Boxing
int j = (int)o; // Unboxing
...but that's almost certainly extremely oversimplified and I might have even done boxing/unboxing without knowing it before.
It's much less of an issue now than it was prior to generics. Now, for example, we can use:
List<int> x = new List<int>();
x.Add(10);
int y = x[0];
No boxing or unboxing required at all.
Previously, we'd have had:
ArrayList x = new ArrayList();
x.Add(10); // Boxing
int y = (int) x[0]; // Unboxing
That was my most common experience of boxing and unboxing, at least.
Without generics getting involved, I think I'd probably say that reflection is the most common cause of boxing in the projects I've worked on. The reflection APIs always use "object" for things like the return value for a method - because they have no other way of knowing what to use.
Another cause which could catch you out if you're not aware of it is if you use a value type which implements an interface, and pass that value to another method which has the interface type as its parameter. Again, generics make this less of a problem, but it can be a nasty surprise if you're not aware of it.
Boxing (in my experience) usually occurs in these cases:
A value type is passed to a method that accepts an argument of type Object.
A value type is added to a non-generic collection (like an ArrayList).
Other times you can see boxing and unboxing is when you use reflection as the .NET framework's reflection API makes heavy use of Object.
Boxing/unboxing occurs when a value type (like a struct, int, long) is passed somewhere that accepts a reference type - such as object.
This occurs when you explicitly create a method that takes parameters of type object that will be passed value types. It also comes up when you use the older non-generic collections to store value types (typically primitives).
You will also see boxing occuring when you use String.Format() and pass primitives to it. This is because String.Format() accepts a params object[] - which results in boxing of the additional parameters in the call.
Using reflection to invoke methods can also result in boxing/unboxing, because the reflection APIs have no choice but to return object since the real type is not known at compile time (and the Reflection APIs cannot be generic).
The newer generic collections do not result in boxing/unboxing, and so are preferable to the older collections for this reason (eg ArrayList, Hashtable, etc). Not to mention they are typesafe.
You can avoid boxing concerns by changing methods that accept objects to be generic. For example:
public void string Decorate( object a ) // passing a value type results in boxing
{
return a.ToString() + " Some other value";
}
vs:
public void string Decorate<T>( T a )
{
return a.ToString() + " some other value";
}
Here is a really nasty one :)
SqlCommand cmd = <a command that returns a scalar value stored as int>;
// This code works very well.
int result = (int)cmd.ExecuteScalar();
// This code will throw an exception.
uint result = (uint)cmd.ExecuteScalar();
The second execute fails because it tries to unbox an Int32 into an UInt32 which is not possible. So you have to unbox first and than cast.
uint result = (uint)(int)cmd.ExecuteScalar();
Boxing and unboxing is really moving from value type to reference type. So, think of it as moving from the stack to the heap and back again.
There certainly are cases where this is relevant. The inclusion of generics in the 2.0 framework cut a lot of common boxing cases out of practice.
It happens all the time when people do not know what the implications are, simply don't care or sometimes one cannot help but accept boxing as the lesser evel.
Strongly typed datarows will box/unbox pretty much all the time when you access a value-type property.
Also, using a value type as an interface reference will box it as well. Or getting a delegate from an instance method of a value type. (The delegate's target is of type Object)
Since the advent of strongly-typed lists and dictionaries using generics with C# 2.0 (Visual Studio 2005), I think the importance of keeping boxing/unboxing in mind have been amazingly minimized. Add to that nullable types (int?, etc.) and using the null coalescing operator (??) and it really shouldn't be much of a concern at all and would likely not see it in any code that's not 1.1 Framework or earlier.
"The type parameter for an ArrayList must be a class, not a primitive type, so Java provides wrapper classes for the primitive types, like "Integer" for int, "Double" for double, etc.
For more explanation:
An array is a numbered sequence of elements, and each element acts like a separate variable."
Java provides a special syntax for "for" loops over the elements of arrays (and other collection types in Java). The simplified syntax is called a "for-each" loop. For example, the following statement prints each String in an array called "words".
for (String word : words) System.out.println(word);
An array has a number of elements that are set when the array object is created and cannot be changed. Java provides the "ArrayList" class for the functionality of a dynamic array, an array that can change in size. ArrayList is an example of a parameterized type, a type that depends on another type." Eck (2019)
References :
Introduction to Programming Using Java, Eck (2019) describes as follows in Chapter 7

Categories

Resources