-2

What is the difference between these two properties:

public int Foo = 6;
public int Bar {get;} = 6

Here is a link to a working program that shows the output is the same: https://replit.com/@TomDane/GloriousDramaticScope#main.cs

using System;

class Program {
    static void Main(string[] args) {
      
      var someClass = new SomeClass();
      
      Console.WriteLine(someClass.PropertyWithEquals);
      Console.WriteLine(someClass.PropertyWithGetter);
      
    }
}

public class SomeClass {
    public int PropertyWithEquals = 6;
    public int PropertyWithGetter {get;} = 6;
}

The output of this is 6 and 6. If the output is the same, are there any other reasons to prefer one over the other?

TomDane
  • 1,010
  • 10
  • 25

1 Answers1

1

In real life, the result might be the same, but the first one Foo can be set, so it's equal to public int Foo {get; set;} while Bar cannot be set outside the class and it's already initialized

Juan Medina
  • 565
  • 7
  • 15