Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator as and generic classes

I want to make a method:

object Execute() {     return type.InvokeMember(..); } 

to accept a generic parameter:

T Execute<T>() {     return Execute() as T;      /* doesn't work:     The type parameter 'T' cannot be used with the 'as' operator because     it does not have a class type constraint nor a 'class' constraint */      // also neither typeof(T), nor T.GetType() are possible      return (T) Execute(); // ok } 

But I think operator as will be very useful: if result type isn't T method will return null, instead of an exception! Is it possible to do?

like image 261
abatishchev Avatar asked Mar 28 '09 20:03

abatishchev


People also ask

What are generic classes?

Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on.

What is the difference between generic class and generic method?

A generic class or structure can contain nongeneric procedures, and a nongeneric class, structure, or module can contain generic procedures. A generic procedure can use its type parameters in its normal parameter list, in its return type if it has one, and in its procedure code.

What are generic functions and generic classes?

Generic functions are functions declared with one or more generic type parameters. They may be methods in a class or struct , or standalone functions. A single generic declaration implicitly declares a family of functions that differ only in the substitution of a different actual type for the generic type parameter.

Can generic be used as class name?

Generics in Java are implemented by erasure, so no, you won't be able to get the name of the "type" which was used to create your generic collection at run-time.


1 Answers

You need to add

where T : class 

to your method declaration, e.g.

T Execute<T>()  where T : class { 

By the way, as a suggestion, that generic wrapper doesn't really add much value. The caller can write:

MyClass c = whatever.Execute() as MyClass; 

Or if they want to throw on fail:

MyClass c = (MyClass)whatever.Execute(); 

The generic wrapper method looks like this:

MyClass c = whatever.Execute<MyClass>(); 

All three versions have to specify exactly the same three entities, just in different orders, so none are any simpler or any more convenient, and yet the generic version hides what is happening, whereas the "raw" versions each make it clear whether there will be a throw or a null.

(This may be irrelevant to you if your example is simplified from your actual code).

like image 79
Daniel Earwicker Avatar answered Sep 21 '22 12:09

Daniel Earwicker