Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Superclasses to C# Functions (With a Java overture)

It's been a while since I did anything with Java OOP, so I'm a bit rusty and wanted some clarification.

In Java, if I remember correctly, one could declare a superclass and instantiate a subclass; for example, Superclass myObject = new Subclass().

One could then pass myObject into a function that accepted a Superclass parameter, and access any Superclass properties/methods using the reference.

Here's where things get foggy - if you want to access Subclass-specific methods/variables, can you do that directly with myObject (which was declared as a Superclass) or do you need to cast it first to a Subclass type?

If we roll this over to C# now, does the same logic apply? I'm running into some weird issues trying to duplicate this behavior. The specific use case I'm looking at is:

//These are just declarations for ease-of-reading
Superclass bar = new Subclass();
public static void doSomething(Superclass foo) {...}

//Logic
doSomething(bar);
bar.superOnly() //Should this work?
bar.subOnly() //Should this work?
bar.subOverrided() //Will this call the superclass or subclass version?

I'm looking up this stuff in tutorials as well, but most examples seem to be simple "Subclass myObject = new Subclass()" instances with trivial output. Nothing I've found so far covers the nebulous world of function parameters.

If anyone can help me out, or point me to a specific resource that covers function parameters and OO in C#, I would greatly appreciate it!

like image 303
sichinumi Avatar asked Aug 09 '26 05:08

sichinumi


1 Answers

Here's where things get foggy - if you want to access Subclass-specific methods/variables, can you do that directly with myObject (which was declared as a Superclass) or do you need to cast it first to a Subclass type?

Yes, that's what polymorphism is for. Virtual methods of the base class that are overridden in the derived class will always be called, even if you call the method through a reference of the base type.

If we roll this over to C# now, does the same logic apply?

Yes, the principle is the same

As for your example:

bar.superOnly() //Should this work?

Yes

bar.subOnly() //Should this work?

No, because the compiler wouldn't know about this method

bar.subOverrided() // Will this call the superclass or subclass version? => the subclass

Yes, thanks to polymorphism

like image 186
Thomas Levesque Avatar answered Aug 11 '26 19:08

Thomas Levesque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!