c# - IS vs. AS vs. IsAssignableFrom - What are the differences when checking for objectTypes and Interfaces? -
i'm sort of new c# , wondering if me out.
the scenario:
public bool objectimplementsspecificinterface (object obj) { // 1. if (obj iexampleinterface) { return true; } // 2. var tmp = obj iexampleinterface; if (tmp != null) { return true; } // 3. if (typeof(iexampleinterface).isassignablefrom (obj.gettype ())) { return true; } }
the goal: determine wether object o implements given interface-definition iexampleinterface
or not.
the questions:
- which implementation best practice?
- disregarding first question, 1 technically correct?
- what specific differences in operators? msdnaa isn't detailed on them.
- which call takes longest / shortest?
- var impinterface = obj isampleinterface;
- what mean "technically" ? work. if want ois know whether implments interface, that's
is
for. if want new variable cast interface, useas
. is
determines if object derives type , returns boolean.as
attempts cast object type, , return new variable cast type, or null if cannot. (but know question).as
should take longer, if cast works.
Comments
Post a Comment