how to detect undefined property

May 15, 2010 at 10:18 AM
In javascript you can detect if a property is defined by using the undefined keyword: if( data.myProperty == undefined ) ... How would you do this in C# using the dynamic keyword with an ExpandeObject ?
May 15, 2010 at 2:45 PM

There's no real solution for the general case of a dynamic object. In fact, languages like Python can execute user code when you try to access a member with an arbitrary name. So the best you can do is to wrap the property access in a try/catch and hope that an invalid member access throws an exception.

However, in the specific case that you know the object is an ExpandoObject, you can cast it to an IDictionary<string, object> and use TryGetValue to see if the property is defined.

May 15, 2010 at 3:31 PM

Hi again,

I have a better understanding of the DLR now that i've played with its core engine.

 

I've overriden the TryGetValue of the ExpandoObject class to always return true and it behaves now as expected without any exception. I always set the returned object to a string with "undefined" in it. This is specific to my business model. Maybe a special object instance would have been better. One called Undefined maybe :)

 

Coordinator
May 17, 2010 at 5:48 PM

If you look at the Sympl sample language, there's some static helpers written in C# that provide a HasMember test.  The only issue is there's no caching involved, so if you're doing it in one place only and don't care about "clean abstraction", you'd just have to wrap your member access in a try/catch.

Bill

From: softlion [mailto:notifications@codeplex.com]
Sent: Saturday, May 15, 2010 2:19 AM
To: Bill Chiles
Subject: how to detect undefined property [dlr:212732]

From: softlion

In javascript you can detect if a property is defined by using the undefined keyword: if( data.myProperty == undefined ) ... How would you do this in C# using the dynamic keyword with an ExpandeObject ?

Read the full discussion online.

To add a post to this discussion, reply to this email (dlr@discussions.codeplex.com)

To start a new discussion for this project, email dlr@discussions.codeplex.com

You are receiving this email because you subscribed to this discussion on CodePlex. You can unsubscribe or change your settings on codePlex.com.

Please note: Images and attachments will be removed from emails. Any posts to this discussion will also be available online at codeplex.com