Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is overloaded method differing in ref only CLS compliant

Common Language Specification is quite strict on method overloads.

Methods are allowed to be overloaded only based on the number and types of their parameters, and in the case of generic methods, the number of their generic parameters.

Why is this code CLS compliant (no CS3006 warning) according to csc?

using System;

[assembly: CLSCompliant (true)]

public class Test {
    public static void Expect<T>(T arg)
    {
    }

    public static void Expect<T>(ref T arg)
    {
    }

    public static void Main ()
    {
    }
}
like image 974
Marek Safar Avatar asked Sep 26 '12 08:09

Marek Safar


1 Answers

This is CLS-compliant because the types differ. The rules for overloading are requiring one (or more) of the criteria to be met, not all of them at the same time.

A ref T (or out T, which is using the same with same type different semantics) is declaring a "reference" to a T reference (for classes) or the instance (in case of value types).

For more details, look up the Type.MakeByRefType() method - it creates the type representing a reference to the original type, e.g. for a T this returns a T& (in C++ notation).

like image 100
Lucero Avatar answered Nov 01 '22 03:11

Lucero