Showing posts with label access modifier. Show all posts
Showing posts with label access modifier. Show all posts

December 15, 2013

Defining Properties

Properties are unique features of C#. They look like data fields, but they have logic behind them. Over the surface, they look like any other member variable. But they act like a member function.

Properties are defined like a field (variable), with the addition of get and set code. Like any other fields or methods, they can use access modifiers.

Let us consider a particular problem. Consider the code below.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass my = new MyClass();
            my.SetVal(7);
            Console.WriteLine("The value that was set = {0}",my.GetVal());
            Console.Read(); //keeps the console alive
        }
    }

    class MyClass
    {
        private int myint;
        public void SetVal(int val)
        {
            myint = val;
        }
        public int GetVal()
        {
            return myint;
        }
    }
}
We have a class named MyClass. We have a private field and lets assume that its integer type. The methods on line 19 and 23 provides a way to set and get a value from the private field myint. This is neat and pretty basic. If you are familiar with Java, you will see that your IDE provides facilities to implement default code that are usually called getters and setters.

In C#, you can do the same with properties. Properties make your code more readable and manageable. Instead of the methods on line 19 and 23, add the following code inside MyClass.

public int MyIntVal
{
    get { return myint; }
    set { myint = value; }
}
This is what we call a property in C#. MyIntVal is a property. It looks somewhat a mixture of a variable and method declaration. The get code allows you to return the current value of this property. The set code helps you to save the incoming value to the desired variable. Notice the value variable inside the set code. This value is implicit and C# automatically provides the data inside this field. Here is the complete code.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass my = new MyClass();
            my.MyIntVal = 7;   //triggers the set logic
            Console.WriteLine("The value that was set = {0}",my.MyIntVal);  //triggers the get logic
            Console.Read(); //keeps the console alive
        }
    }

    class MyClass
    {
        private int myint;
        public int MyIntVal
        {
            get { return myint; }
            set { myint = value; }
        }
    }
}
Read the comments on the code, it will help you to get along. Copy and paste or simply write down all the code given. Now remove line 10 and try writing it down again. Once you type my[dot] you will notice a drop down suggestion that Visual Studio is offering.
Properties - MyIntVal
You will see that Visual Studio marks properties differently for you so that they are easily recognizable. In fact Visual Studio provides different visual information for different types of things.

Why use Properties? The obvious reason is the flexibility that it gives. Firstly properties can be calculated on the fly. Secondly properties promote the idea of Encapsulation. It means that you keep your data logic and private things private, encapsulated inside a class. Encapsulation is one of the core features of Object Oriented Programming. Thirdly, properties provide complete control over data field access. The logic is hidden from the consumer class. In our case, the consumer class is the Program class.

Let's play with them a bit more. You can make properties automatic. It means that the property itself will serve the purpose of another private field. For example, look at the following code snippet.

class MyClass
{
    public int MyIntVal
    {
        get;
        set;
    }
}
I have modified MyClass. Go ahead and use it like you see above. It works right? You can also make a property read only or write only. Just remove the get logic, it makes your property write only. Again, just remove set logic, it makes your property read only.

Finally I would like to show you a real life problem and solution using properties.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            MyProduct soap1 = new MyProduct("Irish Spring", 50);
            soap1.Price = 95;
            Console.WriteLine("Price of {0} is {1} BDT", soap1.Name, soap1.Price);

            MyProduct cake1 = new MyProduct("Chocolate Cheese Cake", 10);
            cake1.Price = 710;
            Console.WriteLine("Price of {0} is {1} BDT", cake1.Name, cake1.Price);
            Console.Read(); //keeps the console alive
        }
    }

    class MyProduct
    {
        public string Name
        {
            get;
            set;
        }
        private decimal profit = 0.07m;   // 7% profit on each product
        private decimal wholesale;
        private int units;
        public decimal Price
        {
            get { return wholesale + (wholesale * profit); }
            set { wholesale = value; }
        }
        public MyProduct(string prod, int units)
        {
            Name = prod;
            this.units = units;
        }
    }
}
Observe the following points:
  1. Look at line 9 and 14 inside Main. We create two objects. We already know that once we declare an object, the constructor is called. The constructor at line 35 is called each time. The prod argument is assigned to Name property. This triggers the set logic on line 25. 
  2. Consider line 10 and 14. In each case, the objects individual Price property is used to set a value. So the set logic on line 33 is executed. 
  3. Finally consider line 11 and 15. C# compiler understands that you want to access the values set inside those properties. So the get logic is executed, respectively at line 24 and 32 for Name and Price properties. You already understand that among both the properties, Name is an automatic property. You may also notice that the get logic on Price is working on the fly.
I hope this post makes your C# experience easier and happier. Happy Coding!

December 11, 2013

Classes and Objects

We already know that C# is an Object Oriented Programming language. We have seen that every variable that we declare in our program are objects. A C# program at the heart is an object; you probably have noticed that your code is inside a class named Program. Inside that class, you declare some other variables or objects or methods and you do your stuff.

So what we understand from this is that C# is inherently an object oriented programming language. We shall discuss about classes and objects in this post. We shall also go through some important aspects that are related to classes and objects.

Classes group together some data and logic with those data. If you have some data and logic which are closely related, the idea is to keep them together and bundle up. While you bundle things up, you will want to control how you want to modify these data. So classes actually provide you a neat and cleaner experience of doing these things.
Interaction between classes
Classes can interact with each other. By all means you will want to modify/update your data from other end. This is how you make your program dynamic.

A class is actually a blueprint or model of what an object looks like, what this object is capable of. It tells you what kinds of data this object is interested in, what kinds of task this object can perform. Suppose someone makes the design of how a laptop looks like, the blueprint of a laptop is a class. When you make an actual product from that blueprint, its an object from that design. A red covered laptop is an object, so is a silver covered laptop. Your blueprint lets you know what each of them has in basics.

