#226 – Classes and Objects
January 29, 2011 1 Comment
A class is a data structure containing data and associated behavior. You use the class keyword in C# to define a new class. You use your user-defined class in the same way that you use built-in classes in the .NET Framework.
You can create an instance of a class, also known as an object, using the new keyword. Each instance of a class has its own copy of the data defined by the class.
Here’s an example, a declaration of a new Person class.
public class Person { public string FirstName; public string LastName; public int Age; public string DescribeMe() { return string.Format("{0} {1} is {2} yrs old.", FirstName, LastName, Age); } }
Once the class is defined, we can create new instances of the class, read/write its data and call its methods.
Person p = new Person(); p.FirstName = "James"; p.LastName = "Joyce"; p.Age = 40; string desc = p.DescribeMe();