Q:

What is the best way to give a C# auto-property an initial value?

0

What is the best way to give a C# auto-property an initial value?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In C# 5 and earlier, to give auto-implemented properties an initial value, you have to do it in a constructor. Let see an example,

using System;
class Person
{
    public Person()
    {
        //do anything before variable assignment
        //assign initial values
        Name = "Aticleworld.com";
        //do anything after variable assignment
    }
    public string Name { get; set; }
}
class Program
{
    static void Main()
    {
        var Person = new Person();
        Console.WriteLine(Person.Name);
    }
}

Output:

Aticleworld.com

 

Since C# 6.0, you can specify the initial value in-line. See the below code,

using System;
class Person
{
    public string Name { get; set; } = "Aticleworld.com";
}
class Program
{
    static void Main()
    {
        var Person = new Person();
        Console.WriteLine(Person.Name);
    }
}

Output:

Aticleworld.com

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Interview Questions and Answers,You Need To Know

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
List down the reason behind the usage of C# langua... >>
<< Explain Inheritance in C# with an example?...