#241 – Declaring and Using Private Instance Methods

You can include a method in a class that is private.  It will be callable from other methods within the class, but not callable from outside the class.

In the example below, the PrintName method is visible from outside the class, but the PrintAge method can only be called from within the class.

    public class Dog
    {
        public string Name;
        public int Age;

        public void PrintName()
        {
            Console.Write(Name);
            PrintAge();
        }

        private void PrintAge()
        {
            Console.WriteLine(string.Format(" ({0})", Age));
        }
    }

Code that attempts to call the PrintAge method from outside the class will not compile.

            Dog kirby = new Dog();
            kirby.Name = "Kirby";
            kirby.Age = 14;

            kirby.PrintName();
            kirby.PrintAge();    // compiler error
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: