Boxing and Unboxing with Generic Collections

1.1k views Asked by At

In interview i had been asked for Boxing and Unboxing and i explained it. After that i asked for Generic Collections. I explained the below code and from here they asked how boxing operation applied here in the below code. I am not sure about this answer.

public abstract class DataAccess<T, TKey>
{
   --CRUD Operations here
}

public class AdminDataAccess : DataAccess<Admin, long>
{
    --code here
}
1

There are 1 answers

1
Simon Whitehead On BEST ANSWER

There is no boxing. Boxing does not apply to generic type parameters. It only applies when they are actually used in code and are actually boxed/unboxed by said code.

EDIT: ..an example, although I think I explained it fairly well..

This will box:

public abstract class DataAccess<T, TKey> where TKey : struct {
    private object _boxedKey;

    private void DoSomething(TKey key) {
        _boxedKey = key;
    }
}

Without some code forcefully boxing/unboxing a value type, your generic type parameters don't have anything to do with boxing or unboxing.