Is there a syntax in C# that allows me to define a private property, like in Typescript?
Example: Typescript:
constructor (private field1: string) { }
In C# I have to do this:
private readonly string field1;
public MyClass(string field1)
{
this.field1 = field1;
}
I'm looking for a syntax sugar for AspNet core dependency injection.
Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property.
private: The type or member can be accessed only by code in the same class or struct . protected: The type or member can be accessed only by code in the same class , or in a class that is derived from that class .
Private setters allow you to create read-only public or protected properties. That's it.
The private keyword in object-oriented languages is an access modifier that can be used to make properties and methods only accessible inside the declared class. This makes it easy to hide underlying logic that should be hidden from curious eyes and should not be interacted with outside from the class.
There is no syntactic sugar for this in C# 7, you'll have to write the boilerplate.
Sounds like primary constructors are sort of what you're looking for - they were in C# 6 beta but ultimately dropped.
http://www.alteridem.net/2014/09/08/c-6-0-primary-constructors/
Class myClass
{
private string field1 {get; set;}
public Class()
{
}
}
Thats it, you now have a property if you initialize this class. If you want it readonly, only write a get method.
If you want a dependency injection syntactic sugar in the constructor as in Angular, unfortunately there aren't any ... yet .
To declare a private
field in a class:
Class myClass
{
private string field1;
public Class()
{
}
}
if you want to be able to initilialize this field with a constructor call, you can give a parameter to the constructor so it can initialize it.
Class myClass
{
private string field1;
public Class(string field1)
{
this.field1 = field1;
}
}
you can also define it as a property instead of a simple field (properties have getter and / or setters, and are internally backed by a hidden variable in C# with the below syntax) :
Class myClass
{
private string Field1 { get; set; }
public Class(string field1)
{
this.Field1 = field1;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With