Some of the topics-concepts, I will try to cover are:
- Classes
- Properties
- Methods
- Fields
- Members
- Enums
- Casting
- Structures
- Abstraction
- Encapsulation
- Interfaces
- Static classes
- Constructors
- Method overloading
- Inheritance
- Overriding methods
- Virtual methods
- Abstract classes
- Polymorphism
- Delegates
- Events
- Assemblies
- Namespaces
and many more…
Before jumping into bits of code and create our step by step example, I must explain some basic concepts regarding OOP.
- What is a class?
A class is an abstract concept. It is a blueprint. Try to think of a class as e.g the blueprints of a car in the real world.
The designers of auto mobiles sit in front of their computer (or use paper and pencil) and describe exactly the parts of the auto mobile. They describe how these parts interact, the colour of the car, the height of the car, the size of the engine, the acceleration of the car, if the car has air-conditioning system installed.
Then the mechanics that observe the production line, make sure that the cars built (the actual cars) follow the blueprints outlined in the design stage of building a car.
So a class is a way of describing real world entities. It is the code definition for objects.
The class is the fundamental building block of code when creating object-oriented software. A class describes in abstract (in theory) all of the characteristics and behaviour of an object.
The object on the other hand is the instance of a class. The real thing, if you excuse my slang…
So we must start thinking about modelling our applications in terms of objects.
When someone, who has hired us to implement a web site-commerce site for his business, he could outline his view of the web site in plain words…
” I would like to have a site where I can keep track of the sales-orders that were placed through the site. I also would like to be able to see the customer details and manage my employees details”,
Then you must think in terms of Orders,Customer,Employee classes-objects for this particular scenario.
This is a first attempt of Abstraction for the scenario above.
Abstraction is the process of representing simplified versions of real-world objects in your classes and objects.
Programming with the OOP paradigm is to decide what a class should represent and breaking down your code into a group of interrelated classes.
Members of a class
The first thing after finalising the class names is to identify the members of a class.
I will talk about Properties, methods and events. As we go on I will talk in greater detail about class members.
- What is a property ?
A Property allows you to access an object’s data. Properties can be read-only, so they cannot be modified, while others can be changed. A Property defines the state of an object.It describes its individual data or unique configuration.
- What is a method ?
A method allows you to perform an action with an object. Unlike properties, methods are used for actions that perform a distinct task and may change the object’s state-property.
- What is an event ?
An event provides notification that something has happened. Objects can fire events to trigger the code we have placed in the event-handling routines-methods. For example, if a user clicks on a button,the button object fires a Click event, which our code can react to.
Methods, properties and events can be considered as the public interface of a class.
Now we are ready to move on and practice what we have been saying so far.
I assume that people who will read this post, have some experience with C# and Visual studio as a development platform.
I will use Visual Studio 2008 Professional edition. People who have downloaded and installed Visual web developer 2008 can also follow these examples. You can download Visual Web Developer by clicking here .
I will create an ASP.NET application. I will create a base class and then take it from there and try to highlight all the concepts mentioned above. The point of this example is not create super sophisticated classes and methods but to create a simple class with plain properties and methods.
1) Launch VS 2008
2) Go to File->New->Project
3) From the templates, choose ASP.NET web application. Make sure you select C# as the language of development
4) Give a name for your project. I name it “LearnCLass”. Click OK on the Templates window.
5) You will have 2 main files, Default.aspx and Default.aspx.cs
Building a basic class
The class I will construct regards a Person class.This class can represent any person, e.g the customer of an e-commerce shop.The Personclass will store the person’s data, and it will include the built-in functionality needed to generate a block of HTML that displays the person details on a web page. We will test this class with an ASP.NET page.
Once you’ve defined a class, the first step is to add some basic data. The next example defines five member variables that store information about the person, namely, its name, surname, age, height,weight .
Once you’ve defined a class, the first step is to add some basic data. The next example defines five member variables that store information about the person, namely, its name, surname, age, height,weight .
In your default.aspx.cs (code behind file) you have something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;namespace LearnCLass
{
public partial class _Default : System.Web.UI.Page
{
Then add the class definition
public class Person
{
public string name;
public string surname;
public int age;
public decimal height;
public decimal weight;
}
Now we have the class definition we need to creating an object. We must use new keyword to do that. The new keyword instantiates the object, which means it creates a copy of the class in memory. If you define an object but don’t instantiate it, you’ll receive an error from the compiler.The members of a class (methods and properties) are accessed using dot ‘.’ operator against the reference of the object.
In the Page _Load event handling routine type
protected void Page_Load(object sender, EventArgs e)
{
Person mynewperson;
mynewperson=new Person();
mynewperson.name = “nikos”;
mynewperson.surname = “kantzelis”;
mynewperson.age = 31;
mynewperson.weight = 88;
mynewperson.height = 1.78M;
Response.Write(mynewperson.name);
}
Run your application by hitting F5 from the keyboard and see the results.
What I am trying to highlight here, is how to create an object from a class.The bit that does it is this:
Person mynewperson;
mynewperson=new Person();
One could write it in a single line
Person mynewperson=new Person();
But the snippet of code inside the Page_Load method is not very well thought.
One could write mynewperson.age = -2;
We would not like to have the code above. The reason the code above works is that the properties of the Person class,
are all public. That is the visibility of the properties is public. Another more technical word for visibility is scope.
This is very important concept and one must understand.
The main accessibility keywords are
public -Members defined as public can be accessed by any other class
private - Members defined as private can be accessed only by code procedures inside the current class
internal – Members defined as internal can be accessed by code procedures in any of the classes in the current assembly (the compiled file)
protected Members defined as protected can be accessed by code procedures in the current class or by any class
that inherits from this class
private - Members defined as private can be accessed only by code procedures inside the current class
internal – Members defined as internal can be accessed by code procedures in any of the classes in the current assembly (the compiled file)
protected Members defined as protected can be accessed by code procedures in the current class or by any class
that inherits from this class
So by having in our example the variables defined as public, this means that any other class or method of another class has direct access to those variables-properties.
We must not design classes like that. In order to have useful classes we must have a way to protect the data within them. This is called,Encapsulation. Encapsulation is is the hiding of the internal mechanisms and data of a class behind a defined interface.Other classes , if they need to “talk” – interact with a specific class, they can do so by just knowing its interface. Let me try to explain this better with my car analogy example. When you try to change the gear in your car, imagine the gear system as class or a component, the gear system interacts with another system that commands the car to slow down or accelerate. The gear system does not have to know how it is done, just how to interacts with it.
So let’s change public to private.
private string name;
private string surname;
private int age;
private decimal height;
private decimal weight;
Let’s run the code again. We get the following error. I am sure you get what is going on here. There is no variable name still “alive-visible” when we call it in the Page_Load event handling routine.
Error 1 ’LearnCLass._Default.Person.name’ is inaccessible due to its protection level C:\Users\fofo\Desktop\webapps\LearnCLass\LearnCLass\Default.aspx.cs 24 25 LearnCLass
In general objects are automatically released when the appropriate variable goes out of scope. Objects are also released when your application ends. That means that their memory is reclaimed. In the managed applications, the CLR uses a service (garbage collector) that periodically scans for released objects and reclaims the memory they hold.
So , you must be thinking that we have not accomplished anything yet. The truth is that we have not finished yet.
We must write property accessors for the member variables.
For the name member variable we have
public string Name
{
get
{
return name;
}set
{
name = value;
}}
With C# 3.0 we had a new feature that is called Auto-implemented properties. Have a look here in one of my past posts to find out more about that.Basically with auto implemented properties, there is no need to implement a private field to store the value.
So we could write the code above like this
public string Name { get; set; }
much easier isn’t it?
We can do that for all property accessors if no no additional logic is required.
So we have
public string Name { get; set; }
public string Surname { get; set; }
that means that we can comment out the following lines from our class declaration.
//private string name;
//private string surname;
//private string surname;
but for the Age,Height,Weight member variables we require some additional logic for the property accessors.
Just for this example let’s just assume that a person’s age must between 1 and 100, his height from 1 to 2.40 and his weight from 30 to 240.
public int Age
{
get
{
return age;
}set
{
if (value < 1 || value > 100)
{
throw new Exception(“Invalid age”);
}age = value;
}}public decimal Height
{
get
{
return height;
}set
{
if (value < 1.00M || value > 2.40M )
{
throw new Exception(“Invalid height”);
}height = value;
}}public decimal Weight
{
get
{
return weight;
}set
{
if (value < 30 || value > 240)
{
throw new Exception(“Invalid weight”);
}weight = value;
}}
When trying to assign an invalidvalue, an exception is thrown by the class code.
Now let’s create a method for our Person Class.
We can create a very simple method like:
public void Talk()
{
// add logic later
}
or we can add a method that returns something (it is not void) and can do something useful.
So we can have a method that calculates the age of the person in years. The method follows:
public int CalculateAge(DateTime birthDate)
{DateTime now = DateTime.Today;int years = now.Year – birthDate.Year;if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
–years;return years;
}
It is not something difficult. We should not focus on how the method does it, right now. Basically I am just using
DateTime Class in the System namespace.
In your Page_Load event you can add to the code already there, the following bit
string myDateTimeString;int res;myDateTimeString = “17 Feb,1977″;DateTime dt;
dt = Convert.ToDateTime(myDateTimeString);
res=mynewperson.CalculateAge(dt);Response.Write(res.ToString());
Run your application and see the results.
The Person class so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;namespace LearnCLass
{
public partial class _Default : System.Web.UI.Page
{public class Person
{
//private string name;
//private string surname;
private int age;
private decimal height;
private decimal weight;public int Age
{
get
{
return age;
}set
{
if (value < 1 || value > 100)
{
throw new Exception(“Invalid age”);
}age = value;
}}public decimal Height
{
get
{
return height;
}set
{
if (value < 1.00M || value > 2.40M )
{
throw new Exception(“Invalid height”);
}height = value;
}}public decimal Weight
{
get
{
return weight;
}set
{
if (value < 30 || value > 240)
{
throw new Exception(“Invalid weight”);
}weight = value;
}}public string Name { get; set; }
public string Surname { get; set; }public int CalculateAge(DateTime birthDate)
{DateTime now = DateTime.Today;int years = now.Year – birthDate.Year;if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
–years;return years;
}public void Talk()
{
//add logic later
}}protected void Page_Load(object sender, EventArgs e)
{
Person mynewperson=new Person();
mynewperson.Name = “nikos”;
mynewperson.Surname = “kantzelis”;
mynewperson.Age = 22;
mynewperson.Weight = 88;
mynewperson.Height = 1.78M;
Response.Write(mynewperson.Name);
Response.Write(“</br>”);
Response.Write(mynewperson.Surname);
Response.Write(“</br>”);
Response.Write(mynewperson.Age);
Response.Write(“</br>”);
Response.Write(mynewperson.Height);
Response.Write(“</br>”);
Response.Write(mynewperson.Weight);
Response.Write(“</br>”);
mynewperson.Talk();string myDateTimeString;int res;myDateTimeString = “17 Feb,1977″;DateTime dt;
dt = Convert.ToDateTime(myDateTimeString);
res=mynewperson.CalculateAge(dt);Response.Write(res.ToString());mynewperson.Talk();}
}
}
When we create our Person object,
Person mynewperson=new Person();
you might think that we have here is a method call.When an instance of a class is created the C# system makes a call to a constructormethod in that class. A constructor is a function with the same name as that of the class. Every single class must have a constructor method.It is called when we write the new keyword. Even If we do not provide a constructor method, the compiler creates a default one,without any parameters.
So in our case is:
public Person(){}
We often need to overload our default constructors. Let me explain what overload is.
It is possible to have more than one method with the same name and return type but with a different number and type of arguments-parameters. The compiler knows every time which method to call by looking at the number of the arguments. I will explain more about overloading later on.
Sometimes it is better to send some information to the class upfront so it is available as soon as it is constructed. So let’s overload the default constructor.
public Person( string thename, string thesurname, int theage)
{
Name = thename;
Surname=thesurname;
Age = theage;
}
We can also have a destructor.Destructors are just the opposite of constructors.
It has the same name as the containing class but prefixes it with the ~ (tilde) sign.
It is called automatically when the object is about to be destructed (when garbage collector is about to destroy your object).
It has no return type just as the constructor does not have one as well.
We declare the destructor in our case like
We declare the destructor in our case like
~Person()
{
// place our e.g resource freeing code here
}
What really happens is that the C# compiler internally converts the destructor to the Finalize() method.
The Object class is the parent of all objects in .Net.It contains a method called Finalize().
This method is be called when your object is garbage collected . One can override this method and put here code for freeing resources that you reserved when using the object.
This method is be called when your object is garbage collected . One can override this method and put here code for freeing resources that you reserved when using the object.
protected override void Finalize()
{
try
{// put some code here
}
finally
{
base.Finalize();
}
}
Do not worry about the override keyword. I will explain it later on.
Many people ask me about enums and structures and what they are and how we can use them.
What is enum?
An enumeration is a group of related constants. Each constant is given a descriptive name.
Every enumerated value corresponds to a preset integer.
Every enumerated value corresponds to a preset integer.
Sometimes we want to hold a range of particular values or states. This is a perfect place to use enums.
In our example we could have something like
public enum PersonState
{
Married = 1,
Widoewed = 2,
Single = 3,
Divorced = 4
}
And then call it from our Page_load event
PersonState personstate;personstate =PersonState.Married;
Response.Write(“</br>”);
Response.Write(personstate);
C# compiler will represent these states as particular numeric values . But it will do so behind the curtains.
So I can use the enum name values and have more readable code. The concept of enumerated values is extremely important, because the .NET class library uses it extensively.
What is a structure ?
Structures are lightweight objects. Structures are very similar to classes in C#.
Basically they can hold a collection of different things about a particular item.
They are denoted in C# by the struct keyword. In our example we could have a structure like this
struct NewPerson
{
public string name;
public string surname;
public int age;
public decimal height;
public decimal weight;}
In the Page_Load event routine we can have
NewPerson myperson;myperson.name = “John”;Response.Write(myperson.name);
As you notice there is no need for the new keyword.
There is a key difference between objects and structures. Structures are managed in terms of value while objects are managed in terms of reference.
A reference holds the physical address of where the data is stored in memory. So it points to the data. It is not the actual data. On the other hand structure variables hold the actual data.
There are some limitations with structures and even if they have their place when we design a software component, they can never be used to replace a class type.
A structure for example can neither inherit another class, nor can they be inherited. A structure can implement interfaces.
A common place where we find structures are Net framework types like System.Int32, System.Double , System.Boolean.If you want to check it out yourselves just place the pointer of your mouse on an int declaration and right click. From the right-menu click on the “Go To Definition “. Then you will see the definitions. See the picture below.
Inheritance
I know a lot people who use Inheritance in their applications without even realizing.
If you look at the Default.aspx.cs you can see
public partial class _Default : System.Web.UI.Page
In plain English , this means that every web page we create is a child of the Page class. Inheritance is a form of code reuse. It allows one class to acquire and extend the functionality of another class. There is no need to reinvent the wheel when other people have done this for you. Instead of that you have only to think about the peculiarities of the project at hand.
Let’s assume that we need to create another class,called Student.
In this class we want to inherit the functionality of the Person class or base class.
class Student : Person
Then we want to extend the Parent class. We want to create a new simple method to calculate the total marks achieved by the student.
The whole Student class follows. I have explained in detail properties and methods in previous paragraphs.
class Student : Person
{
private int _marksEnglish;
private int _marksLiterature;
private int _marksIT;
private int _marksMaths;
private int marksTotal;public int marksEnglish
{
get
{
return _marksEnglish;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}_marksEnglish = value;
}
}
public int marksLiterature
{
get
{
return _marksLiterature;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}
_marksLiterature = value;
}
}public int marksMaths
{
get
{
return _marksMaths;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}
_marksMaths = value;
}
}public int marksIT
{
get
{
return _marksIT;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}
_marksIT = value;
}
}public int CalculateTotalMarks()
{marksTotal = marksEnglish + marksLiterature + marksIT + marksMaths;return marksTotal;
}
}
In our Page_Load event , we can create a new object of type Student.
Student mystudent = new Student();
Response.Write(“</br>”);
mystudent.Name=”fofo”;
Response.Write(mystudent.Name);
mystudent.marksEnglish = 12;
mystudent.marksLiterature = 13;
mystudent.marksIT = 18;mystudent.marksMaths = 17;mystudent.CalculateTotalMarks();
Response.Write(mystudent.CalculateTotalMarks());
If you pay attention even though we did not define the Name and Surname properties for the Student class, they are available to the class, since they are inherited. The same applies for the CalculateAge method.
Some things worth mentioning regarding inheritance are:
- C# allows only single class inheritance
- Multiple inheritance of classes is not allowed in C#
- The Object class defined in the System namespace is implicitly the ultimate base class of all the classes in C# and the .NET framework
- A class may implement multiple interfaces. We may also declare objects of different classes in a class. This way, the encapsulated class may be instantiated in other classes.
Now, we know how to make a new class based on an existing one and extend it.If we want to change the behavior of a method in the base class in the child class we must override it.
Let’s create a new method in the base class (Person) that we want to override it later on the child class. It is just a method that calculates the pay of a person.
public double CalculatePay(double hoursWorked, double wageperhour,double tax)
{return (hoursWorked * wageperhour * tax);
}
This method is inherited in the Student class. Let’s assume that we live in a fantastic world where student’s money is not taxed if the student worked less than 100 hours.
The first thing to do is to add the word virtual to the CalculatePay method.So we have:
public virtual double CalculatePay(double hoursWorked, double wageperhour,double tax)
{return (hoursWorked * wageperhour * tax);
}
and then to use the word override in Student class CalculatePay method
public override double CalculatePay(double hoursWorked, double wageperhour,double tax)
{
if (hoursWorked > 100)
{return (hoursWorked * wageperhour * tax);
}
else
{
return (hoursWorked * wageperhour);}
}From our Page_Load event we can call thisResponse.Write(mystudent.CalculatePay(45, 4, 0.45));By calling the line above the CalculatePay method of the student class will be invoked.This relationship between virtual methods and the derived class methods that override them enables polymorphism.
If we want to stop overriding a class we can use the special word sealed. This means that this class cannot be used as the basis for another class.
if you change the
public class Person to public sealed class Person
and run your application you will receive an error
“cannot derive from sealed type ‘LearnCLass._Default.Person“
Now it is time to see in greater detail method overloading.
In our Person class we can define a new method
public string JoinNames(string name, string surname)
{
return name + ” ” + surname;
}
Now we could have a different implementation of the method above.
public string JoinNames(string prefix, string name, string surname)
{
return prefix + ” ” + name + ” ” + surname;
}
In our Page_ Load event if we write the line:
mynewperson.JoinNames(“Mr”,”nikos”, “kantzelis”)
The compiler will not complain. It will know which method to invoke depending on the number of the parameters-arguments it “sees”.
Polymorphism (from the Greek meaning “having multiple forms” – “Poly” means many and “morphy” means “shape”) can be achieved by overloading a method.
What is a static class?
In .NET we can use some class members without creating an object first. These are called static members, and they’re accessed by class name. So far in the previous examples we have seen the static property DateTime.Now to retrieve a DateTime object that represents the current date and time. We didn’ create a DateTime object first.
If we wanted to have a method that determines whether a person can hold a valid driving licence, the method would look like this.
public bool AllowedToDrive(int age)
{
if (age >= 18 || age <= 80)
{
return true;
}
else
{
return false;
}}
The method above is a good candidate to become a static method.In order to do that, we just add the word static
public static bool AllowedToDrive(int age)
{
if (age >= 18 || age <= 80)
{
return true;
}
else
{
return false;
}}
In our Page_Load event routine,we can write
Person.AllowedToDrive(22)
As you see we do not need an object to invoke our method, just the class name.
So a static member is a member of the class and not a member of an instance of the class.
It takes some experience to determine which methods or classes. One common place where we find static classes and methods is the creation of libraries that provide general functionality, e.g find the square root of a number, find the perimeter of a circle.
The next thing to review is Interfaces. I will not cover Interfaces in detail because you can find another post of mine on Interfaces on this blog.
The Interface is basically a contract between a the Interface and a class. In the Interface we do not have implementation of properties of methods.
The class that implements the Interface or inherits from the Interface must implement the methods defined in the Interface.
A .NET interface is similar to an abstract class in the sense that it’s a kind of a template. More on abstract classes later.
If we define an interface like this
interface IPerson
{
double DaysVacation(int yearsOfWork);
}
and if we say that the Person class implements the IPerson Interface
class Person : IPerson
the Person class must in its body implement the DaysVacation(int yearsOfWork) method.
public double DaysVacation(int yearsOfWork)
{if (yearsOfWork > 25)
{
return 25;
}
else if (yearsOfWork < 25 && yearsOfWork > 20)
{
return 20;
}
else
{
return 10;
}}
What is an abstact class?
If we need to provide common fields and members to all subclasses, we create an Abstract class. We can create an abstract class, with the use of the abstract keyword. Abstract classes cannot be instantiated. In our example if we decide that there are some things that an object of type Person must do, then we can make the class Person abstract and then get the clild classes to provide the implementation. I will create another class to demonstrate abstract classes, because we need to change los of code in the Person class and I do not want to do that.
In abstract classes we can have abstract members and virtual members. An abstract member is not implemented in the base class and must be implemented in derived classes in order for the class to compile. A virtual member must be implemented in the base class, and if need be (optionally) overriden in the derived class if want the child method to do something different.
Let’s define our abstract Vehicle class.
public abstract class Vehicle
{public string Model { get; set; }
public string Color { get; set; }
public int NumOfDoors { get; set; }
public int NumoOfWheels { get; set; }public Vehicle(string model, string color)
{
this.Color = color;
this.Model = model;}
public abstract string Accelarate(int speed);public virtual double CalculatePetrolCostPerDistance( double distance){
double costperkilometer=0.25;
double res;res = distance * costperkilometer;return res;
}}
Now we can have another class Car that can inherit from the Vehicle class. The method Accelerate in the Vehicle class must be implemented in the child class.
public class Car : Vehicle
{public Car(string model, string color): base(model,color)
{
//code to be added
}public override string Accelarate(int speed)
{
return “I can accelerate. My speed is right now:”+speed.ToString();
}public override double CalculatePetrolCostPerDistance(double distance)
{
double costperkilometer = 0.45;
double res;res = distance * costperkilometer;return res;
}}
We can create and use an object type Car in our Page_Load event handling routine
Car mycar = new Car( “bmw”, “silver”);
Response.Write(mycar.Accelarate(134));
Response.Write(“</br>”);
Response.Write(“The cost is: ” + mycar.CalculatePetrolCostPerDistance(125.5).ToString() +” euros”);
In the child class I have implemented a simple version of the Accelarate method by using the override keyword and I chose to ovverideCalculatePetrolCostPerDistance. But If i did not need any different behaviour for the CalculatePetrolCostPerDistance then that would be ok, my class would compile just fine.
Abstract classes are a lot like interfaces, however abstract classes are different in that they contain fully implemented methods alongside the abstract ones.So we do not have to implement the same methods in each of the components that implement a particular interface. An abstract class can contain fields, constructors, or destructors and implement properties while an interface cannot.
An abstract class cannot support multiple inheritance, but an interface can support multiple inheritance. Thus a class may inherit several interfaces but only one abstract class.
An abstract class cannot support multiple inheritance, but an interface can support multiple inheritance. Thus a class may inherit several interfaces but only one abstract class.
What is a delegate?
For more information on this topic have a look at this post of mine.
What is Generics ?
Same applies here. I have another single post on Generics and I do not see any point repeating myself.
What is a namespace?
In my solution in the Default.aspx.cs , I have the namespace LearnCLass namespace. All my classes and code is included in this namespace.
Namespaces are a logical way to group classes. Let me give you an example of what it means. It is a way that we can identify a class beyond doubt.
Imagine that you want to phone an old friend that you have lost track, so you can invite him to your wedding. So you phone the phone directory service.
Your friend’s name is George Patouxas. The operator lets you know that there are 100 people with this name coming up. Then you tell the operator that his mother’s name and father’s name are Maria and John respectively. BINGO!! The operator tells you there is only match. So in our example the LearnCLass.Person class resides in this specific namespace and if someone wants to use it, he can use the using LearnCLass.Person declaration.
That is exactly why namespaces are for in .NET. We try to group related classes in namespaces and all of them that reside in this particular namespace will be uniquely identified.
If I have a class called Calculate in my LearnClass namespace, then there will be no conflict if need be to use another component from a third party that has also a Calculate Class.
That Calculate class will reside in the AnotherNameSpace so there will be no conflict.
Please note that in the beginning of the Default.aspx.cs we import namespaces that we need to using System.Web.UI;
Assemblies
All .NET classes (built-in or custom made) are contained in assemblies. Assemblies are the physical files that contain compiled code. Assembly files have the extension .exe if they are stand-alone applications or .dll if they’re reusable components. Assemblies are a physical package for distributing code. Often, assemblies and namespaces have the same names. For example, you’ll find the namespaceSystem.Web in the assembly file System.Web.dll.
But in many cases there is no direct mapping between assemblies and namespaces.
What is Casting?
When we talk about casting, we can think of this concept in terms of narrowing and widening. If you move a value from one type to another that narrows the value, it will ask you to explicitly do it yourself. When you move a value from one type to another by widening it, it does not complain.
By widening I mean that if I have the declaration:
int mynum=5;
float anothernum=mynum;
This will be fine because the floating point type can hold all the values supported by the integer type.
If I have this statement (narrowing)
double mynum = 3.5;
float thenum = mynum;
the compiler will complain.
Cannot implicitly convert type ‘double’ to ‘float’. An explicit conversion exists (are you missing a cast?)
The compiler is basically saying “Is there any chance you are discarding information?”
But you can cast the value by using this statement.
double mynum = 3.5;
float thenum = (float)mynum;
This is an explicit conversion and I say in simple words to the compiler, that I take the responsibility for the possible data loss.
For reference types, if we have a situation like this, where the derived type (Student) is converted to base type (Person), we have imlicit conversion which is safe.
Student thestudent = new Student();
while if we type this:
Person theperson=new Person();
this will fail and we must explicitly cast it to the Student type, like this.
Person theperson=new Person();
Student thestudent = (Student)theperson;
Hope it helps. If you need the source code, leave a comment and I will email it to you.
------------------
Static Keyword.
1. A static method can access only static fields.
2. A static method cannot access non-static fields.
3. A static method cannot be called using object of a class.
4. A static method can be called using Class name.
5. Static fields can be used using Class Name.
A static method can access only static fields.
A static method cannot access non-static fields
Error Message
A static method cannot be called using an object of a class
Usually intellisense gives the list of method names available for a particular object. But here intellisense cannot show any user defined method.
A static method can be accessed using Class Name
Here Intellisense has the respective method name of the particular class.
Static fields can be accessed using Class Name
you can access Session in static method by using HttpContext
HttpContext.Current.Session["key"]
Access ViewState from Static method in aspx page
Note: similar to session
public static string GetData(int CustomerID) {
Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
string outputToReturn = "";
page.ViewState["MyVal"]="Hello";
return outputToReturn;
//btw, what a strange method!
}
}
e: Access control on a page from a static method.
try to pass your textboox control as a parameter to this method i.e;
//Call it like this ConfirmMatchedDataCount(TextBox1); [System.Web.Services.WebMethod] public static bool ConfirmMatchedDataCount(TextBox txtBegin) { txtBegin.Text = "Some Text"; //or do whatever you want to do with this }
Re: Access control on a page from a static method.
thats alrite, so if you have to access multiple controls, use code below:
[System.Web.Services.WebMethod] public static bool ConfirmMatchedDataCount() { Page page = HttpContext.Current.Handler as Page; UseControlsOnPage(page); } public static void UseControlsOnPage(Control parent) { string selectedRdoValue = string.Empty; string selectedDdlValue = string.Empty; string selectedChkValue = string.Empty; foreach (Control ctrl in parent.Controls) { if (ctrl is TextBox) ((TextBox)ctrl).Text = "Some Text"; else if (ctrl is RadioButtonList) selectedRdoValue = ((RadioButtonList)ctrl).SelectedValue; else if (ctrl is DropDownList) selectedDdlValue = ((DropDownList)ctrl).SelectedValue; else if (ctrl is HyperLink) ((HyperLink)ctrl).Enabled = false; else if (ctrl is CheckBoxList) selectedChkValue = ((CheckBoxList)ctrl).SelectedValue = status; else if (ctrl is FileUpload) UploadFile(((FileUpload)ctrl));//where UploadFile() may be function to upload some file //and so on; do similarly for other Controls UseControlsOnPage(ctrl); } }
A static class contains only static members.We can't create instance of that class using new key word.
The members of static class are accessed using the class without an instance of that class.
Eg:
public static class MyStaticClass
{
public static void Test()
{
//code here
}
}
The members of static class are accessed using the class without an instance of that class.
Eg:
public static class MyStaticClass
{
public static void Test()
{
//code here
}
}
a static class cannot be instantiated. In other words, we cannot use the new keyword to create a variable of the class type. Because there is no instance variable, we access the members of a static class by using the class name itself.
A Constructor is usually used to initialize data. However Static Constructor is used to initialize only static members. Here I am just talking about the Constructors. How they get initialized and how they behave.
Things to know about Static Constructor
Things to know about Static Constructor
- It is used to initialize static data members.
- Can't access anything but static members.
- Can't have parameters
- Can't have access modifiers like Public, Private or Protected.
Now once you understand the above points, you can appreciate the difference between Static Class and Unstatic Class
- Static Class cannot be instantiated unlike the unstatic class. You should directly access its Method via the ClassName.MethodName
- A Program can't tell when it is going to load static class but its definitely loaded before the call.
- A Static class will always have the static constructor and its called only once since after that its in the memory for its lifetime.
- A Static class can contain only static members. So all the members and functions have to be static.
- A Static class is always sealed since it cannot be inherited further. Further they cannot inherit form any other class (except Object)
Let's look at a normal Constructor
class Program{ static void Main(string[] args)
{
class Program{ static void Main(string[] args)
{
/* Note two things
1.Here you get to instantiate the Constructor in the code wherever you like.
2.If you debug you get to goto the Constructor and see what is being done.
*/ MyExample myExample = new MyExample();
myExample.Print();
}
}
public class MyExample{ private static int StaticVariable ; public MyExample()
{ if (StaticVariable < 10)
{
StaticVariable = 20;
} else {
StaticVariable = 100;
}
}
myExample.Print();
}
}
public class MyExample{ private static int StaticVariable ; public MyExample()
{ if (StaticVariable < 10)
{
StaticVariable = 20;
} else {
StaticVariable = 100;
}
}
public void Print()
{ Console.WriteLine(StaticVariable);
}
}
{ Console.WriteLine(StaticVariable);
}
}
Now consider this second example for static class
class Program{ static void Main(string[] args)
{
class Program{ static void Main(string[] args)
{
/* Note the following
1.You dont get to instantiate for sure so you dont know when the constructor was called.
2.Secondly you can access your method directly.
*/
//MyExampleStatic myExampleStatic = new MyExampleStatic(); MyExampleStatic.Print();
}
}
}
}
static class MyExampleStatic{ private static int StaticVariable; static MyExampleStatic()
{ if (StaticVariable < 10)
{
StaticVariable = 20;
} else {
StaticVariable = 100;
}
} public static void Print()
{ Console.WriteLine(StaticVariable);
}
}
{ if (StaticVariable < 10)
{
StaticVariable = 20;
} else {
StaticVariable = 100;
}
} public static void Print()
{ Console.WriteLine(StaticVariable);
}
}
The following are rules to create a static class:
Rule#1. a static class must contain the static keyword in the class declaration.
Rule#2. a method should be static i.e. the method declaration must contain the static keyword.
Rule#3. the Constructor must be static because a static class doesn't allow an instance constructor.
Rule#4. the Constructor must not contain an access modifier.
Rule#5. a Static class can't implement an inteface.
Rule#6. a Static class can't be a base class i.e. it cannot be derived from.
public static class clsStatic
{
static string varA = string.Empty;
static int varB = 0;
static clsStatic()
{
varA = "Give some value";
varB = 100;
}
public static void MethodA()
{
}
public static void MethodB()
{
}
}
Experiment #1:
Let's do an experiement; try to violater some rules i.e. Rule #1,2,3.
Remove the static keyword from the Constructor, member variable and also from methods.
public static class clsStatic
{
string varA = string.Empty;
int varB = 0;
public clsStatic()
{
varA = "Give some value";
varB = 100;
}
public void MethodA()
{
}
public void MethodB()
{
}
}
C# Comiler will give you the following error:
Error 1 Static classes cannot have instance constructors
Error 2 'MethodA': cannot declare instance members in a static class
Error 3 'MethodB': cannot declare instance members in a static class
Error 4 'prjStatic.clsStatic.varA': cannot declare instance members in a static class
Error 5 'prjStatic.clsStatic.varB': cannot declare instance members in a static class
Experiement #2:
Let's try another experiement; let's change the access modifier of the constructor; we are breaking Rule #4.
public static class clsStatic
{
static string varA = string.Empty;
static int varB = 0;
//Break the Rule # 4, declare constructor as public
public static clsStatic()
{
varA = "Give some value";
varB = 100;
}
public static void MethodA()
{
}
public static void MethodB()
{
}
}
C# Compiler will give you the following error.
Error 1 'prjStatic.clsStatic.clsStatic()': access modifiers are not allowed on static constructors
So, what is the reason behind that we can't put access modifier in static constructor?
CLR controls the static class and invoke the static constructor, so static constructor does not require any access modifier.
Experiment #3:
Let's try to implement an interface in a static class:
interface iStaticCls
{
void MethodC();
void MethodD();
}
public static class clsStatic : iStaticCls
{
public static void MethodA()
{
}
public static void MethodB()
{
}
}
Try to rebuild the code, you will get the following error:
Error 1 'prjStatic.iStaticCls': static classes cannot implement interfaces
10 Features of Static class
- A static class cannot be instantiated
- Static class can have only static members.
- Member of the Static class can be accessed by class name itself.
- Static class is sealed. So static class cannot be inherited.
- Static class contains only static constructors.
- Static class cannot have instance constructors.
- Static class can only be inherited only from object class.
- Static class is preceded by keyword static.
- Static constructor of static class called only once.
- Static class has private constructors.
How CLR deals with static class?
- Information of Static class is loaded by CLR, when the Program accessing or referencing Static class is being loaded.
- The program referencing static class has no control to specify when static class should be loaded by CLR.
- Static class remains in memory for the lifetime of application domain in which program resides.
How to create Static class?
- Create a class with keyword Static.
- Create a private constructor inside class.
- Make all members as static.
Notable Points here are:
1. A static method can be invoked directly from the class level
2. A static method not requires any class object
3. Any main() method is shared through entire class scope so it always appears with static keyword.
Abstract class real time example
Abstract class realtime example explanation
You can see the above image is for example for Abstract class in real time.Take three classes Human, Man and Woman.All Man and Woman belong to Humancategory.In Original object exists for only for Man or Woman.NO object exist forHuman category.But both Man and Woman have common characteristics where we can say it as Human characters.Now you can understand that why do we need abstract class.
Difference between Abstract class and interface
Now As you know that abstract class where we can not create object for abstract class.Same like abstract class, you can not create object for interface also.Then what is the difference between abstract class and interfaces in java.I can say that interface is for "PURE ABSTRACTION".Pure abstraction means you can not have concrete methods.But an abstract class can have concrete methods.Interfaces should not have any concrete methods, it should only have method declarations.
Which one is advantage over another:
Interface has advantage over Abstract class.Since you can not use abstract class for already inherited class.But you can use interface for already inherited class.
No comments:
Post a Comment