Reputation: 2303
Ok,
Here is what I'm doing, I have a class called Settings
Settings has a list of properties:
I'm trying to make it as dynamic as possible.
So I can just copy and paste each property and just change its name
and it will grab the new setting by the name
Example..
public string Url
{ get { return Get<string>(MethodBase.GetCurrentMethod()); } }
public int Port
{ get { return Get<int>(MethodBase.GetCurrentMethod()); } }
private T Get<T>(MethodBase method)
{
// Code that pulls setting from the property name
}
Question is, how can I pass the properties type to Get, that way I don't have to specify the data type twice..
I know this is wrong but sort of like
Get<MethodBase.GetCurrentMethod().GetType()>(MethodBase.GetCurrentMethod());
Upvotes: 2
Views: 832
Reputation: 4909
You can't do something like
Get<MethodThatReturnsAType()>
because the generic type is set at compile time. I'm sort of wondering what the advantage you're getting here is. You could have the Get simply return object and manage the cast in the property.
What behaviour do you expect if the setting is missing for example, or defined but the wrong type?
Upvotes: 0
Reputation: 887443
It is not possible to infer a return type; you cannot do this using generics.
If Get
doesn't use typeof(T)
, you can change it to return dynamic
instead of using generics.
The caller can then implicitly cast the result in its return
statement.
There may be a performance penalty, though.
Upvotes: 3