55

I have a class that currently has several methods that take integer parameters. These integers map to operations that the application can perform. I'd like to make the class generic so that the consumers of the class can provide an enum type that they have with all the operations in it, then the methods will take parameters of that enum type. However, I want them to be able to not specify a generic type at all, and have it default back to integers with no change in syntax from the current way. Is this possible?

3
  • 2
    Isn't @Vilx- solution a good approach and better answer? Sep 13, 2017 at 5:21
  • 2
    @Max Schmeling After the first answer was posted (and after it was accepted, I assume) the correct answer was provided. For the benefit of the future searchers, could you accept the correct answer, please.
    – Brondahl
    Sep 25, 2018 at 21:08
  • 1
    So I realize these questions are from forever ago.. but this is a duplicate: stackoverflow.com/q/707780
    – fqhv
    May 21, 2019 at 1:42

6 Answers 6

146

So... why not use simple inheritance? Like:

class MyGenericClass<T>
{
}

class MyGenericClass : MyGenericClass<int>
{
}

This way you can write both ways:

var X = new MyGenericClass<string>();
var Y = new MyGenericClass(); // Is now MyGenericClass<int>
2
  • The only sad part is that this is limited to generic classes. In cases where it makes more sense to have a struct (which are many) then it still seems there's no convenient alternative.
    – Maxx
    Feb 21, 2020 at 18:20
  • 1
    @Maxx - Well, you can do a using ShortcutType = MyType<int>; at the start of the file where you want to use it. At the end of the day, it's just convenience anyway.
    – Vilx-
    Feb 21, 2020 at 19:14
10

You can't do it in the definition of the class:

var foo = new MyGenericClass(); // defaults to integer... this doesn't work
var bar = new MyGenericClass<MyEnum>(); // T is a MyEnum

If really value the implicitness of the default type being int, you'll have to do it with a static factory method, although I don't see the value of it.

public class MyGenericClass<T>
{
    public static MyGenericClass<T> Create()
    {
        return new MyGenericClass<T>();
    }
    public static MyGenericClass<int> CreateDefault()
    {
        return new MyGenericClass<int>();
    }
}

See below for how you really don't benefit from the above.

var foo = MyGenericClass<MyEnum>.Create();
var bar1 = MyGenericClass.CreateDefault(); // doesn't work
var bar2 = MyGenericClass<int>.CreateDefault(); // works, but what's the point

If you want to take it even farther, you can create a static factory class that will solve this, but that's an even more ridiculous solution if you're doing it for no other reason than to provide a default type:

public static class MyGenericClassFactory
{
    public static MyGenericClass<T> Create<T>()
    {
        return new MyGenericClass<T>();
    }
    public static MyGenericClass<int> Create()
    {
        return new MyGenericClass<int>();
    }
}

var foo = MyGenericClassFactory.Create(); // now we have an int definition
var bar = MyGenericClassFactory.Create<MyEnum>();
2
  • 2
    yeah, I don't want to introduce that complexity. the default isn't extremely important, it just would have been nice. i didn't know of any way to do it, but I wanted to check with all you guys first to make sure. thanks for the answer Jul 8, 2009 at 17:46
  • 5
    This answer is incomplete - it misses the very easy way of achieving the desired default. See Vilx-'s answer below.
    – Brondahl
    Sep 25, 2018 at 21:06
9

Keep your original version (non-generic version) and create a generic version of it.

Then call the generic version from your non-generic version.

void Main()
{
    DoSomething(2);
    DoSomething(EnumValue);
}
    
public void DoSomething(int test) {
    DoSomething<int>(test);
}
    
// Define other methods and classes here
public void DoSomething<T>(T test) {
    Console.WriteLine(test);
}
1
  • The generic parameter type will be the same for all methods, so I would like it at the class level. I know I could make a generic version and then inherit from it for the int version, but I was just hoping to get it all in one... but I didn't know of any way to do that. I guess it's not possible in as simple a way as I was hoping. Jul 8, 2009 at 17:45
2

The compiler can infer the type arguments on methods most of the time based on the type of the arguments passed:

public void DoSomething<T>(T test) {
}

can be called with

DoSomething(4);                   // = DoSomething<int>(4);
DoSomething(MyEnum.SomeValue);    // = DoSomething<MyEnum>(MyEnum.SomeValue);

By the way, you can have non-generic overloads of a generic method too.

1
  • I'm looking for the class to be sort of "optionally generic". I don't think it's possible so I'll just have to make generic methods with non-generic overloads... I was looking for this "SecurityContext sec = new SecurityContext();" (which would create it using integers for parameters, and then "SecurityContext<MyOperations> sec = new SecurityContext<MyOperations>();" which would create it using MyOperations for parameters Jul 8, 2009 at 17:42
2

I'm sure you've moved on from this, however I was working through a similar issue and found this solution that uses a context of "using" I was not familiar with. They need to put it in their namespace, so its not completely perfect.

namespace mygeneric
{
    public class SecurityContext<T>
    {

    }
}

namespace mytest
{
    using SecurityContext = mygeneric.SecurityContext<int>;
    using mygeneric;

    enum MyContexts
    {
        User,
        Admin
    }
    class MyTest
    {
        SecurityContext myDefaultContext;
        SecurityContext<MyContexts> mySpecialContext;
    }
}
1
  • 1
    This is very cool and would probably be used for evil. :-) Nov 17, 2020 at 19:30
0

The compiler can infer the type arguments on fields most of the time based on the type of the arguments passed:

import lombok.Data;

@Data
public class MyClass<T> {

    private T myField;
}

can be used as,

MyClass myClass = new MyClass();
String abc = "hello world !";
myClass.setMyField(abc);
System.out.println("test generic class with generic field = " + myGenericClass.getMyField());

and that should result into,

test generic class with generic field = hello world !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.