public static ConstantExpression Constant(object value, Type type)
{
ContractUtils.RequiresNotNull(type, nameof(type));
TypeUtils.ValidateType(type, nameof(type));
if (type.IsByRef)
{
throw Error.TypeMustNotBeByRef(nameof(type));
}
if (type.IsPointer)
{
throw Error.TypeMustNotBePointer(nameof(type));
}
if (value == null)
{
if (type == typeof(object))
{
return new ConstantExpression(null);
}
if (!type.GetTypeInfo().IsValueType || type.IsNullableType())
{
return new TypedConstantExpression(null, type);
}
}
else
{
Type valueType = value.GetType();
if (type == valueType)
{
return new ConstantExpression(value);
}
if (type.IsAssignableFrom(valueType))
{
return new TypedConstantExpression(value, type);
}
}
throw Error.ArgumentTypesMustMatch();
}
}