Is there a default constructor in .NET as there is in C#?

188 Views Asked by At

I'm learning about constructors and am still a bit of a newbie in programming so apologies in advance if I'm using any terminology incorrectly. I believe that what I've read is there's a handy default constructor in C# that allows you to declare properties in object initialization like this…

Cat cat = new Cat { Age = 10, Name = "Fluffy" };

However I'm using UnityScript in the Unity3D engine and this language is, although often referred to as Javascript, more similar to JScript.NET. Is there a default constructor like the C# one available when initializing an object?

Currently what I have to do is initialize the object then set each property one at a time. Alternatively I can create a constructor I can use but I'm just curious if there's already a default one there like in C#?

2

There are 2 best solutions below

1
On BEST ANSWER

What you are asking about is not called the default constructor. It's called an object initializer.

It would not be a feature of .NET or Mono, because those are not languages; initializers are language features. I have tried to use them in UnityScript, but they either aren't implemented (I'm betting on that), or their syntax is just undocumented.

For your own classes/structs, I don't think they're frequently useful, but they are useful for working with classes/structs for which you don't control the source:

var v = new Vector3 { y = .5F }; // x and z are still zero, the default for floats

If you were able to write Vector3, you could give it a constructor like this:

public Vector3(x = 0, y = 0, z = 0) : this()
{
    this.x = x;
    this.y = y;
    this.z = z;
}

and used named parameter syntax, as such:

var v = new Vector3(y: .5F);

Given initializer syntax, there would be no point to bother with doing that, for a simple mutable struct like Vector3, but when you start working with readonly fields and privately set properties, you'll find constructors to be more valuable.

3
On

Unless Cat is a struct, it may not have a default constructor: it all depends on the class. If all constructors of a class take parameters (i.e. there is no default constructor) the construct

new MyClass { ... }

would be illegal.

Note that you can use the same initialization construct even for classes that lack default constructors: all you need is to call the non-default one, like this:

class Cat {
    public string Name {get;set;}
    public string Age {get;set;}
    public Cat(string name) {Name = name;}
}

Cat myCat = new Cat("Fluffy") {Age = 10 };