C# Fields and Properties

C# Code Snippets Fields and Properties
Share:

About

In this code snippet, we will learn how to implement fields and properties in C#.

Fields are just normal variables but declared directly inside of a class. Even though you can make fields public, you shouldn’t(use a property instead). Only use fields locally inside the class.

Properties provide us with a way to read from and write to our private fields. In other programming languages, you usually have to implement getter and setter methods for this. Using properties you have way more control over your fields. For example, you can add some code for input validation. This way you can ensure that a value will fit in a certain range of values before assigning it.

Let’s see how to use and implement fields and properties.

Code:

using System;

namespace FieldsAndProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass MC = new MyClass();

            MC.MyProperty = 10;

            MC.MyThirdProperty = 15;
            MC.MyThirdProperty = 15;

            Console.WriteLine(MC.MyProperty);
            Console.WriteLine(MC.MyThirdProperty);

            Console.ReadLine();
        }
    }

    class MyClass
    {
        //This is a field. It's a variable that is declared inside of a class.
        //Even though you can make fields public, you shouldn't(use a property instead). Only use fields locally inside the class.
        /*public*/private int MyField;

        //This is a property. 
        public int MyProperty { get; set; }


        //Visual studio shortcut for implementing a property:
        //1. write: prop
        //or write: propfull     
        //2. pres TAB twice

        //Short way of implementing a property.
        public int MyPropertySecond { get; set; }

        //Long way of implementing a property.
        //You can for example add some code for validation.
        //This way you can ensure that a value will fit in a certain range of values before assigning it.
        private int myVar;

        public int MyThirdProperty
        {
            get { return myVar; }
            set
            {
                if (value > 0)
                {
                    myVar = value;
                }
            }
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger