c00kiemonster
c00kiemonster

Reputation: 23361

How can I translate this C# variable declaration to something IronPython can handle?

I don't know if this is a simple matter of RTFM, but bear with me as it was a while ago I used a statically typed language...

I'm porting some C# code to IronPython, and I just stumbled on this statement below. I'm not at liberty to post the actual code, so I'll write it in pseudo code instead:

data_type_1 variable_1 = variable_2 as data_type_2;

where

variable_2 is a COM object from earlier parts of the code, variable_1 is a new variable, and data_type_1 is a class that interacts with the data in the COM object.

What does it mean? I'm guessing it is some form of conversion. How can I convert it to something IronPython can make sense of?

Upvotes: 0

Views: 153

Answers (3)

Jeff Hardy
Jeff Hardy

Reputation: 7662

As Hans already explained, the as operator converts from one type to another. This is necessary to keep C#'s compiler happy. IronPython, on the other hand, doesn't care - you can call whatever operation you need to on variable_2 and if it doesn't work you'll get an error at runtime.

So, the short version is that as is unnecessary in IronPython and that statement can be reduced to

variable_1 = variable_2

If you do need to check whether a Python object is of a particular type (or a subclass), use isinstance.

Upvotes: 0

c00kiemonster
c00kiemonster

Reputation: 23361

After killing a few hours I figured I might as well do it the simple but perhaps not the prettiest way. I simply downloaded Visual C# 2010 Express (free version) and wrote a minimal Class Library containing one method consisting of only the troublesome statement. I then built the dll, which was promptly imported and used in the original IronPython script.

From idea to a working solution it only took 10 minutes. Kudos to Microsoft, it was a whole lot simpler to build a dll than I thought.

Upvotes: 1

Hans Kesting
Hans Kesting

Reputation: 39329

The as operator is a "safe cast" operator, it converts the variable_2 to type data_type_2. If that conversion fails, it doesn't throw an exception but returns null.

Further, to be able to assign a value of data_type_2 (the result of the 'as' expression) to a variable of data_type_1, that data_type_2 must be derived from data_type_1 (or implement the interface data_type_1).

Upvotes: 2

Related Questions