Reflection - object comparison & default values - c#

I'm trying to compare two complex objects in C#, and produce a Dictionary containing the differences between the two.
If I have a class like so:
public class Product
{
public int Id {get; set;}
public bool IsWhatever {get; set;}
public string Something {get; set;}
public int SomeOtherId {get; set;}
}
And one instance, thus:
var p = new Product
{
Id = 1,
IsWhatever = false,
Something = "Pony",
SomeOtherId = 5
};
and another:
var newP = new Product
{
Id = 1,
IsWhatever = true
};
To get the differences between these, i'm doing stuff that includes this:
var oldProps = p.GetType().GetProperties();
var newProps = newP.GetType().GetProperties();
// snip
foreach(var newInfo in newProps)
{
var oldVal = oldInfo.GetValue(oldVersion, null);
var newVal = newInfo.GetValue(newVersion,null);
}
// snip - some ifs & thens & other stuff
and it's this line that's of interest
var newVal = newInfo.GetValue(newVersion,null);
Using the example objects above, this line would give me a default value of 0 for SomeOtherId (same story for bools & DateTimes & whathaveyou).
What i'm looking for is a way to have newProps include only the properties that are explicitly specified in the object, so in the above example, Id and IsWhatever. I've played about with BindingFlags to no avail.
Is this possible? Is there a cleaner/better way to do it, or a tool that's out there to save me the trouble?
Thanks.

There is no flag to tell if you a property was explicitly set. What you could do is declare your properties as nullable types and compare value to null.

If i understand you correctly, this is what microsoft did with the xml wrapping classes, generated with the xsd utility, where you had a XIsSpecified, or something like that, for each property X.
So this is what You can do as well - instead of public int ID{get;set;}, add a private member _id , or whatever you choose to call it, and a boolean property IDSpecified which will be set to true whenever Id's setter is called

I ended up fixing the issue without using reflection (or, not using it in this way at least).
It goes, more or less, like this:
public class Comparable
{
private IDictionary<string, object> _cache;
public Comparable()
{
_cache = new Dictionary<string, object>();
}
public IDictionary<string, object> Cache { get { return _cache; } }
protected void Add(string name, object val)
{
_cache.Add(name, val);
}
}
And the product implementation goes to this:
public class Product : Comparable
{
private int _id;
private bool _isWhatever;
private string _something;
private int _someOtherId;
public int Id {get { return _id; } set{ _id = value; Add("Id", value); } }
public bool IsWhatever { get { return _isWhatever; } set{ _isWhatever = value; Add("IsWhatever ", value); } }
public string Something {get { return _something; } set{ _something = value; Add("Something ", value); } }
public int SomeOtherId {get { return _someOtherId; } set{ _someOtherId = value; Add("SomeOtherId", value); } }
}
And the comparison is then pretty straightforward
var dic = new Dictionary<string, object>();
foreach(var obj in version1.Cache)
{
foreach(var newObj in version2.Cache)
{
//snip -- do stuff to check equality
dic.Add(....);
}
}
Doesn't hugely dirty the model, and works nicely.

Related

How to implement property with parameter

I'm trying to implement a class with a property which can be accessed only with parameter. To clear my question see how I intend to use it
Note that this is different than Indexer. Please don't flag for duplicate.
My incomplete class
public class Inventory{
public object Options..... // I don't know how to define this property
}
How I'm going to use it
Inventory inv = new Inventory();
string invLabel = (string)inv.Options["Label"];
int size = inv.Options["Size"];
inv.Options["Weight"] = 24;
Internally, Options reads data from a private Dictionary. Please help me on how I can define the Options property.
Note: This is different than Indexer. With Indexer, I can use below code:
int size = inv["Size"];
But my usage is different.
I found a way to implement it.
public class Options
{
public Dictionary<string, object> _options;
public Options()
{
_options = new Dictionary<string, object>();
}
public object this[string key] {
get { return _options.Single(r => r.Key == key).Value; }
set { _options[key] = value; }
}
}
public class Inventory
{
public Inventory()
{
Options = new Options();
}
public Options Options { get; set; }
}
Usage:
var x = new Inventory();
x.Options["Size"] = 120;
x.Options["Box"] = "4 x 4 x 8";
Console.WriteLine(x.Options["Size"]);
Console.WriteLine(x.Options["Box"]);

Update member in class using LINQ

I have a class with 5 members.
like that:
class Demo
{
public int id;
public string name;
public string color;
public int 4th_member;
public int 5th_member;
}
I have list of this class.
for the 4th_member, and 5th_member, I have 2 list of dictionary with int key and int value. (one for 4th, and the second for 5th)
I want to update these members, according to the dictionary.
like, if dictionary's key = id, then update 4th_member to be value of Dictionary.
I hope my question is clear enough.
I tested the below code its working fine.
Hope this will solve your problem if I have understood your question properly
var demo = demoTest.Select(s =>
{
s.Fourthth_member = dic.GetValueFromDictonary(s.Fourthth_member);
s.Fifthth_member = dic1.GetValueFromDictonary(s.Fifthth_member);
return s;
}).ToList();
//Extension method
public static class extMethod
{
public static int GetValueFromDictonary(this Dictionary<int, int> dic, int key)
{
int value = 0;
dic.TryGetValue(key, out value);
return value;
}
}
linq is not used for updating data but for queries. This is a possible solution:
foreach(var demo in demoList)
{
if(dictionaries[0].ContainsKey(demo.id))
{
demo.member4 = dictionaries[0][demo.id];
}
if (dictionaries[1].ContainsKey(demo.id))
{
demo.member5 = dictionaries[1][demo.id];
}
}
Or with the TryGetValue
foreach(var demo in demoList)
{
int value;
if(dictionaries[0].TryGetValue(demo.id, out value))
{
demo.member4 = value;
}
if (dictionaries[1].TryGetValue(demo.id, out value))
{
demo.member5 = value;
}
}

Example usage of HashSet<T>.CreateSetComparer

I am aware of the HashSet<T>.SetEquals method, but when and how should CreateSetComparer be used?
The documentation states: "checks for equality at only one level; however, you can chain together comparers at additional levels to perform deeper equality testing"
What would be a simple example of that?
In particular, if each item in the sets I am comparing also contains a HashSet , what would be the correct usage of CreateSetComparer?
Here is my starting point. I'd like to know if the CreateSetComparer method is applicable and how to properly use it:
public class Foo : IEquatable<Foo>
{
public string Label { get; set; }
public string Value { get; set; }
public override string ToString() {return String.Format("{0}:{1}", Label, Value); }
// assume for this example that Label and Value are immutable once set;
public override int GetHashCode(){ return ToString().GetHashCode(); }
// simplified equality check; assume it meets my needs for this example;
public bool Equals(Foo other){ return String.Equals(this.ToString(), other.ToString()); }
}
public class FooGroup : IEquatable<FooGroup>
{
public int GroupIndex {get; set;}
public HashSet<Foo> FooCollection {get; set;}
// -----------------------------
// Does HashSet.CreateSetComparer somehow eliminate or simplify the following code?
// -----------------------------
public override int GetHashCode()
{
int hash = GroupIndex;
foreach(Foo f in FooCollection)
hash = hash ^ (f.GetHashCode() & 0x7FFFFFFF);
return hash;
}
public bool Equals(FooGroup other)
{
// ignore missing null checks for this example
return this.GroupIndex == other.GroupIndex && this.FooCollection.SetEquals(other.FooCollection);
}
}
public class GroupCollection : IEquatable<GroupCollection>
{
public string CollectionLabel {get; set;}
public HashSet<FooGroup> AllGroups {get; set;}
// -----------------------------
// Does HashSet.CreateSetComparer somehow eliminate or simplify the following code?
// -----------------------------
public override int GetHashCode()
{
int hash = CollectionLabel.GetHashCode();
foreach(FooGroup g in AllGroups)
hash = hash ^ (g.GetHashCode() & 0x7FFFFFFF);
return hash;
}
public bool Equals(GroupCollection other)
{
// ignore missing null checks for this example
return String.Equals(this.CollectionLabel, other.CollectionLabel) && this.AllGroups.SetEquals(other.AllGroups);
}
}
Ignoring arguments about system design and such, a simplified use-case would be: imagine I have pulled a complex set of data that looks like this:
var newSetA = new GroupCollection{ ... }
var oldSetA = new GroupCollection{ ... }
I simply want to check:
if (newSetA.Equals(oldSetA))
Process(newSetA);
Let's start with the question of "when would the CreateSetComparer" be useful? You already have quite an idea here:
In particular, if each item in the sets I am comparing also contains a HashSet , what would be the correct usage of CreateSetComparer?
Well, for example, the next example demonstrates the default behaviour when HashSet uses its default comparer (comparing only by references):
var set1 = new HashSet<HashSet<int>>{
new HashSet<int>{2,3,4},
new HashSet<int>{7,8,9}
};
var set2 = new HashSet<HashSet<int>>{
new HashSet<int>{2,3,4},
new HashSet<int>{7,8,9},
};
set1.SetEquals(set2).Dump(); // false :-(
set1.SequenceEqual(set2).Dump(); // false
set1.SequenceEqual(set2, HashSet<int>.CreateSetComparer()).Dump(); // true
It's also possible to use CreateSetComparer with SetEquals, like so:
// the order of elements in the set has been change.
var set1 = new HashSet<HashSet<int>>(HashSet<int>.CreateSetComparer()){
new HashSet<int>{2,3,4},
new HashSet<int>{7,8,9}
};
var set2 = new HashSet<HashSet<int>>{
new HashSet<int>{7,8,9},
new HashSet<int>{2,3,4},
};
set1.SetEquals(set2).Dump(); // true :-)
set1.SequenceEqual(set2).Dump(); // false
set1.SequenceEqual(set2, HashSet<int>.CreateSetComparer()).Dump(); // false
That is the usual usage, however the CreateSetComparer provides GetHashCode which you could exploit, although this is not necessarily shorter / cleaner, what you already do.
// -----------------------------
// Does HashSet.CreateSetComparer somehow eliminate or simplify the following code?
// -----------------------------
private IEqualityComparer<HashSet<FooGroup>> _ecomparer =
HashSet<FooGroup>.CreateSetComparer();
public override int GetHashCode()
{
int hash = CollectionLabel.GetHashCode();
hash ^= _ecomparer.GetHashCode(AllGroups);
return hash;
}
I've used it when providing to a Dictionary with "multiple" keys in which the order does not matter:
var dict = new Dictionary<HashSet<int>, string>(HashSet<int>.CreateSetComparer());
dict[new HashSet<int> { 1, 2 }] = "foo";
dict[new HashSet<int> { 2, 1 }].Dump();
You can provide a nicer API by wrapping it with a params indexer:
public class MultiKeyDictionary<TKey, TValue> : IDictionary<HashSet<TKey>, TValue>
{
private readonly IDictionary<HashSet<TKey>, TValue> _dict;
public MultiKeyDictionary()
{
_dict = new Dictionary<HashSet<TKey>, TValue>(HashSet<TKey>.CreateSetComparer());
}
public TValue this[params TKey[] keys]
{
get { return _dict[new HashSet<TKey>(keys)]; }
set { _dict[new HashSet<TKey>(keys)] = value; }
}
...
}
var dict = new MultiKeyDictionary<int, string>();
dict[1, 2] = "foo";
dict[2, 1].Dump();

Adding a bool for each property

I'm building a c# class that works with two different data sources. It will load a data source and take a configuration set from a function. Then I want to do several tasks on all properties within the object.
for example.
public String StreetAddress
{
get { return _streetAddress; }
set
{
if (value.Length <= 64)
_streetAddress = value;
else
_streetAddress = value.Substring(0, 1024).Trim();
}
}
public String City
{
get { return _city; }
set
{
if (value.Length <= 128)
_city = value;
else
_city = value.Substring(0, 128).Trim();
}
}
public String State
{
get { return _state; }
set
{
if (value.Length <= 128)
_state = value;
else
_state = value.Substring(0, 128).Trim();
}
}
So that holds the data from one side. I was hoping to be able to store and set a change flag on each property. So if we take State for example. If the person is moved from Texas to Illinois I want to set a bool within that property to note the change then be able to loop over all changes before saving the object to the DB. But I don't see any way to assign another state variable within that property. Is the best way to write another object on top of this to control it or is there another more creative way to store multiple strings within the one property?
If you'd like an OOP way of doing the thing, you can:
Define an interface and a class for holding your property, such as:
interface IPropertySlot
{
bool IsDirty { get; }
void ResetIsDirty();
object UntypedValue { get; }
}
class PropertySlot<T>:IPropertySlot
{
public T Value { get; private set; }
public bool SetValue(T value)
{
if (!Equals(_value, Value))
{
Value = value;
IsDirty = true;
return true;
}
return false;
}
public bool IsDirty { get; private set; }
public void ResetIsDirty()
{
IsDirty = false;
}
public object UntypedValue
{
get { return Value; }
}
}
Store your properties inside your class in a dictionary from String (for name of property) to IPropertySlot and get/set them through a pair of methods:
void SetProperty<T>(string name, T value)
{
IPropertySlot property;
if (!_properties.TryGetValue(name, out property))
{
property = new PropertySlot<T>();
_properties[name] = property;
}
((PropertySlot<T>)property) .SetValue(value);
}
T GetProperty<T>(string name)
{
IPropertySlot property;
if (!_properties.TryGetValue(name, out property))
{
property = new PropertySlot<T>();
_properties[name] = property;
}
return ((PropertySlot<T>)property).Value;
}
Finding the changed properties later is just a matter of going over the _properties.Values and finding which of them are IsDirty.
This approach also gives you a way to add more functionality to your properties in an OO manner (such as raising PropertyChanged/PropertyChanging events, mapping it to DB fields, etc.).
In such a situation I'd prefer an approach external to the Dto implementation.
Implement some unit that would take two instances of a class, and determine all the differences.
Map each property to compare:
static PropertyManager<Dto> manager = new PropertyManager<Dto>()
.Map(x => x.City)
.Map(x => x.StreetAddress);
Use two instances to compute difference:
var a = new Dto{ StreetAddress = "Foo", City = "Bar" };
var b = new Dto{ StreetAddress = "Foo", City = "Baz" };
var differences = manager.ComputeDifferences(a,b).ToList();
if( differences.Any() )
{
Console.WriteLine("Instances differ");
}
foreach (var diff in differences)
{
Console.WriteLine(diff);
}
This sample code prints out:
Instances differ
x.City
Here is a complete code example:
https://dotnetfiddle.net/4sNeoN

multi return type in c# methods

I have a (string, object) dictionary, object (class) has some values including data type which is defined by enum. I need a GetItemValue method that should return dictionary item's value. So return type must be the type which is defined in item object.
Class Item
{
String Name;
DataValueType DataType;
Object DataValue;
}
private Dictionary<string, Item> ItemList = new Dictionary<string, Item>();
void Main()
{
int value;
ItemList.Add("IntItem", new Item("IntItem", DataValueType.TInt, 123));
value = GetItemValue("IntItem"); // value = 123
}
What kind of solution can overcome this problem?
Best Regards,
You can use Generic Classes
Class Item<T>
{
String Name;
T DataTypeObject;
Object DataValue;
public T GetItemValue()
{
//Your code
return DataTypeObject;
}
}
A better solution would be to introduce an interface that you make all the classes implement. Note that the interface doesn't necessarily have to specify any behavior:
public interface ICanBePutInTheSpecialDictionary {
}
public class ItemTypeA : ICanBePutInTheSpecialDictionary {
// code for the first type
}
public class ItemTypeB : ICanBePutInTheSpecialDictionary {
// code for the second type
}
// etc for all the types you want to put in the dictionary
To put stuff in the dictionary:
var dict = new Dictionary<string, ICanBePutInTheSpecialDictionary>();
dict.add("typeA", new ItemTypeA());
dict.add("typeB", new ItemTypeB());
When you need to cast the objects to their specific types, you can either use an if-elseif-block, something like
var obj = dict["typeA"];
if (obj is ItemTypeA) {
var a = obj as ItemTypeA;
// Do stuff with an ItemTypeA.
// You probably want to call a separate method for this.
} elseif (obj is ItemTypeB) {
// do stuff with an ItemTypeB
}
or use reflection. Depending on how many choices you have, either might be preferrable.
If you have a 'mixed bag' you could do something like this...
class Item<T>
{
public String Name { get; set; }
public DataValueType DataType { get; set; }
public T DataValue { get; set; }
}
class ItemRepository
{
private Dictionary<string, object> ItemList = new Dictionary<string, object>();
public void Add<T>(Item<T> item) { ItemList[item.Name] = item; }
public T GetItemValue<T>(string key)
{
var item = ItemList[key] as Item<T>;
return item != null ? item.DataValue : default(T);
}
}
and use it like...
var repository = new ItemRepository();
int value;
repository.Add(new Item<int> { Name = "IntItem", DataType = DataValueType.TInt, DataValue = 123 });
value = repository.GetItemValue<int>("IntItem");
If you have just a couple types - you're better off with Repository<T>.
I found a solution exactly what I want. Thanks to uncle Google.
Thanks all of you for your kind interest.
public dynamic GetValue(string name)
{
if (OpcDataList[name].IsChanged)
{
OpcReflectItem tmpItem = OpcDataList[name];
tmpItem.IsChanged = false;
OpcDataList[name] = tmpItem;
}
return Convert.ChangeType(OpcDataList[name].ItemValue.Value, OpcDataList[name].DataType);
}

Categories