Unity doesn't like my 'where' constraints in my C# script

First, I'll show you the basic static function that is causing the compiler error:

static T CreateIfNeededAndReturn<T>( T obj )
    where T : new()
    where T : class
{
    if( obj == null )
    {
        obj = new T();
    }

    return obj;
}

In plain old C# in Visual Studio, this code is fine and I've used a similar construct before. I'm thinking this is a limitation of Mono, since it's a fairly old version of .NET (I'm not sure when multiple 'where' clauses were legalized by the language).

The error that I'm getting in Unity is:

error CS0409: A constraint clause has already been specified for type parameter `T'

It's actually pointing to the second 'where' (i.e. 'where T : class'). It seems pretty obvious at this point, but since I'm no expert in C#, Mono, or Unity by any means, I'm hoping someone has encountered this problem before and has a work around or an explanation as to why this isn't supported/working.

Try using a comma instead of a second where. Like this:

static T CreateIfNeededAndReturn<T>( T obj )    
    where T : new(), class

Actually, you also need to change the order, so it would be

static T CreateIfNeededAndReturn<T>(T obj)
    where T : class, new() {
    if (obj == null) {
        obj = new T();
    }

    return obj;
}

Otherwise, you'll get:

error CS0401: The new() constraint must be the last constraint specified

Btw, I haven't checked this against .NET - but this also doesn't work in more recent versions of Mono. And it would surprise me if it would: This looks like a weird syntax to me, having those two "where"-statements one after the other. Since C# ignores whitespace, you could also write your version:

static T CreateIfNeededAndReturn<T>(T obj) where T : new() where T : class {

Which doesn't look good to me - and I'm pretty sure this also doesn't look too great to the compiler, either ;-)

I think

static T CreateIfNeededAndReturn<T>(T obj) where T : class, new() {

looks much better, doesn't it?

Actually instead of a comma use a semicolon