Today I messed around with something called “automatic field” in C#, and I wanna share what I did and how it went. It’s pretty basic stuff, but hey, we all start somewhere, right?
Getting Started
So, I was looking at this code example online and decided to try it out myself. I fired up Visual Studio and created a new console application. You know, the usual – File > New > Project, choose Console App, give it a name, and hit Create.
The Experiment
First, I made a simple class, I’m calling it “MyClass” for now. Just a basic class, nothing fancy:
public class MyClass
Then I added a private string member, and I want that C# can automatic create get and set properties, just like this:
public class MyClass
private string myValue;
Then I want use myValue, I need add get and set method, like this:
public class MyClass
private string myValue;
public string MyValue
get { return myValue; }
set { myValue = value; }
I have set myValue as private,so I can not use myValue directly.
The Result
It worked! I mean, of course, it did, it’s pretty simple. I can set the value and get it back no problem. I added a little bit of code in the Main method to test it out:
static void Main(string[] args)
MyClass instance = new MyClass();
* = "Hello, Automatic Field!";
This is how you use an automatic field, I think this is the best C# * makes the code super clean and easy to read. And it’s less typing, which is always a win in my book.