c# - When to use value and reference types for immutable types? (.NET) -


with mutable types, difference in behaviour between value , reference types clear:

// mutable value type pointmutstruct pms1 = new pointmutstruct(1, 2); pointmutstruct pms2 = pms1; // pms1 == (1, 2); pms2 == (1, 2); pms2.x = 3; mutatestate(pms1); // changes x property 4. // pms1 == (1, 2); pms2 == (3, 2);  // mutable reference type pointmutclass pmc1 = new pointmutclass(1, 2); pointmutclass pmc2 = pmc1; // pmc1 == (1, 2); pmc2 == (1, 2); pmc2.x = 3; mutatestate(pmc1); // changes x property 4. // pmc1 == (4, 2); pmc2 == (4, 2); 

with immutable types however, difference less clear cut:

// immutable value type pointimmstruct pis1 = new pointimmstruct(1, 2); pointimmstruct pis2 = pis1; // pis1 == (1, 2); pis2 == (1, 2); pis2 = new pointimmstruct(3, pis2.y); // can't mutate pis1 // pis1 == (1, 2); pis2 == (3, 2);  // immutable reference type pointimmclass pic1 = new pointimmclass(1, 2); pointimmclass pic2 = pic1; // pic1 == (1, 2); pic2 == (1, 2); pic2 = new pointimmclass(3, pic2.y); // can't mutate pic1 either // pic1 == (1, 2); pic2 == (3, 2); 

immutable reference types use value semantics (e.g. canonical example system.string):

string s1 = generateteststring(); // generate identical non-interned strings string s2 = generateteststring(); // dynamically creating them // object.referenceequals(stra, strb)) == false; // stra.equals(strb) == true // stra == strb 

eric lippert has discussed before on blog (e.g. here) fact value types (when doesn't matter discussion) allocated on stack implementation detail , shouldn't dictate whether make object value or reference type.

given blurred distinction in behaviour immutable types, criteria leave decide whether make immutable type reference type or value type?

also, immutable emphasis on values vs variables, should immutable types implement value semantics?

i eric's blog post link gives answer:

i regret documentation not focus on relevant; focusing on largely irrelevant implementation detail, enlarge importance of implementation detail , obscure importance of makes value type semantically useful. dearly wish articles explaining “the stack” instead spend time explaining “copied value” means , how misunderstanding or misusing “copy value” can cause bugs.

if objects should have "copy-by-value" semantic, make them value types. if should have "copy-by-reference" semantic, make them reference types.

he says this, agree with:

i’d make choice of value type vs reference type based on whether type semantically representing value or semantically reference something.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -