In C#, you can give an auto-property an initial value by using the constructor of the class that contains the property. Auto-properties are properties where the getter and setter are automatically generated by the compiler, and they don't have an explicit field to store the value. Here's an example of how to give an auto-property an initial value:
csharp
public class MyClass
{
// Auto-property with an initial value
public int MyProperty { get; set; }
// Constructor to set the initial value
public MyClass()
{
MyProperty = 42; // Set the initial value to 42
}
}
class Program
{
static void Main()
{
MyClass obj = new MyClass();
Console.WriteLine(obj.MyProperty); // Output: 42
}
}
In this example, we have a class MyClass
with an auto-property MyProperty
. We provide an initial value of 42
for MyProperty
within the constructor of the class. When you create an instance of MyClass
, the MyProperty
will be initialized with the value 42
.
Alternatively, if you are using C# 6.0 or later, you can use an expression-bodied constructor to set the initial value:
csharp
public class MyClass
{
// Auto-property with an initial value using a constructor expression body
public int MyProperty { get; set; } = 42;
}
In this case, you set the initial value directly in the auto-property declaration itself. The result is the same as the previous example, where MyProperty
is initialized to 42
when you create an instance of MyClass
.
Comments
Post a Comment