4
interface<T> where T : class

for example

public interface iSend<T> where T : class

What does the above code mean?

Why to use this?

When to use this?

MattC
  • 3,984
  • 1
  • 33
  • 49
MARKAND Bhatt
  • 2,428
  • 10
  • 47
  • 80
  • 3
    You should read about generics in c# instead of questioning about it. Here is article on MSDN http://msdn.microsoft.com/en-us/library/512aeb7t.aspx – Sarrus Feb 14 '14 at 11:56
  • 1
    Also see: [What does denote in C#](http://stackoverflow.com/questions/9857180/what-does-t-denote-in-c-sharp) – Theraot Feb 14 '14 at 12:07

3 Answers3

9

Check my full post here : Constrain on custom generic type which talks about different type of generic constrain

it's Reference Type Constrain

Constrain ensure that type argument is Reference Type. i.e Class, Interface, Delegates, Array etc.

interface iSend<T> where T : class

Example

Valid             InValid
A<MyClass>        A<int>
A<InterfaceME>    A<float>   
A<float[]>  

Note : Always come first when multiple constrain applied.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
5

From the docs:

Constraints on Type Parameters

When you define a generic class, you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class. If client code tries to instantiate your class by using a type that is not allowed by a constraint, the result is a compile-time error. These restrictions are called constraints.
...
where T : class: The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

If you use this constraint, then T has to be a reference type (and no value type).

You do this e.g. to be able to use null, since reference types can be null and value types can not.

sloth
  • 99,095
  • 21
  • 171
  • 219
2

There are called generic type constraints.

Above code means, you have an generic interface iSend and it takes only a Reference type as Type Parameter

When you want to limit the Type Parameters for iSend to be Reference types

  • Why to use this? and when to use this? – MARKAND Bhatt Feb 14 '14 at 11:51
  • 2
    @MARKANDBhatt I don't have examples that applies to interfaces, some cases when you may want to constraint to reference types are: when you depend on ReferenceEquals, when you are using weak references, or when you want to able to do an atomic read or write on a complex type. It may also be a shorthand to say that the variables of the generic type should be able to be null. – Theraot Feb 14 '14 at 12:04