According To Microsoft Class always contain Default Constructor which is private then how is possible to initiate the Object in another Class.
You are simply misreading that page. For a class without a defined constructor:
class C {}
There exists a default, public constructor, C().
If you explicitly declare a constructor, then that default constructor won't exist. If you declare your constructor like:
class C
{
C()
}
then it will be private, as all class members are private unless an explicit public, internal or protected access modifier is used.
You've missed the most important part of the article:
A private constructor is a special instance constructor. It is
generally used in classes that contain static members only. If a class
has one or more private constructors and no public constructors, other
classes (except nested classes) cannot create instances of this class
The common use case they show in the article talks about using static members only via the said class, like this:
class NLog
{
// Private Constructor:
private NLog() { }
public static double Foo = 3.284;
}
Classes do not have default private constructor, they have a public one (except for abstract classes):
If the class is abstract then the declared accessibility for the
default constructor is protected. Otherwise, the declared
accessibility for the default constructor is public. Thus, the default
constructor is always of the form
"The declaration of the empty constructor prevents the automatic generation of a default constructor" (https://msdn.microsoft.com/en-us/library/kcfb85a6.aspx)
If you declare an empty constructor (whether it is private or not, it doesn't matter), you prevent the generation of the default one (which is always public).
Related
When declaring a class in C# without specifying if the class is a static or non-static class which will it default to?
EDIT: Here's an article I wrote based on this discussion.
https://hackernoon.com/c-static-vs-instance-classes-and-methods-50fe8987b231
If you don't declare the class as static then its members can be either static or non-static.
A static class can only have static members.
You can invoke non-static members only on instances of the class.
You can invoke static members only on the class itself.
Also, in your class declaration, there are no parentheses.
If the "static" is not specified, it will require an instance of the class to be used (Unless the member itself is specified as static).
If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable.
From: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/classes
A class is always an instance class unless you specify otherwise
public class ParentBaseClass
{
public ParentBaseClass()
{
// Parameter less constructor
}
public ParentBaseClass(string type)
{
// single parameter constructor
}
public ParentBaseClass(Entity model)
{
// entity type constructor
}
public ParentBaseClass(string type, bool IsNewEntity)
{
// two parameter constructor
}
public ParentBaseClass(string type, bool IsNewEntity, Entity model)
{
// three parameter constructor
}
}
public class ChildClassFirst : ParentBaseClass
{
public ChildClassFirst() : base("Customer", false)
{
// implementation of 4th constructor having string, bool parameters.
}
}
in child class I implemented only one constructor of parent class having two parameters. why there no need to implement other constructor? can anyone explain me? please consider other constructor may have MVC Model class or other entity class of dbContext.
Every child class calls it's base class constructor, if there is a parameter-less constructor and we haven't implemented any parameter based constructor in it, the parameter-less is automatically called, but like in your case you are specifying which constructor to be used when ChildClassFirst is instantiated, so now the calling code has only access to this parameter-less constructor to instantiate an object of ChildClassFirst which in turn will instantiate the parent class object using the parameter based constructor which is called using base().
In short, Child class only needs to specify one base class construction which would be called during instantiation of child class, and when there is none specified the default would be parameter-less constructor which would get called, but remember the parameter-less only exists if we have no parameterized constructor specified in the class.
Abstract classes are designed for inheritance by other classes, usually more than one. Different derived classes may need to construct their abstract base class in slightly different ways. Hence, an abstract class can supply different constructors for different derived classes.
Non-abstract derived classes, on the other hand, are designed to be instantiated by the class users. User construction needs may be completely different from the needs of the class itself, so derived classes provide their own constructors.
Therefore, the two sets of constructors are completely independent of each other: they serve different needs. Derived classes can provide more or fewer constructors, and the signatures of their constructors may be similar or completely different. This is exactly the case in your code: ChildClassFirst provides a parameterless constructor, while its abstract base class provides two constructors with different sets of parameters. As long as you provide any constructor in the derived class, C# compiler is fine with your code.
A default constructor has no parameters. And nor does a constructor that you write with no parameters. So what is the ultimate difference in c#?
Added to this when you inherit a default constructor and a parameterless constructor are they exposed on the inheritting type exactly the same? Because my IOC container doesn't seem to think so. (Unity).
Cheers,
Pete
The "default" constructor is added by the C# compiler if your class does not contain an explicit instance constructor. It is a public, parameterless constructor. If you have created an explicit non-public, parameterless constructor, Unity will not be able to use it in the same way it would have used a public constructor (regardless of whether this was generated by the compiler, and regardless of whether it had parameters).
You can override the behaviour of the default constructor by creating a parameterless constructor. A common use of this is when you have a custom object as a member of your class and you need to initialize it with a default value when an instance of your class created.
A default constructor is a synonym for a parameterless constructor.
Adding to #Sachin Kainth and #Fredrik Leijon answers, in .NET (also in Java) constructors are not inherited.
You either explicitly call a base constructor or, by default, the base parameterless constructor is invoked.
If you don't add a constructor then a default constructor with no parameters is inserted for you. If you add a constructor (with or without parameters) no default constructor is generated
I'll let the code speak for itself:
public class ThisHasADefaultConstructor
{
}
public class ThisHasAParameterlessConstructor
{
public ThisHasAParameterlessConstructor()
{
}
}
Note that a default constructor is effectively a parameterless constructor that is automatically generated when you don't specify a constructor (with or without parameters).
Maybe you need the the parameterless constructor if you want to have more constructors. Let's say one without parameters and one with parameters.
if your class has only a constructor with parameters, you're are not allowed to use the parameterless constructor, unless you define one, in other words, no default parameterless constructor is provided if you define a custom constructor in your class.
MSDN states:
A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated using the new operator and no arguments are provided to new.
So the default constructor does not have to be automatically generated. A hand-written, parameterless constructor is also the default constructor.
This actually makes sense when you look at derived classes:
class A
{
public A() { ... } // do something
public A(object o) { ... } // do something else
}
class B
{
public B() { ... }
}
Which A constructor is called while creating B? The default one.
Default constructor refers to a constructor without parameters, wheter created automatically or created by you.
A defualt constructor is created automatically if you don't declare any other instance constructor, with or without paramters. (declaring a static constructor won't avoid the defautl constructor to be automatically created).
The constructors of a hierarchy of classes are not inherited, but all the constructor on the inheriting chain are invoked when using the constructor of a derived class, starting from the root of the hierarchy. Unless you specify which constructor to invoke, the default constructor of each class is invoked.
public class Base
{
public Base()
{
}
}
public class Derived : Base
{
public Derived()
{
}
}
// invokes, the Base() construtor, and then the Derived() constructor
var d = new Derived();
You can also explicitly invoke a base class constructor, with or without parameters like so:
// Derived class explicitly invoking base class constructor.
public Derived() :base()
{
}
If you want, you can invoke a base class constructor with parameters like so:
public Derived(int j) :base(j)
or so
public Derived() :base(23)
In this last code sample, if you create a Derived object with the default constructor, the constructor invoked in the base class isn't the default one, but a constructor with an integer parameter, invoked with the parameter 23.
(of course, this constructor with parameter must exist in the Base class).
You can only invoke explicitly the constructor of the inmediate base class.
A default contructor is called implicitly by the comppiler, except if you have explicitly created a new one (with no parameters).
How is it possible that class in C# may has no constructors defined?
For instance I have a class
internal class TextStyle
{
internal string text = "";
internal Font font = new Font("Arial", 8);
internal Color color = Color.Black;
}
And in the code this class is instantiated as
TextStyle textParameters = new TextStyle();
If you don't declare any constructors for a non-static class, the compiler provides a public (or protected for abstract classes) parameterless constructor for you. Your class effectively has a constructor of:
public TextStyle()
{
}
This is described in section 10.11.4 of the C# 4 spec:
If a class contains no instance constructor declarations, a default instance constructor is automatically provided. That default constructor simply invokes the parameterless constructor of the direct base class. If the direct base class does not have an accessible parameterless instance constructor, a compile-time error occurs. If the class is abstract, then the declared accessibility for the default constructor is protected. Otherwise, the declared accessibility for the default constructor is public.
The only classes in C# which don't have any instance constructors are static classes, and they can't have constructors.
(inspired by this comment)
Is there ever a situation in which you need to use the private keyword?
(In other words, a situation in which omitting the keyword would result in different behavior)
public class Foo
{
public int Bar { get; private set; }
}
Omitting the word 'private' would change the accessibility.
a situation in which omitting the keyword [private] would result in different behavior
David Yaw's answer gave the most usual situation. Here is another one:
In Account_generated.cs:
// Generated file. Do not edit!
public partial class Account
{
...
private partial class Helper
{
...
}
...
}
In AccountHandCoded.cs:
public partial class Account
{
...
public partial class Helper
{
...
}
...
}
The above code will not compile. The first "part" of Account requires the nested class Helper to be private. Therefore the attempt by the hand-coder to make Helper public must fail!
However, had the first part of the class simply omitted the private keyword, all would compile.
So for partial classes (and structs, interfaces), the access-level-free declaration
partial class Name
means "the other 'parts' of this class are allowed to decide what the accessibility should be".
Whereas explicitly giving the default accessibility (which is internal for non-nested types and private for nested ones) means "this class must have the most restricted access possible, and the other 'parts' cannot change that fact".
private isn't about the runtime behaviour. It's to make your application maintainable. What's hidden by private can only ever affect the code outside its class through the public or protected members.
So the answer is 'no' for runtime behaviour, 'yes' for developer behaviour!
In C# version 7.2 and later.
The private protected keyword combination is a member access modifier. A private protected member is accessible by types derived from the containing class, but only within its containing assembly.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private-protected