0

I've come across a struct in legacy code that I feel should be redefined as a class. It doesn't fit the general guidelines for choosing between a class and a struct.

While I'm in here, I would like to better understand if a struct that contains methods with reference type parameters, such as an interface, are in any case possibly less efficient due to boxing and unboxing?

My understanding is that value types are boxed when cast to a reference type or to an interface they implement, and unboxed when cast back to a value type, but I am unclear about the implications of using reference types within methods of a struct.

Given a struct and a static class:

public struct Foo {
    public static string ResolveSomething(IBar someInterface, int baz) {
        return someInterface.Calculate(baz);
    }
}

public static class FooClass {
    public static string ResolveSomething(IBar someInterface, int baz) {
        return someInterface.Calculate(baz);
    }
}

Does the following use of the struct vs. class have any general implications with regards to memory use?

Foo.ResolveSomething(someImplementation, 2);
FooClass.ResolveSomething(someImplementation, 2);
Wes Doyle
  • 2,199
  • 3
  • 17
  • 32
  • 2
    Reference types won't be "boxed" as they already live on the heap, so no such operation is necessary. – Lasse V. Karlsen Jul 02 '21 at 20:22
  • 1
    In short, no, it doesn't matters if a method is on a struct or a class. Boxing only matters when considering the variable type (or parameter, or field, or property) and which type of object you put in it, as you described it. Everything else is irrelevant. – Alejandro Jul 02 '21 at 20:38

1 Answers1

0

Reference types can't be boxed, only value types may. I don't think the allocation of memory for local variables and parameters within a method has anything to do with whether the method is declared in a reference type or value type.

Joe Sewell
  • 6,067
  • 1
  • 21
  • 34