Skip to content

Instantly share code, notes, and snippets.

@dnasca
Created March 17, 2015 06:39
Show Gist options
  • Select an option

  • Save dnasca/ee549d1be97368427d47 to your computer and use it in GitHub Desktop.

Select an option

Save dnasca/ee549d1be97368427d47 to your computer and use it in GitHub Desktop.
Getting and setting properties by hand
using System;
public class Student
{
private int _id;
private string _name;
private const int PassValue = 70; //read only field
public int Id
{
get { return this._id; }
set
{
if (value <= 0)
{
throw new Exception("Id cannot be a negative value");
}
this._id = value;
}
}
public string Name
{
get { return string.IsNullOrEmpty(this._name) ? "Name field is empty" : this._name; } //ternary operator (3 arguments)
set
{
if (string.IsNullOrEmpty(value)) //if the string passed to this method is null or empty, throw exception
{
throw new Exception("Name cannot be null or empty.");
}
this._name = value;
}
}
public int GetPassValue //read only because no set method
{
get { return PassValue; }
}
}
public class Program
{
public static void Main()
{
Student S1 = new Student();
S1.Id = 14412;
S1.Name = "Derrik Nasca";
Console.WriteLine("ID: {0}", S1.Id);
Console.WriteLine("NAME: {0}", S1.Name);
Console.WriteLine("PASSVALUE: {0}", S1.GetPassValue);
Console.ReadKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment