0

I have few function with the same kind of procedure when only Object does changes. I've tried to write generic function to that group of methods but failed to get ID of T.

Can you help me refactor this ?

List<ObjectOfSomeKind> allObjects = new List<ObjectOfSomeKind>() { new ObjectOfSomeKind{ ID = 1}, new ObjectOfSomeKind { ID = 2 }};
List<ObjectOfSomeKind> objects = new List<ObjectOfSomeKind>();
            for (int i = 0; i < ids.Count(); i++)
            {
                int id = ids.ElementAt(i);
                ObjectOfSomeKind object = allObjects .Where(item => item.ID.Equals(id)).SingleOrDefault();
                if (object == null)
                {
                    throw new Exception("error");
                }

                objects.Add(object);
            }
3
  • new Object { ID = 1} is not valid.. unless you created a class named 'Object'? In which case, don't do that.. Commented Feb 12, 2013 at 8:40
  • Object = ObjectOfSomeKind Commented Feb 12, 2013 at 8:41
  • Naming is very much a key skill for programmers. Good idea to learn it, and fast! Commented Feb 12, 2013 at 9:01

1 Answer 1

1

Define interface (or base class) with ID property

public interface IEntity
{
   int ID { get; set; }
}

Implement this interface by your classes

public class Foo : IEntity
{
   public int ID { get; set; }
}

Then either use IEntity in your code, or (if you want to use generics) add constraint to your generic class or method

where T : IEntity

UPDATE if all your classes have ID property, you also can use dynamic objects (sometimes it is also solution, but I prefer compile time checks):

List<dynamic> allObjects = new List<dynamic>() { 
    new ObjectOfSomeKind{ ID = 1}, new ObjectOfSomeKind { ID = 2 }};
List<dynamic> objects = new List<dynamic>();

for (int i = 0; i < ids.Count(); i++)
{
    int id = ids.ElementAt(i);
    dynamic obj = allObjects.Where(item => item.ID.Equals(id)).SingleOrDefault();
    if (obj == null)                
        throw new Exception("error");                

    objects.Add(obj);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yep, this was my first thought but is there anyway to avoid common interface ?
@eugeneK nope, there is no legal way (I mean without reflection). In order to have common property, classes should have common interface (or base class)
@eugeneK actually there is also dynamic (sorry, forgot about that).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.