Thursday, September 16, 2010

Console Classes

by Emmaneale Mendu
In this post i will show you how to work on two classes.

Lets start adding two classes as shown below and imagine User entered AccountNumber and we need to show him UserName and Account Balance.

class AccountNumber
    {
        static void Main()
        {
            UserName();

            Console.ReadKey();
        }
    }

    class Details
    {
        public static void UserName()
        {            
            Console.WriteLine("Emmaneale Mendu");
        }
    }


Compilation Error
'UserName' does not exist in the current context.


So, oops! error. while working in the same class, we can the method directly but while working with different classes like above one. Here we have a new class Details. we are trying to call a method which is in the Details class from AccountNumber class, so we  need do have use Details class name to acces it as shown in the below program.

class AccountNumber
    {
        static void Main()
        {
            Details.UserName();

            Console.ReadKey();
        }
    }

    class Details
    {
        public static void UserName()
        {            
            Console.WriteLine("Emmaneale Mendu");
        }
    }

OutPut
Emmaneale Mendu

Thank GOD, no errors this time.

my intension is getting Account Balance also, Lets do it with using some secure manner. follow the code below.

class AccountNumber
    {
        static void Main()
        {
            Details.UserName();

            Details.Balance();

            Console.ReadKey();
        }
    }

    class Details
    {
        public static void UserName()
        {            
            Console.WriteLine("Emmaneale Mendu");
        }

        //Default this method is private
        static void Balance()
        {
            Console.WriteLine("1,000,000,000");
        }
    }

Compilation Error
Details.Balance() is inaccessible due to its protection level.

By reading the error we can know that Balance method is secured in that class itself. By this we can know whats going on with private and public keywords.

class AccountNumber
    {
        static void Main()
        {
            Details.UserName();

            Details f;

            //Details.Balance();
            Console.ReadKey();
        }
    }

    class Details
    {
        public static void UserName()
        {            
            Console.WriteLine("Emmaneale Mendu");

            //you can call method from inside a class
            Balance();
        }

        //Default this method is private
        static void Balance()
        {
            Console.WriteLine("1,000,000,000");
        }
    }

OutPut
Emmaneale Mendu
1,000,000,000

So, hence we are calling Balance method from inside the class using same flow.

No comments:

Post a Comment