Michael
Michael

Reputation: 13636

How to make method to return generic type?

I have a class named config with one string field named key.

When I apply the GET property of the class, the property has to return one variable key in different types (Int or bool or String).

I implemented it as follow:

  public enum RetType {RetInt, RetBool, RetString};
  ...
  public object PolimorphProperty(string key, RetType how) 
  {
      get 
     { 
        switch (how)
        {
         case RetType.RetInt:
           ...;
        case RetType.RetBool:
           ...;
        case RetType.RetString:
           ...;
        }
     }  
 }

But the problem that PolimorphProperty returns Object type.

What should I change in the code to get the appropriate type (int,bool,string), not the object?

Upvotes: 2

Views: 295

Answers (5)

Michael Buen
Michael Buen

Reputation: 39463

Do this:

public T PolimorphProperty<T>(string key)
{
    return (T) objectInstanceHere;
}

Usage example:

int i = PolimorphProperty<int>("somekey");

And this supports the http://www.antiifcampaign.com/

As much as possible avoid switch, if for that matter, in a polymorphic code.

Upvotes: 1

seldary
seldary

Reputation: 6256

If I understood correctly, you are looking for something like this:

public T GenericMethod<T>(string key)
{
    var ret = new object(); // Retrieve object from whatever...
    return (T) ret;
}

public void UsageExample()
{
    int typedResult = GenericMethod<int>("myKey");
}

If you are trying to fetch different objects based on the type T, with different logic, than you'll have to switch on types anyway, Because unless your collection supports objects of certain type (they usually do), the compiler doesn't know what to do.
In this case, check this question.

Upvotes: 0

Glenn Ferrie
Glenn Ferrie

Reputation: 10408

How about this, consider that you original implementation of 'PolimorphProperty' remains im your project and you add this:

public TType PolimorphProperty<TType>(string key, RetType how) 
 {
     return (TType)PolimorphProperty(key, how);
 }

Upvotes: 0

Mark Segal
Mark Segal

Reputation: 5560

Any type in C# is actually an object.
From what I understood from your question, you call your method this way:
PolimorpthProperty(key, RetType.SomeType)
The method returns an object. You should use it this way:
int key = (int)PolimorthProperty(key, RetType.RetInt);
This is called Unboxing.

Upvotes: 0

burning_LEGION
burning_LEGION

Reputation: 13460

public T PolimorphProperty<T>(string key, T how)
{
    //todo
}

Upvotes: 0

Related Questions