For example, consider the following code snippet
Contract.Requires<CustomException>(arg !=null)
during the runtime, the following code will throw the exception of type CustomException
. Does code contract use Activator to create an instance of the CustomException
or how do we use it. I would like to implement a similar one in my code too for another purpose.
According to Microsoft Reference Source, the method you refer to is implemented like this:
public static void Requires<TException>(bool condition) where TException : Exception
{
AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>");
}
As you can see, there isn't any functional conjunction to the generic TException
type parameter. This is because ccrewrite.exe
handles this after compilation.
As for your second question, you can always create an instance of a given type with two different ways:
First, with a new()
constraint on your generic type parameter:
public static void CreateInstance<TClass>() where TClass : new()
{
TClass instance = new TClass();
// ...
}
Second, via reflection using Activator
:
public static void CreateInstanceWithReflection<TClass>()
{
TClass instance = Activator.CreateInstance<TClass>();
// ...
}
The latter method is useful if you e.g. don't know the real type yet and want to search it via reflection first. Please note that creating an instance via reflection also requires your class to provide a parameterless constructor. If it doesn't, please refer to this question for advice.