Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a default value if dynamic object doesn't contain property

Tags:

c#

.net

dynamic

When working with dynamic objects in many languages, there is a construct that allows you to get the value of a property and if said property doesn't exist, return a default value.

I want to know if there is a similar method/syntax when working with dynamic in .NET. I know that you can cast an ExpandoObject to a Dictionary, but sometimes there is no guarantee that a dynamic object is an Expando.

I'm thinking of something that would have the same effect of the following code

public class SomeClass
{
    public string ValidProperty { get; set; }
}

dynamic t = new SomeClass() { 
    ValidProperty = "someValue"
};

Console.WriteLine(t.Get("ValidProperty", "doesn't exist")); // Prints 'someValue'
Console.WriteLine(t.Get("InvalidProperty", "doesn't exist")); // Prints 'doesn't exist'
like image 377
Carlos G. Avatar asked Nov 09 '22 04:11

Carlos G.


1 Answers

I want to know if there is a similar method/syntax when working with dynamic in .NET. I know that you can cast an ExpandoObject to a Dictionary, but sometimes there is no guarantee that a dynamic object is an Expando.

And there is also no guarantee that it is a compile-time object.

You may use try/catch but this even doesn't say anything about the existence of the property. An example of dynamic object:

 public class MyDynamic: DynamicObject
{
    static int Count = 0;
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = Count++;
        if (binder.Name == "Test")
        {
            return Count % 2 == 0;
        }
        return false;
    }
}

And suppose you use it as

dynamic d = new MyDynamic();
try { Console.WriteLine(d.Test); } catch (Exception ex) { Console.WriteLine(ex.Message); }
try { Console.WriteLine(d.Test); } catch (Exception ex) { Console.WriteLine(ex.Message); }
try { Console.WriteLine(d.Test); } catch (Exception ex) { Console.WriteLine(ex.Message); }
try { Console.WriteLine(d.Test); } catch (Exception ex) { Console.WriteLine(ex.Message); }

Some calls to d.Test will return a value and some will throw exception. So I'll say, there is no safe method to test it, and there isn't any default value for a method that may not exist.

like image 156
Eser Avatar answered Nov 14 '22 21:11

Eser