KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I would like to create a type in C# with value like semantics. It is immutable and it has a low memory footprint. However, it is mostly going to be accessed via an interface it implements. In this case, a value type would have to be boxed which means that the actual value would have to be copied from the stack to the heap. Therefore I wonder if there is any advantage at all in using a value type (struct) instead of a reference type (class)? To illustrate my situation, I provide the following example of an interface I with implementations ReferenceTypeImplementation and ValueTypeImplementation : interface I { int GetSomeInt(); } class ReferenceTypeImplementation : I { public readonly int i; public ReferenceTypeImplementation (int i) { this.i = i; } public int GetSomeInt() { return i*2; } } struct ValueTypeImplementation : I { public readonly int i; public ValueTypeImplementation (int i) { this.i = i; } public int GetSomeInt() { return i*2; } } I would almost exclusively use these type using the interface I like I i1 = new ReferenceTypeImplementation(1); I i2 = new ValueTypeImplementation(1); Is there any advantage in using ValueTypeImplementation over ReferenceTypeImplementation ?
Tags (comma-separated)
Save Edits
Cancel