C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The result of the new operator and the constructor invocation is an instance of the type.
Here: The Perl class contains 2 user-defined constructors—these are invoked with the new operator.
Tip: To call the constructors in the Perl type, specify the new operator, and then use the Perl() type with a formal parameter list.
ParametersNext: We instantiate the Program class. The Program type declaration has the implicit default constructor (which is added automatically).
C# program that uses new operator
using System;
class Perl
{
public Perl()
{
// Public parameterless constructor.
Console.WriteLine("New Perl()");
}
public Perl(int a, int b, int c)
{
// Public parameterful constructor.
Console.WriteLine("New Perl(a, b, c)");
}
}
class Program
{
static void Main()
{
// Create a new instance of the Perl type.
// ... Use the new operator.
// ... Then reassign to another new object instance.
Perl perl = new Perl();
perl = new Perl(1, 2, 3);
// Another Perl instance.
Perl perl2 = null;
perl2 = new Perl();
// Instantiate the Program class.
// ... No constructor is declared, so there is a default.
Program program = new Program();
Console.WriteLine(program != null);
}
}
Output
New Perl()
New Perl(a, b, c)
New Perl()
True
Here: This program introduces 2 classes, A and B. The B class derives from the A class.
Next: Class A has a public method Y, while class B has a public method Y that uses the new keyword to hide the base method Y.
Note: The new keyword prevents a warning from the C# compiler when this program is compiled.
Warning: A "new" method can be confusing. Hiding methods is often not a good idea in program design.
C# program that uses new modifier
using System;
class A
{
public void Y()
{
Console.WriteLine("A.Y");
}
}
class B : A
{
public new void Y()
{
// This method hides A.Y.
// It is only called through the B type reference.
Console.WriteLine("B.Y");
}
}
class Program
{
static void Main()
{
A ref1 = new A(); // differentnew.
A ref2 = new B();
B ref3 = new B();
ref1.Y();
ref2.Y();
ref3.Y();
}
}
Output
A.Y
A.Y
B.Y
Then: The constructor logic is executed and it can change the values from their defaults.
Tip: A common programming error occurs when a developer does not realize a method is actually hiding (not overriding) a base method.
Tip 2: Many design features in the C# language are intended to reduce common errors like this one.
Also: When declaring generic classes, you can specify that a type must be a reference type with the new() constraint.
Generic Class, Method