NibblyPig
NibblyPig

Reputation: 52922

Is it possible to structure a generic method so T is optional?

Hard question to phrase, but if I have:

public class BunnyManager
{
    public Bunny<T> GetBunny<T>(string someJson)
    {
       return new Bunny<T>(someJson);
    }
}

public class Bunny<T>
{
   T parsedJson { get; set; }

    public Bunny<T>(string someJson)
    {
        if (!string.IsNullOrEmpty(someJson))
            parsedJson = ConvertJsonStringToObject<T>(someJson);
    }
}

in some cases I want to get a Bunny object without any json, because the json string is null, so I don't care what T is.

In this case, can I create an overload or something to ignore T completely, or can I call GetBunny<null> or GetBunny<object>?

I'm wondering what the correct way to solve this might be.

Upvotes: 18

Views: 920

Answers (3)

David
David

Reputation: 10708

First, if the class is generic, then all members are assumed generic, don't need a generic parameter - not even the constructor.

Second, if you don't care about T, then you can make an overload of GetBunny withuot T, since overloading classes and methods based on different generic parameters is allowed (see for example the Tuple classes.)

The easiest method I have found for generics without parameters is to make a nongeneric base class (abstract class Bunny) from which the generic inherits (thus Bunny<T> : Bunny) which makes it easier to keep, say a List<Bunny> of disparate types. This is particularly applicable in your case since the base class would be a less specific implementation and thus fit the usual pattern for inheritance.

Upvotes: 2

Steve Mitcham
Steve Mitcham

Reputation: 5313

You can always create a non-generic base class

public class Bunny 
{
}

public class Bunny<T> : Bunny
{
}

Upvotes: 4

Magnus
Magnus

Reputation: 46909

You can have a non generic bunny class that the generic one inherits from.

public class BunnyManager
{
    public Bunny<T> GetBunny<T>(string someJson)
    {
       return new Bunny<T>(someJson);
    }

    public Bunny GetBunny()
    {
       return new Bunny();
    }
}

public class Bunny
{

}

public class Bunny<T> : Bunny
{
   T parsedJson { get; set; }

    public Bunny(string someJson)
    {
        if (!string.IsNullOrEmpty(someJson))
            parsedJson = ConvertJsonStringToObject<T>(someJson);
    }
}

Upvotes: 20

Related Questions