Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define private properties in C# like Typescript

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;
}

update 1:

I'm looking for a syntax sugar for AspNet core dependency injection.

like image 617
Beetlejuice Avatar asked Oct 13 '17 11:10

Beetlejuice


People also ask

Can properties be private?

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.

What is private in C#?

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 .

What is private set?

Private setters allow you to create read-only public or protected properties. That's it.

What are private properties in Javascript?

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.


3 Answers

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/

like image 111
j4nw Avatar answered Oct 08 '22 02:10

j4nw


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.

like image 25
kurdy Avatar answered Oct 08 '22 01:10

kurdy


EDIT (after question edit)

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;
  }
}
like image 1
Pac0 Avatar answered Oct 08 '22 02:10

Pac0