#226 – Classes and Objects

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();
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #226 – Classes and Objects

  1. Pingback: #519 – Differences Between structs and classes « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: