I\'m trying to collect all of the situations in which boxing occurs in C#:
Converting value type to System.Object type:
struct
Mentioned in Motti's answer, just illustrating with code samples:
Parameters involved
public void Bla(object obj)
{
}
Bla(valueType)
public void Bla(IBla i) //where IBla is interface
{
}
Bla(valueType)
But this is safe:
public void Bla(T obj) where T : IBla
{
}
Bla(valueType)
Return type
public object Bla()
{
return 1;
}
public IBla Bla() //IBla is an interface that 1 inherits
{
return 1;
}
Checking unconstrained T against null
public void Bla(T obj)
{
if (obj == null) //boxes.
}
Use of dynamic
dynamic x = 42; (boxes)
Another one
enumValue.HasFlag