Results 1 to 3 of 3
Thread: Typecasting in C#
-
2017-10-27, 03:07 PM (ISO 8601)
- Join Date
- Aug 2009
Typecasting in C#
For some reason typecasting doesn't seem to work like it does in other languages.
Maybe I'm just missing something.
Consider the following set-up:
Code:public class BaseClass { } public class DerivativeClass : BaseClass { public void DoStuff(){ //do stuff } }
Code:public void CallingContext(BaseClass anObject){ if (anObject is DerivativeClass){ (DerivativeClass)anObject.DoStuff; } }
Instead, C# forces the following construct:
Code:public void CallingContext(BaseClass anObject){ if (anObject is DerivativeClass){ DerivativeClass dummy = (DerivativeClass)anObject; dummy.DoStuff; } }
This is incredibly clunky and makes the code look stupid.
Do I miss something or is C# (which I like otherwise) just dumb in this regard?
-
2017-10-27, 06:00 PM (ISO 8601)
- Join Date
- Mar 2007
- Location
- Oregon, USA
Re: Typecasting in C#
If I'm reading this right, you should be able to do
Code:((DerivativeClass)anObject).DoStuff
FeytouchedBanana eldritch disciple avatar by...me!
The Index of the Giant's Comments VI―Making Dogma from Zapped Bananas
-
2017-10-27, 06:04 PM (ISO 8601)
- Join Date
- Aug 2005
- Location
- Mountain View, CA
- Gender
Re: Typecasting in C#
What you're missing is the order of operations involved - the dot happens before the cast, so you're casting the result of "derivedObject.DoStuff" to the derived type. If you want to cast first, the line needs to be this:
Code:((DerivativeClass)anObject).DoStuff;
Code:if (anObject is DerivativeClass derivedObject) { derivedObject.DoStuff; }
Last edited by Douglas; 2017-10-27 at 06:05 PM.
Like 4X (aka Civilization-like) gaming? Know programming? Interested in game development? Take a look.
Avatar by Ceika.
Archives:
SpoilerSaberhagen's Twelve Swords, some homebrew artifacts for 3.5 (please comment)
Isstinen Tonche for ECL 74 playtesting.
Team Solars: Powergaming beyond your wildest imagining, without infinite loops or epic. Yes, the DM asked for it.
Arcane Swordsage: Making it actually work (homebrew)