Fred Fickleberry III
Fred Fickleberry III

Reputation: 2519

How to get a reference to an object via one of it's own properties?

In WPF you have a lot of classes where you pass a property for processing; e.g. ValueConverters, RuleValidations, etc. You cast the property to the correct type and use it.

But I often need some of the other properties of a specific object for things like calculations and comparing values.

The last view days I have been experimenting with ugly stuff, like passing the entire object as a parameter, just to get to the instance object.

There must be a way to get to the object from one of it's own properties?

How would I go about that?

For instance in this code:

public class Car
{
    public string Brand { get; set; }
    public string Color { get; set; }
}

class Program
{
    public static void Main(string[] args)
    {
        Car car = new Car();

        car.Brand = "Porsche";
        car.Color = "Yellow";

        Test(car.Brand);
    }

    public static void Test(object value)
    {
        var brand = (String)value;

        // Get the Car object instance reference from the passed object?
        var carInstance = ...

            Console.WriteLine("This {0} has a {1} paint job",
                              brand, carInstance.Color);
    }
}

Upvotes: 0

Views: 133

Answers (2)

Teeknow
Teeknow

Reputation: 1015

Is there a reason you don't want to pass the whole object? I think that since objects by default are passed by reference in c# it's not much worse than passing an int (a reference is kind of a number that represents a specific place in memory) so it shouldn't kill you performance-wise to pass a whole object (unless your object is something ridiculously massive and you only need 2 properties from it).

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Sorry, but its impossible. You can't get Car instance from String (its Brand name) value. car.Brand is not a property (say, PropertyInfo) in your code, it's just a value of String. Just imagine:

   // Test(car.Brand);
   String brandName = car.Brand; // <- Just a string, nothing special
   Test(brandName);

Even when we use Reflection, we can't get Object instance, the only thing we can get is class (Type):

  PropertyInfo pi = typeof(Car).GetProperty("Brand");
  ...
  Type tp = pi.ReflectedType; // <- Car; Type only, not instance

Instead, you can pass Car instance and get all properties you want:

public static void Main(string[] args)
{
    Car car = new Car();

    car.Brand = "Porsche";
    car.Color = "Yellow";

    Test(car);
}

public static void Test(Car value)
{
   Console.WriteLine("This {0} has a {1} paint job", value.Brand, value.Color);
}

Upvotes: 1

Related Questions