OOPS Concepts: What is the difference in passing object reference to interface and creating class object in C#? -
i have class, customernew
, , interface, icustomer
:
public class customernew : icustomer { public void a() { messagebox.show("class method"); } void icustomer.a() { messagebox.show("interface method"); } public void b() { messagebox.show("class method"); } } public interface icustomer { void a(); }
i confused between these 2 code of lines.
icustomer objnew = new customernew(); customernew objcustomernew = new customernew(); objnew.b(); // why wrong? objcustomernew.b(); // correct because using object of class
the first line of code means passing object reference of customernew class in objnew
, correct? if yes, why can not access method b() of class interface objnew
?
can explain these 2 in detail.
actually interface type (you can't create instances of interfaces since they'are metadata).
since customernew
implements icustomer
, instance of customernew
can upcasted icustomer
. when customernew
typed icustomer
can access icustomer
members.
this because c# strongly-typed language, thus, in order access particular member (i.e. methods, properties, events...) need object reference qualified type defines members want access (i.e. need store customernew
object in reference of type customernew
access method b
).
update
op said:
so due upcasting can access methods inside interface, correct ? upcasting main reason behind ?
yes. easy explanation object implements icustomer
shouldn't mandatorily customernew
. need downcast icustomer
reference customernew
able access customernew
members.
as both classes , interfaces types, , c# strongly-typed language, access object members providing actual type. why need use casts.
for example, code implicit upcast:
// implicit cast that's equivalent // icustomer objnew = (icustomer)new customernew() icustomer objnew = new customernew();
implicit upcasts possible because compiler knows customernew
implements icustomer
introspecting customernew
metadata, while can't implictly-downcast icustomer
reference because knows implements icustomer
? can either customernew
or other class or struct:
icustomer asinterface = new customernew(); // error: won't compile, need provide explicit downcast customernew asclass1 = asinterface; // ok. you're telling compiler know asinterface // reference guaranteed customernew too! customernew asclass2 = (customernew)asinterface;
if you're not sure icustomer
customernew
, can use as
operator, won't throw exception during run-time if cast isn't possible:
// if asinterface isn't customernew, expression set null customernew asclass3 = asinterface customernew;
Comments
Post a Comment