d3st1ny
d3st1ny

Reputation: 85

Dynamically fitted types

I want to dynamically fit type to argument in my method yet before compiling, I mean:

public class Foo
{
    public int Prop1;
    public string Prop2;
}

public class Program
{
    public static void Main(string[] args)
    {
        Foo foo = MakeMethod(x => x.Prop1, 5); //good, Prop1 is int type, 5 isn't underlined in red in VS
        Foo foo = MakeMethod(x => x.Prop2, 10); //bad, Prop2 is string, not int, VS underlines 10 in red, and I want this behaviour
    }

    private static Foo MakeMethod(Func<Foo, object> prop, object val)
    {
        Foo result;
        //do some stuff
        return result;
    }
}

I know I should do something with object type, but I don't know what. I could simply check if second generic prop argument is the type of val, otherwise do return in my method, but that's not satisfying me. I don't want to use dynamic type either because I get exception after running my program, not at the code writing stage.

Upvotes: 0

Views: 41

Answers (1)

SLaks
SLaks

Reputation: 888047

You're looking for generics:

private static Foo MakeMethod<T>(Func<Foo, T> prop, T val)

Upvotes: 5

Related Questions