c# attributes properties code example
Example 1: c# attribute
//Attributes can be added to properties or classes depending on the attribute.
//They can also be used to keep a sort of static variable hidden to the object on classes, properties, fields, enums, Assemblys, methods, and other objects at verying scopes that can be revied later for different uses
//For example they can mark classes for behaviour or for checks
[Serializable] //<-A class marking attribute marking the your class to do the work of getting ready your class for serlization so you dont have to.
public class SomeAPIClass
{
//The attribute is always placed above the thing you wish to mark and can , seperated in the [ brackets or stacked in many [ brackets.
[APIAlwaysRequired(nameof(UserName))]//Property marking attributes
public string SomeValue { get; set; }
}
//To make a custom attribute class you can look into extending the attribute calls and marking it with attribute for the given object you want to mark
//Here is an example of a attribute to mark properies for a type of check
[System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Field, Inherited = true)]
public class APIAlwaysRequiredAttribute : System.Attribute
{
public string ErrorMessage { get; set; } = "Your request is missing or with out a param.";
public APIAlwaysRequiredAttribute(){}
public APIAlwaysRequiredAttribute(string ParamName)
{
this.ErrorMessage = $"Your request is missing or with out the {ParamName} param."; ;
}
}
//You then will need to make use of your attribute in some way. Probably through reflection.
//Here is an example of the above attribute in use with a templatable generic check that saves you from writing too many vers your self. Let reflection and attributes take on all the work.
private static List<string> CheckObjectForErrors<T>(T obj, bool SkipPostErrors)
{
List<string> Errors = new List<string>();
Type ObjType = typeof(T);
PropertyInfo[] Properties = ObjType.GetProperties();
foreach (PropertyInfo P in Properties)
{
if (Attribute.IsDefined(P, typeof(APIAlwaysRequiredAttribute)))
{
if (P.GetValue(obj) == null)
{
APIAlwaysRequiredAttribute ErrorAttribute = (APIAlwaysRequiredAttribute)Attribute.GetCustomAttribute(P, typeof(APIAlwaysRequiredAttribute));
Errors.Add(ErrorAttribute.ErrorMessage);
}
}
}
if (Errors.Count() != 0)
return Errors;
return null;
}
//There are an an insane amount of ways you can use this like a Regex check that takes the Regex String in a var could be added
Example 2: 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
{
get
{
//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