user1229895
user1229895

Reputation: 2319

Generic Constructor with zero or more arguments in C#

I was wondering what would be the best way (in C#) to combine my two classes below (so that I can choose either to specify a type or not, in the case when one isn't necessary)? Also what would be the recommended method for coding MyClass to take in more arguments if necessary? Thanks!

public class MyClass{

    public MyClass() {}
}

public class MyClass<T> {

    T myvariable;   

    public MyClass<T>(T arg){       
        myvariable = arg;
    }

    // how can I handle MyClass(arg1, arg2, ....?
    // would I need to create classes MyClass<T,U,...> for each number of argument?
}

so that I can delcare MyClass with either...

MyClass my1 = new MyClass()
MyClass<string> my2 = new MyClass("test");

Upvotes: 1

Views: 602

Answers (2)

Erich Schreiner
Erich Schreiner

Reputation: 2058

You could implement static factory methods to avoid specifying a type explicitly, e.g.

public static MyClass<Void> create() {
    return new MyClass<Void>() 
}

and

public static <T> MyClass<T> create(T type) {
    return new MyClass<T>(type); 
}

Clients can then create new instances like so:

MyClass<Void> noType = MyClass.create();
MyClass<String> withType = MyClass.create("some type");
MyClass<Integer> withInt = MyClass.create(123);

(provided you have enabled auto-boxing).

Upvotes: 1

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

so that I can choose either to specify a type or not, in the case when one isn't necessary

Just merge them and create two constructors:

class MyClass<T> {

    T myvariable;

    public MyClass(){

    }

    public MyClass(T arg){
        myvariable = arg;
    }
}

If you don't need a generic type, use Void (not void):

public static void main(String[] args) {
    final MyClass<Void> my1 = new MyClass<Void>();
    final MyClass<String> my2 = new MyClass<String>("Test");
}

coding MyClass to take in more arguments if necessary

If you need a variable number of arguments of same type T, use varargs:

class MyClass<T> {

    T[] myvariable;

    public MyClass(){

    }

    public MyClass(T... arg){
        myvariable = arg;
    }

}

There is no way to declare variable number of heterogenous types like <T, U, V...>.

Upvotes: 3

Related Questions