.NET framework provides you a whole bunch of useful classes. You can use them for many different purposes. You can declare your own class. Classes essentially have two major types of members.
  1. Fields and Properties
  2. Methods (or functions)
The fields and properties are what the class (read object) holds and works with. Methods provide a way of doing stuffs with these fields and properties. You can manipulate or use the fields and properties via these methods.

Let us consider a system where we hold on some data of a student in a school. If we keep it simple, lets say we deal only with his/her name, the standard he/she reads in and his/her roll number. You might have noticed that we have already prepared our fields.
  1. Name
  2. Standard he reads in
  3. Roll number
This is a simple model of our class.

class StudentInfo
{
    string name;
    int standard;
    int rollnum;
}
How do we manipulate these data? How do we put data in the first place? Lets take a look into the following code.
using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            StudentInfo student1 = new StudentInfo("Mahmud", 8, 21);
            Console.Read(); //keeps the console alive
        }
    }
    class StudentInfo
    {
        string name;
        int standard;
        int rollnum;
        public StudentInfo(string name, int stndrd, int roll)
        {
            this.name = name;
            standard = stndrd;
            rollnum = roll;
        }
    }
} 

Line 9 creates an object of the class StudentInfo. If you are familiar with other object oriented languages, you are familiar with this line. This is the way we create an object. And you can see, while creating the object, we are passing three values that we would like to define in our object of type StudentInfo. In a nutshell, the object student1 belongs to a student whose name is Mahmud.
This class functionally does nothing. It can't communicate with others. So how do we make it to speak? Lets try out this.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            StudentInfo student1 = new StudentInfo("Mahmud", 8, 21);
            StudentInfo student2 = new StudentInfo("Nabiha", 2, 5);
            Console.WriteLine("{0}'s roll number is {1}",student1.getName(),student1.getRollNum());
            Console.WriteLine("{0}'s roll number is {1}", student2.getName(), student2.getRollNum());
            
            Console.Read(); //keeps the console alive
        }
    }
    class StudentInfo
    {
        string name;
        int standard;
        int rollnum;
        public StudentInfo(string name, int stndrd, int roll)
        {
            this.name = name;
            standard = stndrd;
            rollnum = roll;
        }
        public int getRollNum()
        {
            return rollnum;
        }
        public string getName()
        {
            return name;
        }
    }
}
You will notice that we create yet another object, but notice that when we ask for the same piece of information from both of the objects, they give us their own individual information.For example, consider line 11 and 12, the output that we are showing, we don't know who actually is student1 or student2 object. So we provided some functions inside the StudentInfo class. Notice that we call the same function from two different objects, so we are getting two different values. Congratulations! You have seen the power of using objects. So you see, you don't have to define different functions for individual records, all you do is code once and use it again and again, perhaps using different objects.

You can create as many objects as you like, as many useful methods as you need. Notice that, while writing the code, when you type the object name and hit a period(dot .) the Visual Studio editor will provide you some options. Aha! You don't see the fields name, do you? What do you understand from this? In C#, the default access modifier is private. What are access modifiers? In C# there are different modes which you can specify how your fields or methods are visible to the outside world. In our case, the string variable name, integer variable  standard and rollnum are private to the class. It means that you can only access them when you are inside the class. For example, from line 25 to 35, you accessed them, returned their values to outside world. You can manipulate here. You cannot manipulate these variables from outside.

Hit the dot [.] again after the object name, now notice that you are able to see the methods getName() and getRollNum(). You can access them because their access modifier is public! Had they been private, they would have been inaccessible from where we accessed earlier.

Constructor: Finally, the one and only constructor. The name of the constructor should be that of the class name. It should be declared public. A constructor should not return anything. A constructor can take any number of arguments. If you do not provide a constructor, your compiler automatically puts (I mean not visible to you!) a default constructor that takes no argument and does nothing. 

Finally let's look into another method in the slightly modified code.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            StudentInfo student1 = new StudentInfo("Mahmud", 8, 21);
            StudentInfo student2 = new StudentInfo("Nabiha", 2, 5);
            
            Console.WriteLine("{0}'s roll number is {1}",student1.GetName(),student1.GetRollNum());
            Console.WriteLine("{0}'s roll number is {1}", student2.GetName(), student2.GetRollNum());
            Console.WriteLine("{0} students are available", StudentInfo.GetCount());
            
            Console.Read(); //keeps the console alive
        }
    }
    class StudentInfo
    {
        string name;
        int standard;
        int rollnum;
        static int count = 0;
        public StudentInfo(string name, int stndrd, int roll)
        {
            this.name = name;
            standard = stndrd;
            rollnum = roll;
            count++;
        }
        public int GetRollNum()
        {
            return rollnum;
        }
        public string GetName()
        {
            return name;
        }
        public static int GetCount()
        {
            return count;
        }
    }
}
Static fields and methods: Suppose you want to get a count of how many students are available in your StudentInfo class. This count should be kept in a variable which should not get changed (re-initialized) when new objects are created. Fortunately the static variables are really good in this purpose. Notice the static integer variable on line 24. It is initialized with default value 0. Each time a new object is created, the constructor is called and a count++ occurs, which increments the value. 
Now notice the method GetCount(). Its access modifier is public static. What does that mean? public allows you to call this method from outside. A static method is something special. Go ahead and try to access it using one of the objects (student1 or student2). This method is inaccessible, right? A static method is accessible from the class definition, it means that in order to access a static method, you don't need to create an object, you can access it using the name of the class itself.

I hope these things make sense to you after reading this post. Happy coding!