I have a C# generic:
public class Generic<TParameter> { ... }
It does not appear that I can use unbound types as type parameters. I get error CS1031: Type expected
when I try the following:
var lGenericInstance = new Generic<List<>>();
How can I use an unbound type as a generic type parameter? Are there workarounds? My generic class is just using reflection so I can get a list of the provided type's members as strings.
Update: My question about the unbound type has been answered, so I have followed up with a separate question that addresses my specific problem.
Yes, you can define a generic method in a non-generic class in Java.
Generic Methods A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.
The definition of a generic type should never be nullable. The nullability should be defined by the one using this generic. With the current Kotlin version, you can have a "String?" implementation and a "String" implementation.
Try this:
class Foo<T> { }
class Bar<T> { }
Type unboundBar = typeof(Bar<>);
Type unboundFoo = typeof(Foo<>);
Type boundFoo = unboundFoo.MakeGenericType(new[] { unboundBar });
Console.WriteLine(boundFoo.Name);
Conosle.WriteLine(boundFoo.GetGenericArguments().First().Name);
Note that you can't write
Type boundFoo = typeof(Foo<Bar<>>)
because the specification explicitly states:
An unbound generic type can only be used within a typeof-expression (§7.6.11).
(Bar<>
is not being used as a parameter to the typeof-expression here, rather, it's a generic type parameter to the parameter to a typeof-expression.)
However, it's perfectly legal within the CLR, as the above using reflection shows.
But what are you trying to do? You can't have instances of unbound types, so I don't get it.
the question you are asking is in my opinion wrongly formulated.
the error you have in your code is because you cannot have List<>
anywhere as it requires a type to be provided.
this one: var lGenericInstance = new Generic<List<>>();
fails on List
, not on Generic
... well on both because they are chained... :)
so your question is more like:
why cannot I create an object of type List<>
? or why can't I specify List<>
as T for my generic class?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With