By using Activator.CreateInstance we can create objects of a class, even if the constructor is private.
Is there anyway to prevent this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Reflection breaks encapsulation in general. Any private member of any type (constructor, method, property, field, you name it) can be accessed using reflection (
Activator.CreateInstancefalls under this umbrella).That said, if you want your type not to be instantiatable via the overload of
Activator.CreateInstancegenerally used to overcomeprivateconstructors, you could get rid of its parameterless constructor for your type altogether (by defining only constructors that take parameters).You still can’t do anything about someone using one of the overloads that specifies parameters, though.