Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are class initializers possible in C#?

In C# you have object initializers to initialize fields of objects at creation time without using a constructor.

Now I'm wondering if there is an equivalent to classes which means that you can 'initialize' properties of classes when defining subclasses without actually using an override syntax but simply declaring what the value of a known property is.

Example:

public abstract class Car {
    public abstract string Name { get; }
}
// usual approach
public class Mustang : Car {
    public overwrite string Name { get { return "Ford Mustang"; } }
}
// my idea of avoiding boilerplate code
public class Mustang : Car { Name = "Ford Mustang" }

Is there a way to accomplish this? If there is none, could T4 templates be of any help?

like image 248
Bastian Avatar asked Nov 17 '25 12:11

Bastian


1 Answers

To make rekire's example clearer, you'd write something like:

public abstract class Car
{
    public string Name { get; private set; }

    protected Car(string name)
    {
        this.Name = name;
    }
}

public class Mustang : Car
{
    public Mustang() : base("Mustang")
    {
    }
}

EDIT: Another option is to use attributes, where you'd write:

[CarName("Mustang")]
public class Mustang : Car

... having written appropriate reflection code in Car. I would strongly recommend that you don't though. Of course, attributes may be useful in your real context.

like image 193
Jon Skeet Avatar answered Nov 20 '25 02:11

Jon Skeet