Strange intellisense behavior with private constructor

Example:

public class Name { public string FirstName { get; private set; } public string LastName { get; private set; } private Name() { } public Name(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } } 

When trying to instantiate this class, C # intellisense displays both the private and public constructor for the new keyword, although one of the constructors is private!

What's even weirder is that when I remove the second argument from the public constructor (delete lastName as an argument to the public constructor), intellisense now correctly only displays the public constructor with the new keyword.

Is this a mistake or am I missing something? I am using VS2008 SP1.

edit: code clarity

+3
source share
4 answers

Wow, this is weird. I just tried this myself on my copy of VS2008 (I also run SP1) and had exactly the same results. When there were several options, the private constructor appeared in Intellisense, but not when there was only one. I guess this is a mistake.

+1
source

Not sure why intellisense shows you weird things. But you must have an abstract base class for your domain objects with an open constructor, so you do not need to transfer your objects to private ones. You should also put things like your properties for your primary keys, etc.

 public abstract class BaseDomainObject{ public BaseDomainObject() { } private int _id; public virtual int Id { get { return _id; } set { _id = value; } } } public SomeDomainObject : BaseDomainObject{ ... } 
0
source

This is probably a mistake, but do not try to fix it. Namely, because there are many scenarios when access to a private constructor is legal. Take the following code snippet. All access to the private constructor is legal

 class Outer { private Outer() { } public Outer Create() { return new Outer(); } class Inner() { void Function1() { new Outer(); } class DoubleInner() { void Function2() { new Outer(); } } } } 
0
source

Although the private constructor appears in Intellisense, the compiler will still use the "inaccessible due to security level" error if you try to compile code that uses it where it is not allowed

0
source

All Articles