generics - Is there any compelling reason to not be able to use equal operator(==) for default(T) in C# -



generics - Is there any compelling reason to not be able to use equal operator(==) for default(T) in C# -

the equal operator , default value of generic type 2 handy feature in c#. can't utilize them seamlessly. example, expect next code can compile,

public static bool equalsdefault<t>(t subject){ homecoming subject == default(t); }

unfortunately, it'll fail, though there's counter-intuitive alternative,

public static bool equalsdefault<t>(t subject){ homecoming object.equals(subject, default(t)); }

so question why c# disallows first code snippet?

the reason not work built-in reference equality operator cannot applied value types.

let's take step , note system.object not, in fact, define equality operator ==. c# language defines built-in reference equality operator signature (see section 7.6.10 of c# 5 specification):

bool operator ==(object x, object y);

however, there 2 rules when can applied:

the predefined reference type equality operators require 1 of following:

both operands value of type known reference-type or literal null. furthermore, explicit reference conversion (§6.2.4) exists type of either operand type of other operand. one operand value of type t t type-parameter , other operand literal null. furthermore t not have value type constraint.

the spec notes means error apply operator 2 value types unless type explicitly defines equality operator. since have no constraints, value types allowed , neither of operands null. therefore, built-in equality operator cannot applied , error produced.

to remedy this, constrain t reference type:

public static bool equalsdefault<t>(t subject) t : class { homecoming subject == default(t); }

however need aware above reference comparison. compiler invoke == operator on specific applicable type @ compile time, in case object.

a improve alternative utilize equalitycomparer<t>.default prevent boxing of value types:

public static bool equalsdefault<t>(t subject) { homecoming equalitycomparer<t>.default.equals(subject, default(t)); }

i suppose inquire why c# not designed have default equality operator can applied value types without boxing. not know total reason, suspect might more confusing determine methods calling in situations. think undesirable if in normal methods overloaded operator called in generic methods mechanism used. although can argue can happen reference types.

c# generics

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -