Posted by: eygneph | 2010/02/22

C# Constraints Syntax

Well, this seems to be straightforward for C# expert but still confused me for hours, for a newbie like me. If you need to constraint generic type to an specific type, you can use the following syntax:

void Foobar<T>(T[] myarray) where T : MyType

But, if you only need to constraint the generic T to value type(that is, struct), you cannot just say:

void Foobar<T>(T[] myarray) where T : System.ValueType

This will gives you an compiler error, complaining “error CS0702: Constraint cannot be special class ‘System.ValueType'”. Okay, I admit I stuck with this for an hour, without referring to the super basic C# generic programming guide. So here’s the right syntax:

void Foobar<T>(T[] myarray) where T : struct

Done! Totally no idea why C# choose this way. Also, by writing this post, I find this post is insanely useful for posting source code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: