C# Keywords Tutorial Part 55: new
The new keyword in the object-oriented programming language C# enables programmers to generate fresh instances of classes and structs. This term is essential to C# programming since it allows developers to construct new objects that belong to a certain class or struct.
This blog article will examine the new C# term in more detail and provide code examples of how to use it.
Making Class and Structure Instances Using the New Keyword
An instance of a class or struct can be created in C# by using the new keyword. The following syntax is used to make a class instance:
ClassName obj = new ClassName();
Here, ClassName
is the name of the class you want to create an instance of, and obj
is the name of the object that holds the reference to the newly created instance.
Similarly, to create an instance of a struct, you use the following syntax:
StructName obj = new StructName();
Here, StructName
is the name of the struct you want to create an instance of, and obj
is the name of the variable that holds the reference to the newly created instance.
Shadowing Inherited Members Using the new
Keyword
In C#, the new
keyword can also be used to shadow inherited members of a class or struct. When you inherit a member from a base class or struct, you can define a member in the derived class or struct with the same name to override the inherited member. However, if you want to keep the inherited member intact and define a new member with the same name, you can use the new
keyword to shadow the inherited member.
Consider the following example:
class BaseClass { public void Print() { Console.WriteLine("Base Class"); } } class DerivedClass : BaseClass { public new void Print() { Console.WriteLine("Derived Class"); } }
In this example, DerivedClass
inherits the Print()
method from BaseClass
. However, it defines its own Print()
method with the same name using the new
keyword. This creates a new member that shadows the inherited Print()
method without overriding it.
Leave a Reply