c# - Why is class copied instead of referenced? -


i've been trying figure out time why copy of data , reference. found out reference types , value types. life changed , started using info when coding.

now making custom editor in unity. have ability class, contains buff list (list of buff classes). each ability have can contain multiple buffs.

when editing ability variables in database, first copy of ability using not edit them directly edit copy , save copy database when done. still seem make copies 1 line , not other. seems not referencing reference type making behave value type. don't understand why is.

//this constructor used make copy of existing ability in database public ability(ability clonefrom) {     buffs = new list<buff>();      //this work, not cause reference takes copy.     //i don't understand because using add()on class (reference type)     (int x = 0; x < clonefrom.buffs.count; x++)         buffs.add(clonefrom.buffs[x]);      //this create reference expected     buffdata = clonefrom.buffdata; } 

the thing imagine list.add() makes copy, haven't been able confirm.

really quick, make sure understand difference between class , object. class cookie cutter; object cookie.

i think ron beyer (from comments) hit nail on head -- you're saying want keep lists in sync buffs of 1 ability object stay in sync ability object.

this work if assign 1 object's buffs another's.

if call add, you'll reference buff, new buffs not added.

you mentioned value vs reference types; quick list follows (someone jump in here , correct me)

value types

  • primitive types (int, float, long, double, bool, etc.)
  • structs
  • enum

reference types

  • classes
  • delegates
  • interfaces
  • object

there 1 case should aware of:

public class ability {     public int score { get; set; }      public ability(int score) {         score = score;     } }   public static void killreference(ability ability) {     // when execute next line, ability     // original scope stay same     ability = new ability(2); }  public static void main() {     ability ability = new ability(5);      killreference(ability);      // ability.score still 5 } 

ohgodwhy

when pass reference type function, you're passing "copy" of reference (this same pointers in c/c++)...you're effective passing reference value (confusing, right?).

when assign reference object, original object referenced no longer referenced variable -- there's new variable , changes ability directed @ new variable (which cleared heap once exit function's scope).

hope helps!


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -