Boxing Occurrence in C#

后端 未结 5 1091
清歌不尽
清歌不尽 2020-11-30 18:15

I\'m trying to collect all of the situations in which boxing occurs in C#:

  • Converting value type to System.Object type:

    struct          
    
    
            
5条回答
  •  清歌不尽
    2020-11-30 18:45

    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

提交回复
热议问题