- Home /
C# dynamic typing
Can C# script use the dynamic typing like in Javascript? Does C# contain similar functionality like the Javascript?
Javascript
var objectType = typeof(object); if (objectType == GUITexture) { //Do Something }
so.. what will be the C# code for the above Javascript?
Answer by Wolfram · Aug 23, 2010 at 11:49 AM
Actually that's quite simple, but it is hard to find the correct documentation pages on that:
if(object is GUITexture){
// Do Something
}
This also works with derived classes (up and down). You might also want to check the docs for GetType() and IsSubclassOf(), if you are working with derived classes. But the "is" keyword simplifies things. The actual dynamic cast would be:
GUITexture myTexture=object as GUITexture;
Avoid static casts ( myTexture=(GUITexture)obj ), as they will throw an exception and not compiler errors for derived classes.
EDIT: So, no there is no "real" dynamic typing / duck typing in (Unity-)C#. But with "is" and "as" you are still quite flexible, and the programmer himself can make sure that what he is trying to do is actually allowed (such as, casting from A to B).
Answer by cyangamer 1 · Aug 23, 2010 at 10:14 AM
Perhaps you can view this link? There is a 'dynamic' type in C#, and it sounds like that's what you want.
That link contains some useful information, I had been looking for that. However, I'm not sure the 'dynamic' type is supported in Unity. Have you tried it?
If I am reading http://unity3d.com/unity/whats-new/unity-3 right and we now have the mono version of C# 3.5 we can indeed do that. Why one would want to do that I can't quite catch on as it can only be used in the local scope.
the dynamic keyword does not work. i use this (http://www.unifycommunity.com/wiki/index.php?title=JSONObject) json parser ins$$anonymous$$d. dynamic progra$$anonymous$$g ftw!
Answer by AnomalusUndrdog · Aug 01, 2012 at 11:17 AM
Since the dynamic keyword doesn't work, the closest you could do is make interfaces.
http://lmgtfy.com/?q=c%23+interface+tutorials
As for the C# equivalent of:
var objectType = typeof(object); if (objectType == GUITexture) { //Do Something }
It would be:
var objectType = object.GetType(); if (objectType == typeof(GUITexture)) { }