c# - Declare variable as one type then override with "new" to another type -


apologies couldn't think of better way describe in title. i'm not real developer please excuse if fields, variables, objects , methods confused.

anyway have c# code declares private variable class, that's available throughout entire class. within code decide declared as. when jump method of capabilities of object/variable not available due original declaration.

private netpeer _peer; //initially declared here it's visible in entire class .... public void initialise() {   if("some arbitrary validation")    {     _peer = new netserver(_config); // netserver object , not netpeer, works fine   }   else   {     _peer = new netclient(_config); // netclient object , not netpeer, works fine   }   _peer.start(); // works fine netclient or netserver. method available both }  public void sendit() {   _peer.sendtoall(_message); //now "sendtoall" available netserver , not netclient. @ runtime fails miserably expect } 

so there way declare private "_peer" variable without defining netserver or netclient till later on, or need revisit rest of code , run 2 separate variables.

it's not overtly relevant issue, i'm using lidgren library netserver , netclient come from. suppose other class or method being referenced here.

i've removed lot of other logic , code show example.

**edit: didn't realise asking generic question kick off such battle. code working fine , i've used suggestion damien that's simplest me understand: ((netserver)_peer).sendtoall(_message);

thanks offered positive issue...

you can write like:

public void sendit() {   var server = _peer netserver;   if(_peer == null) throw new invalidoperationexception("sendit called when we're not server");   server.sendtoall(_message); } 

and in other methods work 1 type or other. have left out if(_peer ... line, have left nullreferenceexception - prefer switch more meaningful exception type , @ same time able provide hint on what, specifically, went wrong.

similarly, have done direct cast ((netserver)_peer).sendtoall(... have thrown invalidcastexception take more digging diagnose issue. prefer use as , try offer rich diagnostic experience possible.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -