Compare two object from the same class with tons of fields - c#

I got two objects from the same class and I need to compare them field by field. The problem is that they have close to hundred fields and it would be helluva work to write that by hand.
Do you know any way to do that the easier way? Reflections in Java could be a solution, but yet it seems to me like a hack. And I seek a C# solution after all.

Two ideas:
Use reflection (it is available in C#) runtime and loop over the fields of the clas comparing them. If you want to be able to exclude certain fields you could do that by creating an attribute class and mark the fields you don't want to compare with that attribute.
Use reflection to loop over the fields in the same way and generate the required comparison code. This way you will have "real" code but won't have to write and maintain it yourself. Attributes can be used to fine-tune the comparison code generated.

The best is to refactor your code, hundred fields is way to mush.
If you can't because is a legacy code find out which attribute make them equals.

If you're lucky, you'll identify one or two properties that are unique for the instance -- especially likely if you class represents a database entity -- and you will only have to compare those unique properties.

Use Regular Expression find and replace. It's a pain when you have to add fields *(removed ones get you a compile error), but you get the benefit of having compiled code.
Really, though, consider splitting the class up. If there's 100 fields, can they be grouped in component classes? 100 members is a lot of mess to have to manage.

Related

Adding universal getter/setter for all calls to child object/Generating methods at runtime

Preamble:
I'm working on implementing a system where a developer can specify on object of type T which has N number of properties.
What I'm trying to accomplish:
I'd like to be able to provide more concrete control over how these properties are set and retrieved. This is difficult because of the limitless number of configurations possible.
Solutions I'm pursuing:
Is it possible to set getters dynamically?
Either through attributes? Generate the methods after the fact during construction like :
foreach(var property in typeOf(T).GetProperties())
{
//dynamically generate getter method which returns this property.
}
Possibly wrap type T in a container object which has the type as one of its properties. Then set up some type of special getter for that.
Why I want to do this:
Currently all the types for T get converted based on Typecode. Allowing people using this library to easily parse in values from various sources (databases, text files, app configs, etc.) as properties of type T. The point being to deliver these properties as type safe values rather than magic strings.
This is the impetus for wanting to use reflection for this but I could see numerous other applications for this I would imagine.
I could just say "Hey make all of your types nullable." so that it would be easy to determine which properties have been set in type T. I'd like to abstract away even that though.
The other option for this would be "Make sure you understand that certain types have default values. Be certain you're ready to accept those values, or set default values of your own (including making it nullable and setting it to null if so desired). Essentially trusting this to the developer rather than abstracting it. <==== This is what I'm currently doing.
Being able to dynamically generate methods, especially getters and setters, dynamically via reflection or a combination of reflection and C# Actions would be incredibly valuable. Any insight or ideas would be greatly welcome. Either ways of accomplishing the solutions I'm pursuiing or another idea which achieves the same ends.
I don't believe you can set accessor methods on properties of static types. Another challenge that I think you will have to deal with will be your goal to provide type safety - you see, if your types are built in run-time, compile-time checks will not work, which means you'll have to rely on dynamic a lot - this is slow. But not all is lost. You have at least two options:
The quick and dirty way
You can generate proxy classes that would inherit from your concrete types. Theese will give you ability to intercept method calls to base members and do pretty much anything you please. See Castle DynamicProxy
The hard but proper way (actually first option is using this behind the scenes)
You're looking at IL Generator namespace. This is a step above linq expression trees in a sense that you can generate your own assembly and types, all programmatically. This however is incredibly complex and error prone. I'd suggest you try option one first and only generate your own IL if you absolutely must.
UPD I know you didn't want magic strings, an I guess this is a bit less conventional solution, but also check out CSharpCodeProvider of CodeDOM namespace

Recursively merging two objects of the same type

I'm looking to combine two objects of the same type in C# so that I can come up with a third instance of the same type, but with combined or overridden properties, according to a convention.
Short of writing a bunch of very gross manual code that requires me to handle each property individually, are there any well known techniques or utility libraries that might be able to make this less of a manual effort?
Is recursion really necessary in order to map two objects of the same type? Could you
not use AutoMapper .
As the objects are of the same type mapping their property is straight forward. Moreover you have control over what member to include or whether to override or combine source and destination etc.
This is a nice SO post to check here

Is reflection the better way to compare two objects of the same type?

Background:
I have 2 instances of an object of the same type. One object is populated with the configuration of a device I'm connected to, the other object is populated with a version of the configuration that I've stored on my hard drive.
The user can alter either, so I'd like to compare them and present the differences to the user.
Each object contains a number of ViewModel properties, all of which extend ViewModelBase, which are the ones I want to compare.
Question:
Is a better way to do this than what I'm about to propose.
I'm thinking of using Reflection to inspect each property in my objects, and for each that extend ViewModelBase, I'll loop through each of those properties. For any that are different, I'll put the name and value into a list and then present that to the user.
Rather than inventing this wheel, I'm wondering if this is this a problem that's been solved before? Is there a better way for it to be done?
Depending on the amount of properties to be compared, manual checking would be the more efficient option. However, if you have lots of properties or want the check to be dynamic (i.e. you just add new properties and it automagically works), then I think Reflection is the way to go here.
Why not just implement the equals operator for your type?
http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
Edit: Having read more carefully I see what you're actually asking is what the most efficient way of doing the actual comparison is.
Doing it via reflection saves on code but is slower. Doing it with lots of manual comparions is fairly quick but more code.
If you are fairly determent and lazy in the good way. You can mix benefits of both solutions. With help of tool like cci you can emit method that compares properties. The beauty of this is that your reflection code will be executed on compile time leaving you with strait forward method to execute at runtime. This allows you to change models as you see fit and not worry about comparison code. There is a down side to this and that is learning cci which is quite challenging.

Loop through T model properties. Building a search

I'm about to build a search page on a website and the search is going to be extensive with a couple of models and with each model having a lot of properties.
Is there a way to do this in a generic way or use reflector as I have seen in some posts? I need some pointers or tips on how to aproach this. Highly appreciate it.
You can use reflection to get the information you need. If you have a type T you can use
typeof(T).GetProperties()
to get all public properties. Same is possible for fields, methods, ... If you need more meta data to generate your search, you can use attributes to annotate the properties (or fields, methods, ...) That's the way I would get started. Further details depend on your exact use case.
Can you give more details?
What is the purpose of your search? Give me the 30 second version so I can understand where you are going with this.
Are you planning on using RegEx and word stemming?
What kinds of values count as matches?
I assume you only want to search properties on the objects/models. Right?
Do want to see every property or only some of them?
What kinds of data is stored in the properties? (string, byte[], enum, etc)
Brainstorming Ideas:
What about searching one the DB server-side instead of in your hydrated objects? It might be faster (at run-time) to leverage your DB than load all of the objects into memory then reflect upon them.
You could also write a method that supports your search within the context of the model itself. You pass in the search rule set as an expression then find the match. If you have some kind of a collection container, the search could be run at that level against all of the objects in the collection.
If you want some reflection code, I wrote something that shows a lot of info about an object via reflection. I wrote this a long while ago (Dec 2009). I'm not sure if it does what you want. Take a look. If it works for you, use it! (Link)

Is there a standard way to organize methods within a class? [duplicate]

This question already has answers here:
Order of items in classes: Fields, Properties, Constructors, Methods
(16 answers)
Closed 4 years ago.
There seem to be many different ways of organizing methods in a class. I could group methods by access, and order them alphabetically. I could group related methods together. I could use a mix of the two, or something else entirely. Is there a standard way to approach this? If not, how do you approach it?
StyleCop enforces some things here:
Within a class, struct, or interface, elements must be positioned in the following order:
Fields
Constructors
Finalizers (Destructors)
Delegates
Events
Enums
Interfaces
Properties
Indexers
Methods
Structs
Classes
Furthermore, elements are ordered by access:
public
internal
protected internal
protected
private
As well as a few other rules:
Contants have to appear before fields
static elements have to appear before instance elements.
This might be a good baseline to start. As for additional ordering rules, I usually group related methods together.
Whatever you do, put it in your standards and be consistent. We use a custom Regionerate configuration to order our methods. Everyone on the team uses the same configuration.
EDIT: We're now using ReSharper's Code Cleanup with a custom Type Members Layout.
I use NArrange which does most of the things I want: Group fields, methods... alphabetically and by access modifiers. It also enforces some Style Cop rules (e.g. order of element types, location of using statements). NArrange is configurable to quite some degree, you do not have to live with the default configuration if you do not like it.
Update: Now I use Resharper since NArrange does not work correctly with newer C# syntax.
I do not order them by access modifier, nor do I order them alphabetically. (I think this is quite a burden when you add or rename a method in that class ... ).
If necessary, I group them by functionality. I mean: I put related methods toghether.
But, if you follow the SRP (Single Responsability Principle), then I think that ordering methods is in most of the circumstances a non-issue; since, when you follow SRP, your classes wouldn't have very much methods.
I group my methods by their access modifier
and in the following sequence:
public
internal
protected internal
protected
private
Since Visual Studio has tools for navigating quickly to methods by name, I prefer to put private member variables and constructors close to the top and group methods by functionality (ie, helper methods are close by to the methods that call them). I also group properties together. If a class becomes substantial, I make use of #region directives to show the organization.
I tend to find grouping of related methods far more useful when reading someone else's source code, than some arbitrary pseudo-order such as alphabetical.
Although the book is specifically about Java, Uncle Bob's Clean Code contains some excellent general principles for readability in OO classes. In particular, he uses the metaphor of a well-written newspaper article, with a headline at the top followed by a synopsis paragraph and then increasing detail as you read further down the article. By aiming for a similar top-down structure in your classes, it makes the task of reading or understanding your code much easier for others.
No, most people just group methods by logical similarity, or not at all. It doesn't really matter - classes shouldn't get too big, and with a decent IDE you can just ctrl+click to goto to any method definition anyways.
I suggest first grouping by interface they come thru, with a nice comment saying the interface name - because these are non-obvious.
Then, by relation, and only then sorting alphabetically.
Use a lot of blank lines to reduce the reader's cognitive load.
I group my method by functionality, ranging from most generic to most concrete, all that inside a region, so I can hide unnecessary details.
Microsoft's StyleCop tool does a nice job of defining element order within a class. You can also write extensions to the tool to conform to your company's coding standards. That being said, StyleCop is a good starting point.
I'm not sure there's a consistently standard way... but I group related methods together, perhaps sub-grouped by accessor. Makes it the easiest for finding related things later down the track.

Categories

Resources