How to Check If a Property Exists on a Dynamic Anonymous Type in C#

How do I check if a property exists on a dynamic anonymous type in c#?

  public static bool DoesPropertyExist(dynamic settings, string name)
{
if (settings is ExpandoObject)
return ((IDictionary<string, object>)settings).ContainsKey(name);

return settings.GetType().GetProperty(name) != null;
}

var settings = new {Filename = @"c:\temp\q.txt"};
Console.WriteLine(DoesPropertyExist(settings, "Filename"));
Console.WriteLine(DoesPropertyExist(settings, "Size"));

Output:

 True
False

Test if a property is available on a dynamic variable

I think there is no way to find out whether a dynamic variable has a certain member without trying to access it, unless you re-implemented the way dynamic binding is handled in the C# compiler. Which would probably include a lot of guessing, because it is implementation-defined, according to the C# specification.

So you should actually try to access the member and catch an exception, if it fails:

dynamic myVariable = GetDataThatLooksVerySimilarButNotTheSame();

try
{
var x = myVariable.MyProperty;
// do stuff with x
}
catch (RuntimeBinderException)
{
// MyProperty doesn't exist
}

How to check if a property exists before trying to add to list

Instead of deserializing to ExpandoObject, create an actual model that represents your data and use that. If you don't have the necessary keys in your json, your model will be null and then you can just do a null check.

public class Activity
{
public string Key {get;set;}
public DisplayProperties DisplayProperties {get;set;}
}

public class DisplayProperties
{
public string Description {get;set;}
public string Name {get;set;}
public string Icon {get;set;}
public bool HasIcon {get;set;}
}

var activity= response.Content.ReadAsAsync<Activity>().Result;

if(!string.IsNullOrWhiteSpace(activity.Key) && !string.IsNullOrWhiteSpace(activity.DisplayProperties?.Name)
//add to list

How do I check if an anonymous object properties are not empty C#

I solved it like that:

public static bool IsAnyNullOrEmpty(object objectToBeChecked, params string[] parametersToBeChecked)
{
foreach (var obj in (IEnumerable)objectToBeChecked)
{
foreach (var pi in obj.GetType().GetProperties())
{
if (parametersToBeChecked.Contains(pi.Name))
{
var value = (string)pi.GetValue(obj);
if (string.IsNullOrEmpty(value))
{
return true;
}
}
}
}

return false;
}

This will take the object (anonymous object) and properties names which you want to check, this works for me.

How to access property of anonymous type in C#?

If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.

var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();

Then you'll be able to access it like:

nodes.Any(n => n.Checked);

Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.

nodes.Add(new { Checked = false, /* etc */ });

How to safely check if a dynamic object has a field or not

You need to surround your dynamic variable with a try catch, nothing else is the better way in makking it safe.

try
{
dynamic testData = ReturnDynamic();
var name = testData.Name;
// do more stuff
}
catch (RuntimeBinderException)
{
// MyProperty doesn't exist
}

Include properties based on conditions in anonymous types

Not directly using an if statement, but you could do it using the ternary operator (assuming TimeIn is of type DateTime):

var g = records.Select(r => new
{

Id = r.CardholderNo,
TimeIn = condition ? r.ArriveTime : (DateTime?)null;
TimeOut = r.LeaveTime
});

Note this will make the property always appear in your Annonymous Type. If this isn't the desired behavior, then you can't do it this way.

I would suggest thinking about the readability of your code and not only about "how can i shorten these few lines so it looks neat".

Get a property of a anonymous type object from ListViewItem's prop Tag

You could use dynamic typing to do this:

// NOTE: NOT RECOMMENDED; SEE BELOW
// Populate the tag as before
newListViewItem.Tag = new { XPATH = FindXPath(node) };

// Recover Tag property using a variable of type dynamic
dynamic myObj = myListView.Items[0].Tag;
string xpath = myObj.XPATH;

However, I'd strongly recommend that you don't do that. You'd only be using dynamic typing to avoid having to declare a few classes, each of which is trivial to create anyway. For example:

public class XPathTag
{
public string XPath { get; set; }
}

// Populate the tag using the class. You could add a constructor
// accepting the XPath if you wanted
newListViewItem.Tag = new XPathTag { XPath = FindXPath(node) };

// Recover Tag property using a variable of type dynamic
XPathTag tag = (XPathTag) myListView.Items[0].Tag;
string xpath = tag.XPath;

Now if you fetch a tag from a control that has a non-XPathTag tag, you'll see an exception indicating exactly what's wrong. Additionally, there's no chance of getting typos when accessing the properties, as you could with the dynamic typing solution... the compiler will check how you use the tag.

Fundamentally, C# is almost entirely a statically typed language. Embrace that, and create types where you want to be able to reliably refer to specific sets of data. While there's still the cast that can fail, that's a a single point of potential failure which will be a lot easier to diagnose than the dynamic typing approach.

How can I access a field in an anonymous type stored in an object variable?

Use the dynamic keyword:

public struct Foo
{
public dynamic obj;
public Foo(int val)
{
obj = new
{
bar = val
};
Console.WriteLine(obj.bar); // is accessible now
}
}


Related Topics



Leave a reply



Submit