3

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
    I don't think there is any `boxing` and `unboxing` here? Were they joking with you? `boxing` and `unboxing` would involve **value type**. All I can see is `generics stuff`, I think the code contains more than what you posted. – King King Sep 03 '13 at 04:03
  • 1
    Boxing doesn't apply in the code you posted. – Matthew Sep 03 '13 at 04:03
  • Oh! But i asked for the same. I thought that there may be something involved in the code. Does the code atleast involves any common techniques? –  Sep 03 '13 at 04:07
  • 1
    I believe that boxing only occurs when casting between `object` and a value type (like `DateTime`, `int`, `long`, etc.). This is a concept that a lot of .net developers talk about, but I have yet to run into an instance where it made a difference in the code I write. – Matthew Sep 03 '13 at 04:13
  • 1
    Generics are templates which can be used later, the simple Boxing and Un-boxing example will be int numValue = 1; object objRef = i; // boxing int numValue2 = (int) numValue; // unboxing – Hi10 Sep 03 '13 at 04:16
  • @SSS Your code example looks like it may be an implementation of the repository pattern, but as it stands right now, it's just one class inheriting another. – Matthew Sep 03 '13 at 04:20
  • @Matthew, Thanks and I am not sure whether this code follows repository pattern –  Sep 03 '13 at 04:27
  • @KingKing: You have mentioned that boxing and unboxing would involve value types. Does it so? What about var so = (TestClass)testClassObject; It involves unboxing a class which inturn is a reference type. – now he who must not be named. Sep 03 '13 at 06:11
  • @nowhewhomustnotbenamed. that's called **casting**, an `object` can hold reference to an instance of all the other classes because all classes inherit from `System.Object`. – King King Sep 03 '13 at 06:24
  • 1
    @KingKing: yup, you are right. Thanks for correcting up! – now he who must not be named. Sep 03 '13 at 06:54

1 Answers1

3

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.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138