Answers for "c# properties"


c# properties

//Properties are like methods except that they are actually Methods for accessing them. They have definable accessors that you can create like get, set, add, and remove;
//There are 2 types of properties: automatic and Manual Peroperties. They can be further marked as static for sharing accross classes
//they exist to limit, control, and check outside access to variables

//A basic Variable with out (Standard notating for variables for manual properies is _ at the start of the name and makeing them private)
private int _num = 0;
//A auto property does the work of makeing a varable for storage for you. Optionaly you can also set them after makeing them in in the class, but they require a get and set (or add and remove for others) accessor in a pair.
public int AutoNum { get; private set; } = 0;
//A manual property allows you to access varable and do checks on the accessing. Optionaly you can also set them after makeing them in in the class, but they require a get or set (or add or remove for others) accessors and use of an outside varable for storage.
//Note you must refernence an outside variable with use to avoid a recursive method call effect from causing a stack overflow.
public int ManualNum
            //Optional checks can be done here but is less normal than set checks
                return _num;
            private set // if you want an accessor to be less accessable than the property you can mark it as such in the accessor, but you must go from the properties level to less accessable.
            //Optional checks can be done here such as  
            //if (value > 0)
            //        throw new IndexOutOfRangeException("Num is too small");
                _num = value;
        } = 0;
//If there are short hands for very simple sets.
public int ManualNum2 { get => _num; private set => _num = value; } = 0;
//these are for accessors like Left=  and =Right.

//There are more advanced properties that use other key words such as add or remove for adding evens to sub properties.
public event DataReceiveEventHandler DataReceiveEvent { add => ClassProperty.DataReceiveEvent += value; remove => ClassProperty.DataReceiveEvent += value; }
//this is for accessors like += and -=

//Properties also have advanced uses in interfaces (such as 'INotifyPropertyChanged') and recursion
Posted by: Guest on March-30-2020

c# accessors

private string _name = "Hello";

public string Name
        return _name;
    protected set
        _name = value;
Posted by: Guest on October-05-2020

C# Answers by Framework

Browse Popular Code Answers by Language