Changes

Jump to navigation Jump to search
→‎Net types: simplify null caveat example
Line 11: Line 11:  
Usage notes:
 
Usage notes:
 
<ul>
 
<ul>
 +
<li>Many net fields have a standard property to access them. Use those when possible to simplify your code and avoid net field gotchas:
 +
<source lang="c#">
 +
Game1.player.name // NetString
 +
Game1.player.Name // string
 +
</source>
 +
</li>
 
<li>You can implicitly cast net types to their standard equivalent:
 
<li>You can implicitly cast net types to their standard equivalent:
 
<source lang="c#">
 
<source lang="c#">
Line 25: Line 31:  
crop.dead.Set(true);
 
crop.dead.Set(true);
 
</source></li>
 
</source></li>
<li>Net types can't handle implicit casting for value types when using null-conditional operators. Always check for null before comparing or implicitly casting to a value type:
+
<li>Net types can't handle implicit casting on null net fields. Always check for null before comparing or implicitly casting to a value type:
 
<source lang="c#">
 
<source lang="c#">
Crop crop = null;
+
NPC villager = null;
   −
// all of these crash: 'System.NullReferenceException' in Netcode.dll
+
// crash: 'System.NullReferenceException' in Netcode.dll
bool deadA = crop?.dead;
+
if (villager?.name == "Abigail")
bool? deadB = crop?.dead;
  −
if (crop?.dead == true)
     −
// this are okay
+
// this is okay
if (crop?.dead != null && crop?.dead == true)
+
if (villager != null && villager.name == "Abigail")
 
</source></li>
 
</source></li>
 
</ul>
 
</ul>
translators
8,438

edits

Navigation menu