- new modifier (C# Reference)
- Examples
- C# language specification
- See also
- оператор new — new оператор создает новый экземпляр типа.
- Вызов конструктора
- Типизированный по целевому объекту new
- создание массива
- Создание экземпляров анонимных типов
- Уничтожение экземпляров типа
- Возможность перегрузки оператора
- Спецификация языка C#
- См. также
- new operator — The new operator creates a new instance of a type
- Constructor invocation
- Target-typed new
- Array creation
- Instantiation of anonymous types
- Destruction of type instances
- Operator overloadability
- C# language specification
- See also
new modifier (C# Reference)
When used as a declaration modifier, the new keyword explicitly hides a member that is inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base class version. This assumes that the base class version of the member is visible, as it would already be hidden if it were marked as private or, in some cases, internal . Although you can hide public or protected members without using the new modifier, you get a compiler warning. If you use new to explicitly hide a member, it suppresses this warning.
You can also use the new keyword to create an instance of a type or as a generic type constraint.
To hide an inherited member, declare it in the derived class by using the same member name, and modify it with the new keyword. For example:
public class BaseC < public int x; public void Invoke() < >> public class DerivedC : BaseC < new public void Invoke() < >>
In this example, BaseC.Invoke is hidden by DerivedC.Invoke . The field x is not affected because it is not hidden by a similar name.
Name hiding through inheritance takes one of the following forms:
- Generally, a constant, field, property, or type that is introduced in a class or struct hides all base class members that share its name. There are special cases. For example, if you declare a new field with name N to have a type that is not invocable, and a base type declares N to be a method, the new field does not hide the base declaration in invocation syntax. For more information, see the Member lookup section of the C# language specification.
- A method introduced in a class or struct hides properties, fields, and types that share that name in the base class. It also hides all base class methods that have the same signature.
- An indexer introduced in a class or struct hides all base class indexers that have the same signature.
It is an error to use both new and override on the same member, because the two modifiers have mutually exclusive meanings. The new modifier creates a new member with the same name and causes the original member to become hidden. The override modifier extends the implementation for an inherited member.
Using the new modifier in a declaration that does not hide an inherited member generates a warning.
Examples
In this example, a base class, BaseC , and a derived class, DerivedC , use the same field name x , which hides the value of the inherited field. The example demonstrates the use of the new modifier. It also demonstrates how to access the hidden members of the base class by using their fully qualified names.
public class BaseC < public static int x = 55; public static int y = 22; >public class DerivedC : BaseC < // Hide field 'x'. new public static int x = 100; static void Main() < // Display the new value of x: Console.WriteLine(x); // Display the hidden value of x: Console.WriteLine(BaseC.x); // Display the unhidden member y: Console.WriteLine(y); >> /* Output: 100 55 22 */
In this example, a nested class hides a class that has the same name in the base class. The example demonstrates how to use the new modifier to eliminate the warning message and how to access the hidden class members by using their fully qualified names.
public class BaseC < public class NestedC < public int x = 200; public int y; >> public class DerivedC : BaseC < // Nested type hiding the base type members. new public class NestedC < public int x = 100; public int y; public int z; >static void Main() < // Creating an object from the overlapping class: NestedC c1 = new NestedC(); // Creating an object from the hidden class: BaseC.NestedC c2 = new BaseC.NestedC(); Console.WriteLine(c1.x); Console.WriteLine(c2.x); >> /* Output: 100 200 */
If you remove the new modifier, the program will still compile and run, but you will get the following warning:
The keyword new is required on 'MyDerivedC.x' because it hides inherited member 'MyBaseC.x'.
C# language specification
For more information, see The new modifier section of the C# language specification.
See also
оператор new — new оператор создает новый экземпляр типа.
Оператор new создает экземпляр типа. Ключевое слово new можно также использовать как модификатор объявления члена или ограничение универсального типа.
Вызов конструктора
Для создания экземпляра типа обычно вызывается один из конструкторов этого типа с помощью оператора new :
var dict = new Dictionary(); dict["first"] = 10; dict["second"] = 20; dict["third"] = 30; Console.WriteLine(string.Join("; ", dict.Select(entry => $": "))); // Output: // first: 10; second: 20; third: 30
Для создания экземпляра объекта и его инициализации в одном операторе можно использовать инициализатор объекта или элементов с оператором new , как в следующем примере:
var dict = new Dictionary < ["first"] = 10, ["second"] = 20, ["third"] = 30 >; Console.WriteLine(string.Join("; ", dict.Select(entry => $": "))); // Output: // first: 10; second: 20; third: 30
Типизированный по целевому объекту new
Начиная с версии C# 9.0 выражения вызова конструктора имеют целевой тип. То есть, если известен целевой тип выражения, вы можете опустить имя типа, как показано в следующем примере:
List xs = new(); List ys = new(capacity: 10_000); List zs = new() < Capacity = 20_000 >; Dictionary lookup = new() < [1] = new() < 1, 2, 3 >, [2] = new() < 5, 8, 3 >, [5] = new() < 1, 0, 4 >>;
Как показано в предыдущем примере, выражение new с целевым типом всегда указывается в скобках.
Если целевой тип выражения new неизвестен (например, если вы используете ключевое слово var ), нужно указать имя типа.
создание массива
С помощью оператора new можно также создать экземпляр массива, как показано в следующем примере:
var numbers = new int[3]; numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; Console.WriteLine(string.Join(", ", numbers)); // Output: // 10, 20, 30
Чтобы создать экземпляр массива и заполнить его элементами в одном операторе, используйте синтаксис инициализации массива. В следующем примере показаны различные способы сделать это:
var a = new int[3] < 10, 20, 30 >; var b = new int[] < 10, 20, 30 >; var c = new[] < 10, 20, 30 >; Console.WriteLine(c.GetType()); // output: System.Int32[]
Дополнительные сведения см. в руководстве по работе с массивами.
Создание экземпляров анонимных типов
Чтобы создать экземпляр анонимного типа, используйте оператор new и синтаксис инициализации объекта:
var example = new < Greeting = "Hello", Name = "World" >; Console.WriteLine($", !"); // Output: // Hello, World!
Уничтожение экземпляров типа
Уничтожать ранее созданные экземпляры типа необязательно. Экземпляры как ссылочных типов, так и типов значений уничтожаются автоматически. Экземпляры типов значений уничтожаются, как только уничтожается содержащий их контекст. Экземпляры ссылочных типов уничтожаются сборщиком мусора в неуказанное время после удаления последней ссылки на них.
Для экземпляров типа, которые содержат неуправляемые ресурсы, например дескриптор файла, рекомендуется использовать детерминированную очистку, чтобы как можно скорее высвободить эти ресурсы. Дополнительные сведения см. в справке по API System.IDisposable и статье об операторе using.
Возможность перегрузки оператора
Определяемый пользователем тип не может перегружать new оператор .
Спецификация языка C#
Дополнительные сведения см. в разделе Оператор newспецификация языка C#.
Подробные сведения о выражении new с целевым типом см. в примечании к предлагаемой функции.
См. также
new operator — The new operator creates a new instance of a type
The new operator creates a new instance of a type. You can also use the new keyword as a member declaration modifier or a generic type constraint.
Constructor invocation
To create a new instance of a type, you typically invoke one of the constructors of that type using the new operator:
var dict = new Dictionary(); dict["first"] = 10; dict["second"] = 20; dict["third"] = 30; Console.WriteLine(string.Join("; ", dict.Select(entry => $": "))); // Output: // first: 10; second: 20; third: 30
You can use an object or collection initializer with the new operator to instantiate and initialize an object in one statement, as the following example shows:
var dict = new Dictionary < ["first"] = 10, ["second"] = 20, ["third"] = 30 >; Console.WriteLine(string.Join("; ", dict.Select(entry => $": "))); // Output: // first: 10; second: 20; third: 30
Target-typed new
Beginning with C# 9.0, constructor invocation expressions are target-typed. That is, if a target type of an expression is known, you can omit a type name, as the following example shows:
List xs = new(); List ys = new(capacity: 10_000); List zs = new() < Capacity = 20_000 >; Dictionary lookup = new() < [1] = new() < 1, 2, 3 >, [2] = new() < 5, 8, 3 >, [5] = new() < 1, 0, 4 >>;
As the preceding example shows, you always use parentheses in a target-typed new expression.
If a target type of a new expression is unknown (for example, when you use the var keyword), you must specify a type name.
Array creation
You also use the new operator to create an array instance, as the following example shows:
var numbers = new int[3]; numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; Console.WriteLine(string.Join(", ", numbers)); // Output: // 10, 20, 30
Use array initialization syntax to create an array instance and populate it with elements in one statement. The following example shows various ways how you can do that:
var a = new int[3] < 10, 20, 30 >; var b = new int[] < 10, 20, 30 >; var c = new[] < 10, 20, 30 >; Console.WriteLine(c.GetType()); // output: System.Int32[]
For more information about arrays, see Arrays.
Instantiation of anonymous types
To create an instance of an anonymous type, use the new operator and object initializer syntax:
var example = new < Greeting = "Hello", Name = "World" >; Console.WriteLine($", !"); // Output: // Hello, World!
Destruction of type instances
You don’t have to destroy earlier created type instances. Instances of both reference and value types are destroyed automatically. Instances of value types are destroyed as soon as the context that contains them is destroyed. Instances of reference types are destroyed by the garbage collector at some unspecified time after the last reference to them is removed.
For type instances that contain unmanaged resources, for example, a file handle, it’s recommended to employ deterministic clean-up to ensure that the resources they contain are released as soon as possible. For more information, see the System.IDisposable API reference and the using statement article.
Operator overloadability
A user-defined type can’t overload the new operator.
C# language specification
For more information, see The new operator section of the C# language specification.
For more information about a target-typed new expression, see the feature proposal note.