user1618825
user1618825

Reputation:

Boxing and Unboxing with Generic Collections

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
}

Upvotes: 3

Views: 1198

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65087

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.

Upvotes: 3

Related Questions