views:

51

answers:

2

Hi all,

Could you answer me how to do next, please? How to do this with Lambda? Is it possible to delegate some object instance and use its properties and methods in case if this method doesn't know type of delegated object?

class class_a {
    public string getChildData<T> (T dynamicInstance) {
        return dynamicInstance.prop;
    }
}

class class_b : a {
    public string prop = "prop_b";
}

class class_c : a {
    public string prop = "prop_c";
}

var inst_b = new b ();
var inst_c = new c ();
b.getChildData(b);
c.getChildData(c);

Purpose : to get child property inside parent class?

Thanks, Artem

+4  A: 

Use an abstract/virtual property instead of a field:

abstract class ClassA
{
    public abstract string MyProperty
    {
        get;
    }

    public void DoIt()
    {
        Console.WriteLine(this.MyProperty);
    }
}

class ClassB : ClassA
{
    public override string MyProperty
    {
        get { return "prop_b"; }
    }
}

class ClassC : ClassA
{
    public override string MyProperty
    {
        get { return "prop_c"; }
    }
}

var instB = new ClassB();
var instC = new ClassC();
instB.DoIt();
instC.DoIt();

See: Inheritance (C# Programming Guide)
See: override (C# Reference)

dtb
Thanks for reply, but it is not what i want. I need to get property not just from created instance, but inside parent method passing this instance inside of it.
Tema
@Tema: Inheritance is the usual solution to let a base class access a value provided by a derived class. Why don't you want the usual solution?
dtb
Because i have the code (method) which is almost the same for all child classes except of two properties names. So, to prevent its duplicating each time i create new class i have decided to describe it as generic method of parent class which can get needed instance containing all needed properties.
Tema
A: 

Thanks for reply dtb,

Now all is working, though not in mentioned way.

Description is here - http://forums.asp.net/t/1608839.aspx

Tema