g18c g18c - 1 year ago 58
C# Question

What do the 'in' and '@' keywords do when defining interfaces in C#?

Given the below interface declarations:

Declaration A

public interface EventHandler<T>
void Handle(T command);

Declaration B

public interface EventHandler<in T>
void Handle(T @event);

In normal testing these all do the same thing. The
method is called as expected.

In what ways do the above vary, and how do they behave differently in other scenarios?

Answer Source

in specifies a generic type parameter as a contravariant: in (Generic Modifier) (C# Reference). There is also out for covariant.

@ allows you use registered keywords as identifiers:

Keywords are predefined, reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if is a valid identifier but if is not because if is a keyword.

Source: C# Keywords

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download