Ian Davis
Ian Davis

Reputation: 19443

How to return a class with a generic type by passing in the type

I have a class which uses a generic type,

public class BaseClass<T> {
  public T Data { get; set; }
  public BaseClass(T data) {
    this.Data = data;
  }
  public BaseClass() { }
}

I want to create a method that returns a BaseClass<T> object, so I'm trying this:

public BaseClass<T> NoData() {
  return new BaseClass<T>(null);
}

and call it with something like return NoData<MyTClass>();

I'm getting an error tho with the <T>, The type or namespace 'T' cannot be found

Is this possible to do in c#? Thanks!

Upvotes: 0

Views: 61

Answers (1)

D Stanley
D Stanley

Reputation: 152634

You just need to add a generic parameter to the method name:

public BaseClass<T> NoData<T>() {
  return new BaseClass<T>(null);
}

But since you don't specify that T is a class, you need to use the more general default(T):

public BaseClass<T> NoData<T>() {
  return new BaseClass<T>(default(T));
}

And since you have a default constructor that essentially does the same thing you could also do:

public BaseClass<T> NoData<T>() {
  return new BaseClass<T>();
}

Upvotes: 4

Related Questions