jjK
jjK

Reputation:

C# Reflection problem : How to ask a class if it has an object called

I have multiple instances of a class in my code, each with difference configs etc. This class has a delegate eventhandler method which receives event from a sender and then need to perform some action with one of the above objects.

I would like to know if reflection can resolve this.

private CatClass cat1;
private CatClass cat2;
private CatClass cat3;

I would like to avoid checking each instance independently to see if it's the object I want. But would instead like to somehow retrieve the object instance which the sending event has identified.

So

private void delegateHandler(string senderName, object sender, CustomEventType evt)
{
     // given reciept of the senderName string,
     // how do I perform an action on say the cat2 object

    // Is it possible to ask the class if it has an object defined
    // called 'cat2' and then proceed with performing an action on that object
}    

Thanks for the help.

Upvotes: 0

Views: 495

Answers (6)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112269

There are different ways to approach this problem. Reflection is certainly not the right choice.

One approach would be to use an array of cats

Cat[] cats = new Cat[] { new Cat(), new Cat(), new Cat() };

Instead of working with cat names you would be working with cat numbers

private void delegateHandler(int catNumber, object sender, CustomEventType evt)
{
    DoSomethingWith(cats[catNumber]);
}

Yet another way is to pass the cat itself as sender (that's the usual way of doing things with event handlers)

private void delegateHandler(object sender, CustomEventType evt)
{
    Cat cat = (Cat)sender;
    DoSomethingWith(cat);
}

Yet another way is to give each cat a name property

public class Cat
{
    public string Name { get; set; }

    // Other properties and methods       
}

then use a dictionary to store cats

var catsByName = new Dictionary<string, Cat>();
Cat cat = new Cat { Name = "Tiger" };
catsByName.Add(cat.Name, cat);
...

Then you can get a cat by its name like this

cat = catsByName["Tiger"];

Or if you are not sure, whether the cat exists

if (catsByName.TryGetValue("Misty", out cat)) {
    DoSomethingWith(cat);
} else {
    CatNotFound();
}

Upvotes: 0

Joshua Marble
Joshua Marble

Reputation: 560

I doubt you even care at this point, but your specific question of how to address this in reflection was never answered. Here is basically how you would do it.

private void delegateHandler(string senderName, object sender, CustomEventType evt)
{
    FieldInfo field = this.GetType().GetField(senderName, BindingFlags.NonPublic | BindingFlags.Instance);
    if(field != null && field.Name == senderName)
    {
        CatClass cat = (CatClass)field.GetValue(this);
        cat.DoWork();
    }
}

Upvotes: 0

MiffTheFox
MiffTheFox

Reputation: 21555

Well, like the posts above mentioned, Reflection is generally a bad idea.

this.GetType().GetMember(senderName) == null;

Would probably work here though.

Upvotes: 0

Lucero
Lucero

Reputation: 60190

You can use reflection for that, but I'd suggest not doing it. Reflection is slow and this is unlikely a situation where it is required.

Why not have a dictionary (when you want to look them up by name), a list or an array of CatClass and iterate on them to see which one is the one you need?

Upvotes: 0

Andrew Hare
Andrew Hare

Reputation: 351466

C# works better if you "tell" rather than when you "ask".

In other words it would be better to have an interface or base class that has the CatClass member declared in it that would allow you to work with a variable of that interface type or base class instead of using reflection. My only concern is that since the members you are hoping to use are private this will prevent you from using an interface.

Are you really using a handler that digs into the sender via reflection to retrieve private members? Perhaps you ought to re-think your approach.

Upvotes: 0

Miha Markic
Miha Markic

Reputation: 3240

That's highly unlikely to achieve the way you want? Out of curiosity, won't sender give you a proper instance? If not, then you should put shot CatClass instances into a Dictionary and search that dictionary when required.

Upvotes: 1

Related Questions