Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the "new" Keyword necessary in C# [closed]

Tags:

c#

keyword

Suppose I have a function foo that takes a vector class as input:

void Foo( Vector3 vector );

If I want to call this function:

Foo( new Vector3(1, 2, 3) );

Why is the new keyword necessary (in C#) at all?

In other languages eg: C++ there is no need to use new in this case. It just seems redundant

edit 1: @ spender the following is perfectly valid C++

Foo ( Vector3(1, 2, 3) );

A Vector3 object will be created on the stack, no new/calloc/malloc required.

like image 577
aCuria Avatar asked Sep 18 '25 05:09

aCuria


1 Answers

The keyword was deemed appropriate by the language designers. It's common in C# that the language forces you to be aware of what is occurring, and either provides errors or warnings in many scenarios where it could have implicitly added features or "filled in" data for you.

C# always requires you to initialize your variables prior to usage. In this case, forcing the new keyword makes it obvious (to the developer) that a new instance (if Vector3 is a class) or a fully constructed type (if Vector3 is a value type) will be passed in to your method, as opposed to the result of a method call.

C++ there is no need to use new

Note that in C++ new is not optional here, at least without changing your function definition. Using new would mean Foo() would require a different syntax.

A call without new (Foo(Vector3(1,2,3));) suggests that Foo is defined as void Foo(Vector3 vector). If you were to use new Vector3, then Foo would be defined void Foo(Vector3* vector), as new will return a pointer to the type.

This is because C++ allows multiple forms of object allocation - you can stack allocate (without new) or allocate on the heap (using new). C# does not have this difference - all reference types are always allocated in long term storage, and value types are allocated in a location depending on their context and usage. The developer does not have the same level of control in C# as in C++ in terms of object usage and allocation.

At the end of the day, every language (with a concept of objects) has their own syntax and rules for object initialization and usage. Each language is unique, which is partly why there are so many different languages. In general, most languages are designed around a set of governing philosophies and apporaches, and the requirement to use new fits with C#'s approach of being very explicit when there is a chance for ambiguity (ie: is this a type constructor or a method?).

like image 103
Reed Copsey Avatar answered Sep 20 '25 21:09

Reed Copsey