Will the following code compile?
 
internal sealed class SomeGenericClass<T> 
{ 
     public static T SomeMethod() 
     { 
          return new T(); 
     }
}
 
Explanation
It will not compile, because constraint is not specified (there is a call of public constructor without parameters, but not all reference types have it). In order for the code to compile it's required to add a constraint, for example:
 
internal sealed class SomeGenericClass<T> where T : struct {
   public static T SomeMethod() { 
       return new T(); 
   } 
}
 
or
 
internal sealed class SomeGenericClass<T> where T : new() { 
   public static T SomeMethod() { 
       return new T(); 
    } 
} 

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
C# quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes