Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generics: Constraining T where T : Object doesn't compile; Error: Constraint cannot be special class 'object'

Tags:

When I constrain T with : Object like this:

public interface IDoWork<T> where T : Object {     T DoWork(); } 

I get the error:

Constraint cannot be special class 'object'

Does that mean there is an implied difference with the following that does compile?

public interface IDoWork<T> // where T : Object {     T DoWork(); } 
like image 552
makerofthings7 Avatar asked May 17 '12 23:05

makerofthings7


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


2 Answers

If you want to constrain a generic type to be a reference type, use : class.

public interface IDoWork<T> where T : class {     T DoWork(); } 

This will forbid the generic type from being a value type, such as int or a struct.

like image 135
Douglas Avatar answered Oct 21 '22 06:10

Douglas


There is no difference between the two constraints, except for that one is disallowed for being useless to explicitly state.

The C# 4.0 language specification (10.1.5 Type parameter constraints) says two things about this:

The type must not be object. Because all types derive from object, such a constraint would have no effect if it were permitted.

...

If T has no primary constraints or type parameter constraints, its effective base class is object.

In your comment, you said that you were trying to make T be of type Void. Void is a special type that indicates that there is no return type and cannot be used in place of T, which requires an appropriate concrete type. You will have to create a void version of your method and a T version if you want both.

like image 37
Chris Hannon Avatar answered Oct 21 '22 06:10

Chris Hannon