VivekMishra

Archive for the ‘Student’ Category

/*Light boxcss Start */

.black_overlay{
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
/*width: 1004px;*/
/*height: 665px;*/
width: auto;
min-width: 1024px;
_width: 1024px;
height: auto;
min-height: 665px;
_height: 665px;
background-color: black;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
display: none;
z-index:9999;
}

.white_content {
position: absolute;
top: 20%;
left: 35%;
width: 320px;
height: 350px;
padding: 5px;
border: 5px solid #D3D3D6;
background-color: white;
z-index:99999;
overflow: auto;
display: none;
}

/* End */

/Show Light Box  Script */

<a href = “javascript:void(0)” onclick = “document.getElementById(‘light’).style.display=’block’;document.getElementById(‘fade’).style.display=’block'” class=”normal_link”>edit</a>
<div id=”light” class=”white_content” >

// Write your content here ///

<div align=”right”><a href = “javascript:void(0)” onclick = “document.getElementById(‘light’).style.display=’none’;document.getElementById(‘fade’).style.display=’none'”><img src=”images/closelabel.gif” border=”0″ /></a></div>
</div>

<div id=”fade” class=”black_overlay”></div>

Advertisements

The Mysql SELECT command is something like a print or write command of other languages..

Displaying the MySQL version number

select version();
 
+-----------+
| version() |
+-----------+
| 5.00.00   |
+-----------+
1 row in set (0.00 sec)
 

Displaying the current date and time

select now();
 
+---------------------+
| now()               |
+---------------------+
| 2008-05-31 00:36:24 |
+---------------------+
1 row in set (0.00 sec)
 

Displaying the current Day, Month and Year

SELECT DAYOFMONTH(CURRENT_DATE);
+--------------------------+
| DAYOFMONTH(CURRENT_DATE) |
+--------------------------+
|                       5 |
+--------------------------+
1 row in set (0.01 sec)
 
SELECT MONTH(CURRENT_DATE);
+---------------------+
| MONTH(CURRENT_DATE) |
+---------------------+
|                   2 |
+---------------------+
1 row in set (0.00 sec)
 
SELECT YEAR(CURRENT_DATE);
+--------------------+
| YEAR(CURRENT_DATE) |
+--------------------+
|               2008 |
+--------------------+
1 row in set (0.00 sec)
 

Displaying text strings

select 'I am MySQL';
 
+--------------+
| I am MySQL |
+--------------+
| I am MySQL |
+--------------+
1 row in set (0.00 sec)
 
These all function are use when you use client side validation in your page .these are very  simple 
 
and use it with your javascript code
 
// function for checking string
function checkString(str_temp, str_fld)
{
      temp=new String(str_temp);
      if(str_temp=="")
      {
           window.alert("Please enter the " + str_fld);
           return false;
      }
 
      if(temp.charAt(0)==" ")
      {
           window.alert("The " + str_fld + " cannot start with a space");
           return false;
      }
 
      str=new String("'\"");
 
      var flag=1;
 
      for (c=0; c<temp.length; c++)
      {
           if(str.indexOf(temp.charAt(c))>=0)
           {
                 flag=0;
                 break;
           }
      }
 
      if (flag==0)
      {
           window.alert("The " + str_fld + " cannot contain single/double quotes");
           return false;
      }
      return true;
}
 
function IsNumeric(sText)
{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;
 
}
 
function IsZip(sText)
{
   var ValidChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;
 
}
 
// function for checking number
function checkNumber(str_temp, str_fld)
{
      temp=new String(str_temp);
      msg="";
      if(str_temp=="")
      {
           //window.alert("Please enter the " + str_fld);
           msg="Please enter the "+ str_fld;
           return msg;
      }
 
      if(temp.charAt(0)==" ")
      {
           //window.alert("The " + str_fld + " cannot start with a space");
           msg="Please enter the "+ str_fld + " cannot start with a space";
           return msg;
      }
 
      if (isNaN(str_temp))
      {
           //window.alert("The " + str_fld + " can contain only numbers");
           msg="Please enter the "+ str_fld + " can contain only numbers";
           return msg;
      }
      return msg;
}
 
// returns the filename(Thumbnail/Blowup name)
function funName(str_temp)
{
      temp=new String(str_temp);
 
      li=temp.lastIndexOf("\\");
      if(li!=-1)
      {
           li++;
           temp=temp.substr(li);
      }
      if(temp.indexOf(".")==-1)
      {
           return("");
      }
      return(temp);
}
//
function Trim(trimstr)
{
      if(trimstr.length < 1)
      {
           return"";
      }
      trimstr = RTrim(trimstr);
      trimstr = LTrim(trimstr);
      if(trimstr=="")
      {
           return "";
      }
      else
      {
           return trimstr;
      }
} //End Function
 
function RTrim(VALUE)
{
      var w_space = String.fromCharCode(32);
      var v_length = VALUE.length;
      var strTemp = "";
      if(v_length < 0)
      {
           return"";
      }
      var iTemp = v_length -1;
 
      while(iTemp > -1)
      {
           if(VALUE.charAt(iTemp) == w_space)
           {
           }
           else
           {
                 strTemp = VALUE.substring(0,iTemp +1);
                 break;
           }
           iTemp = iTemp-1;
      } //End While
      return strTemp;
} //End Function
 
function LTrim(VALUE)
{
      var w_space = String.fromCharCode(32);
      if(v_length < 1)
      {
           return"";
      }
      var v_length = VALUE.length;
      var strTemp = "";
 
      var iTemp = 0;
      while(iTemp < v_length)
      {
           if(VALUE.charAt(iTemp) == w_space)
           {
           }
           else
           {
                 strTemp = VALUE.substring(iTemp,v_length);
                 break;
           }
           iTemp = iTemp + 1;
      } //End While
      return strTemp;
} //End Function
function checkspecialcharacter(str)
{
      var iChars = "!@#$%^&*()+=[]\\\';,./{}|\":<>? ";
      for (var i = 0; i < str.length; i++)
      {
           if (iChars.indexOf(str.charAt(i)) != -1)
           {
                 return false;
           }
      }
}
function checkspecialcharfirstname(str)
{
      var iChars = "!@#$%^&*()+=[]\\;,./{}|\":<>?";
      for (var i = 0; i < str.length; i++)
      {
           if (iChars.indexOf(str.charAt(i)) != -1)
           {
                 return false;
           }
      }
}
function checkspecialcharacterforname(str)
{
      var iChars = "!@#$%^&*()+=[]\\;/{}|\":<>?";
      for (var i = 0; i < str.length; i++)
      {
           if (iChars.indexOf(str.charAt(i)) != -1)
           {
                 return false;
           }
      }
}
function checknumericcharacterforname(str)
{
      var iChars = "0123456789";
      for (var i = 0; i < str.length; i++)
      {
           if (iChars.indexOf(str.charAt(i)) != -1)
           {
                 return false;
           }
      }
}
function checkspecialcharacterforaddress(str)
{
      var iChars = "!@#$%^&*()+=[]\\\;./{}|\":<>?";
      for (var i = 0; i < str.length; i++)
      {
           if (iChars.indexOf(str.charAt(i)) != -1)
           {
                 return false;
           }
      }
}
function checkspecialcharacterfortitle(str)
{
      var iChars = "!@#$%^&*()+=[]\\\;./{}|\"<>?";
      for (var i = 0; i < str.length; i++)
      {
           if (iChars.indexOf(str.charAt(i)) != -1)
           {
                 return false;
           }
      }
}
 
function checkspecialcharacterfordesc(str)
{
      var iChars = "";
      for (var i = 0; i < str.length; i++)
      {
           if (iChars.indexOf(str.charAt(i)) != -1)
           {
                 return false;
           }
      }
}
function checkspecialcharacterforimage(str)
{
      var iChars = "!@#$%^&*()+=[]\';,/{}|\"<>?";
      for (var i = 0; i < str.length; i++)
      {
           if (iChars.indexOf(str.charAt(i)) != -1)
           {
                 return false;
           }
      }
}
function checkspecialcharacterforUsername(str)
{
      var iChars = "!@^()+=[]\';,/{}|\"<>?";
      for (var i = 0; i < str.length; i++)
      {
           if (iChars.indexOf(str.charAt(i)) != -1)
           {
                 return false;
           }
      }
}
 
function isEmailAddr(email)
{
      var result = false
      var theStr = new String(email)
      var index = theStr.indexOf("@");
 
      if (index > 0)
      {
      var pindex = theStr.indexOf(".",index);
      if ((pindex > index+1) && (theStr.length > pindex+1))
           result = true;
      }
  return result;
}
 
function CheckEmail(Email)
{
      //var match = (/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/i);
 
      var match = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9_-]+\.)+[a-zA-Z0-9.-]{2,5}$/;
      if(match.test(Email)){return true}
      else
      {
           return false
      }
 
}
function emailfield(email)
{
      var msg="";
      if(!CheckEmail(email))
      {
           msg="Please enter a complete email address in the form: yourname@yourdomain.com!";
      }
      else if(Trim(email)=="")
      {
           msg="Email can not be blank!";
      }
      return msg;
}
function namefield(name)
{
      var msg="";
      if(checkspecialcharacterforname(name)==false)
      {
           msg="Name can not contain special character!"; //document.getElementById("divname").innerHTML
      }
      else if(Trim(name)=="")
      {
           msg="Name can not be blank!";
      }
      else if(checknumericcharacterforname(name)==false)
      {
           msg="Name can not contain numeric character!";
      }
      return msg;
}
function fnamefield(name)
{
      var msg="";
      if(checkspecialcharacterforname(name)==false)
      {
           msg="First name can not contain special character!"; //document.getElementById("divname").innerHTML
      }
      else if(Trim(name)=="")
      {
           msg="First name can not be blank!";
      }
      else if(checknumericcharacterforname(name)==false)
      {
           msg="First name can not contain numeric character!";
      }
      return msg;
}
function lnamefield(name)
{
      var msg="";
      if(checkspecialcharacterforname(name)==false)
      {
           msg="Last name  can not contain special character!"; //document.getElementById("divname").innerHTML
      }
      else if(Trim(name)=="")
      {
           msg="Last name can not be blank!";
      }
      else if(checknumericcharacterforname(name)==false)
      {
           msg="Last name can not contain numeric character!";
      }
      return msg;
}
function usernamefield(name)
{
      var msg="";
      if(checkspecialcharacterforUsername(name)==false)
      {
           msg="Username can not contain special character!";
      }
      else if(Trim(name)=="")
      {
           msg="Username can not be blank!";
      }
      else if(name.length < 5 )
      {
           msg="Please enter username in 5 character!";
      }
      return msg;
}
function passwordfield(password, confirmpassword)
{
      var msg="";
      if(checkspecialcharacterforUsername(password)==false)
      {
           msg="Password can not contain special character!";
      }
      else if(Trim(password)=="")
      {
           msg="Password can not be blank!";
      }
      else if(password.length < 5 )
      {
           msg="Please enter password in 5 character!";
      }
      else if(password!=confirmpassword)
      {
           msg="Your confirm password is not matched!";
      }
 
      return msg;
}
 
function titledfield(name,str)
{
      var msg="";
      if(checkspecialcharacterfortitle(name)==false)
      {
           msg=str + " can not contain special character!";
      }
      else if(Trim(name)=="")
      {
           msg=str + " can not be blank!";
      }
 
      return msg;
}
function titledfield2(name,str)
{
      var msg="";
      if(checkspecialcharacterfortitle(name)==false)
      {
           msg=str + " can not contain special character!";
      }
      else if(Trim(name)=="1234567654")
      {
           msg=str + " can not be blank!";
      }
 
      return msg;
}
 
function addressfield(name)
{
      var msg="";
      if(checkspecialcharacterforaddress(name)==false)
      {
           msg="Address can not contain special character!";
      }
      else if(Trim(name)=="")
      {
           msg="Address can not be blank!";
      }
      return msg;
}
function validateFileExtension(fvalue)
 {
      var msg="";
      if(fvalue!="")
      {
           if(!/(\.jpg|\.jpeg\.JPG|\.JPEG)$/i.test(fvalue))
            {
 
                 msg="Please select a JPG file";
 
           }
      }
      return msg;
}
function logofilefield(name)
{
      var msg="";
      if(name!="")
      {
           if (name.toUpperCase().indexOf(".JPG") < 0 && name.toUpperCase().indexOf(".JPEG") < 0)
           {
                 msg="Please select a JPG file";
           }
      }
      return msg;
}
function phonefield(phone, str)
{
      var msg="";
      var temp=phone;
      var stripped = temp.replace(/[\(\)\.\-\ ]/g, '');
      if (phone== "") {
        msg=str + " can not be blank!";
    }
      else if (!IsNumeric(stripped)) {
        msg=str + " can contain only hyphen and digits!";
    }
      else if(Trim(phone)=="")
      {
            msg=str + " can not be blank!";
      }
      else if((phone.length < 11 ) || (phone.length > 11 ))
      {
           msg="Please enter " + str + " Number in 11 digits!";
      }
 
      return msg;
}
 
function blankfieldnotcompulsory(name,str)
{
      var msg="";
      if (name!= "")
      {
           if(checkspecialcharacterfortitle(name)==false)
           {
                 msg=str + " can not contain special character!";
           }
           else if(Trim(name)=="")
           {
                 msg=str + " can not be blank!";
           }
      }
 
      return msg;
}
 
function phonefieldnotcompulsory(phone, str)
{
      var msg="";
      var temp=phone;
      var stripped = temp.replace(/[\(\)\.\-\ ]/g, '');
      if (phone!= "")
      {
      //  msg=str + " can not be blank!";
           if (!IsNumeric(stripped)) {
                 msg=str + " can contain only hyphen and digits!";
           }
           else if(Trim(phone)=="")
           {
                  msg=str + " can not be blank!";
           }
       }
      return msg;
}
 
function zipfield(zip, str)
{
      var msg="";
      var temp=zip;
      var stripped = temp.replace(/[\(\)\.\-\ ]/g, '');
      if (zip== "") {
        msg=str + " can not be blank!";
    }
      else if (!IsZip(stripped)) {
        msg=str + " can not contain special charaters !";
    }
      else if(Trim(zip)=="")
      {
            msg=str + " can not be blank!";
      }
      /*else if(zip.length>6)
      {
            msg=str + " no can contain only 6 digits!";
      }*/
 
      return msg;
}
 
function isWebSite(website)
{
      var result = false
      var theStr = new String(website)
      var index = theStr.indexOf(".");
 
      if (index > 0)
      {
      pin=theStr.length;
           if (pin > index+4){ result = true; }
      }
 
  return result;
}
 
function websitefield(website)
{
      var msg="";
      if (website== "") {
        msg="Website can not be blank!";
    }
      return msg;
}
 
function websitefieldnotcompulsary(website)
{
      var msg="";
      if (website!= "")
      {
        if (!isWebSite(website))
           {
                 msg="Invalid Website address ! ";
           }
    }
      return msg;
}
function tocheckblankfield(str, field)
{
      var msg="";
      if (str=="") {
        msg=field + " can not be blank!";
    }
      return msg;
}
function tocheckblankselection(str, field)
{
      var msg="";
      if (str=="") {
        msg=field + " can not be blank!";
    }
      return msg;
}
function tocheckblankselectionv(str, field)
{
      var msg="";
      if (str=="v") {
        msg=field + " can not be Please Select Option!";
    }
      return msg;
}
 
function descriptionfield(website)
{
      var msg="";
      if (website== "") {
        msg="Description can not be blank!";
    }
      return msg;
}
function tocheckfiletype(filetype,file)
{
      var msg="";
      var temp=filetype.toUpperCase();
      var temp1=file.toUpperCase();
      if ((temp1.indexOf(temp)) < 0 )
      {
           msg="Please select " + filetype + " file";
      }
      return msg;
}
 
function validateFiledocExtension(fvalue)
 {
      var msg="";
 
           if(!/(\.DOC|\.doc\.Doc)$/i.test(fvalue))
            {
 
                 msg="Please select a Doc extension file";
 
           }
 
      return msg;
}
 
/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "-";
var minYear=1900;
var maxYear=2100;
 
function isInteger(s){
      var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
 
function stripCharsInBag(s, bag){
      var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}
 
function daysInFebruary (year){
      // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
      for (var i = 1; i <= n; i++) {
           this[i] = 31
           if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
           if (i==2) {this[i] = 29}
   }
   return this
}
 
function isDate(dtStr){
      dtStr=Trim(dtStr);
      var daysInMonth = DaysArray(12)
      var pos1=dtStr.indexOf(dtCh)
      var pos2=dtStr.indexOf(dtCh,pos1+1)
      var strYear=dtStr.substring(0,pos1)
      var strMonth=dtStr.substring(pos1+1,pos2)
      var strDay=dtStr.substring(pos2+1)
      strYr=strYear
      if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
      if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
      for (var i = 1; i <= 3; i++) {
           if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
      }
      month=parseInt(strMonth);
      day=parseInt(strDay);
      year=parseInt(strYr);
      var msg="";
      if (pos1==-1 || pos2==-1){
           msg="The date format should be : mm/dd/yyyy";
      }
      if (strMonth.length<1 || month<1 || month>12){
           msg="Please enter a valid month";
      }
      if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
           msg="Please enter a valid day";
      }
      if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
           msg="Please enter a valid 4 digit year between "+ minYear +" and "+ maxYear;
      }
      if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
           msg="Please enter a valid date";
      }
      return msg
}
 
function expfield(workexpx, workexpy)
{
var msg="";
//alert(workexpx);
//alert(workexpy);
if(parseInt(workexpx) > parseInt(workexpy))
{
msg="Please correct the minimum and maximum experiance value!";
}
 
return msg;
}
 
function validateFiledocExtensionnotcompulsory(fvalue)
{
var msg="";
if(fvalue!="")
{
if(!/(\.DOC|\.doc\.Doc)$/i.test(fvalue))
{
 
msg="Please select a word file(.doc extension)";
 
}
}
return msg;
}
function validateDOB(d,m,y){
var error = false;
//alert(d + '--' + m + '--' + y);
if (d == "" && m == "" && y == "") error = 'Date of birth can not be blank';
else if(d == "") error = 'Date can not be blank';
else if(m == "") error = 'Month can not be blank';
else if(y == "") error = 'Year can not be blank';
 
// Check for valid date
 
if(d > 28 && y != "")
{
if(m == 02)
{
febdays = daysInFebruary(y);
//if (parseInt(febdays) < 29)
if (d > parseInt(febdays) )
{
error = "invalid Date Of Birth";
}
 
}
else
{
if(d > 30)
{
if (m==4 || m==6 || m==9 || m==11)
{
error = "invalid Date Of Birth";
 
}
 
}
}
}
 
return error;
}

Make this script according to your need in code this is server side script which use in ASP.Net server side validation

Email validation

<asp:RegularExpressionValidator runat=”server” ID=”rev_email” ControlToValidate=”txt_email” ErrorMessage=”your entry is not a valid email address” ValidationExpression=”.*@.*\..*”>

</asp:RegularExpressionValidator>

<asp:RequiredFieldValidator runat=”server” ID=”rfv_email” ControlToValidate=”txt_email” ErrorMessage=”please enter your email address”></asp:RequiredFieldValidator>

<asp:TextBox ID=”txt_email” runat=”server”></asp:TextBox>

<asp:RegularExpressionValidator ID=”regExEmail” runat=”server” ControlToValidate=”txtEmail” Display=”Dynamic” ErrorMessage=”Please enter a valid Email Address” ValidationExpression=”\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*”>

</asp:RegularExpressionValidator>

Blank validation

<asp:RequiredFieldValidator id=”rfv_region_name” runat=”server” ErrorMessage=”Must be select region name” ControlToValidate=”ddl_region”>

</asp:RequiredFieldValidator>

Website validation

<asp:RegularExpressionValidator ID=”reg_website” ControlToValidate=”txt_website” ValidationExpression=”http://(%5B\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?” runat=”server” ErrorMessage=”Invalid URL”>

</asp:RegularExpressionValidator>

File Uloading validation

<asp:RegularExpressionValidator id=”RegularExpressionValidator1″ runat=”server”
ErrorMessage=”Only zip file is allowed!” ValidationExpression =”^.+(.zip|.ZIP)$”
ControlToValidate=”FileUpload1″>

</asp:RegularExpressionValidator>

Phone Number

<asp:RegularExpressionValidator ID=”regExTelephone” runat=”server” ControlToValidate=”txtTelNumber” Display=”Dynamic” ErrorMessage=”Please enter a valid Telephone Number” ValidationExpression=”^(\()?(011|012)(\)|-)?([0-9]{3})?([0-9]{4}|[0-9]{4})$”>

</asp:RegularExpressionValidator>

Numeric value :

<asp:RegularExpressionValidator ID=”regExTelephone” runat=”server” ControlToValidate=”txtTelNumber” Display=”Dynamic” ErrorMessage=”Please enter a valid Telephone Number” ValidationExpression=”^[0-9]$”> </asp:RegularExpressionValidator>

Radio field validation

<asp:RequiredFieldValidator ID=”RequiredFieldValidator2″ runat=”server” ControlToValidate=”Gender” Display=”Dynamic” EnableViewState=”False” ErrorMessage=”Please select one of the ‘Gender’ options”> </asp:RequiredFieldValidator>

<asp:RadioButtonList runat=”server” ID=”Gender” Font-Size=”91%”>

<asp:ListItem Value=”Female” Text=”Female”></asp:ListItem>

<asp:ListItem Value=”Male” Text=”Male”></asp:ListItem>

</asp:RadioButtonList>

If You wand client side validation use java script function .

The include() Function


PHP gives you the ability to “hide” code. This is particularly helpful when creating large web environments with numerous pages that require a lot of maintenance. Think of hiding in terms of an HTML template — with an HTML template, you can guarantee uniformity across large numbers of pages as well as save coding time and effort by eliminating redundancy. By hiding code with PHP, you can feed the equivalent of a template to any given page simply by using the include() function.

For instance, if you have a standard heading for all pages on a site you can create a document named header.inc like the following:

<?php
 
   echo '<html>';
   echo '<title>Bob's</title>';
   echo '<body>';
   echo 'Bob's Towing Yard <img src="bobs_logo.jpg">';
 
?>

header.inc sets the title of the page to “Bob’s” and begins the body content of the page with “Bob’s Towing Yard” and Bob’s logo (bobs_logo.jpg). You then include this code by calling the function include() in the appropriate section of your PHP page. We’ll call the page index.php:

<?php
 
   include(header.inc);
 
?>

After you call the include() function you can add any unique content you desire. Viola, you have header uniformity across any page that includes header.inc. Of course, it isn’t a stretch to see that this can also be applied to uniform sections such as the footer of a web page, navigation menus, side panels, etc.

This immediately makes each page a 6-10 line project instead of a 20-40 line project. Once you have the included elements all dialed in, the only part of a web page you have to update is the content that is unique to the situation. In addition, if you need to change something miniscule, like Bob’s logo, or even the name Bob, the only place you have to make the change is in header.inc. All of the pages using header.inc will be automatically updated.

Note: It bears mentioning that the extension .inc is primarily used to differentiate include files from .php files. When looking at a directory of files it can be a bit daunting to pick out which files are merely include files and which are valid PHP pages. There is a difference in how browsers read these files however, and that difference should be kept in mind when creating a webpage. .inc files are treated as plain text and are therefore sent through the browser as plain text. If you view source on a page using .inc files, you will see the contents of these files. If the information contained in the .inc file is sensitive (i.e. passwords, personal information) it is best to use the .php extension so that the information is not readily available. You can also save .inc files outside of the directory, but I have always preferred to keep information that I want to be invisible under the .php extension. Files using the .php extension are treated exactly the same when called by the include() function:

include(header.inc)

and

include('header.php')

will give you the same results.

If you are using an Apache server, you can also manipulate the server configuration so that a user may not access .inc files.

Classes in Session


Now we know that we can feed whatever redundant elements we like into any number of pages by simply invoking a single function, let’s take it a step further and introduce classes.

Classes start using the Object-Oriented Programming (OOP) methodology in PHP (OOP is only available in PHP versions 4.0 and later). Briefly, OOP uses objects, which are unique and identifiable collections of stored data and operations that operate on that data. These objects are not unlike real-life objects, such as a chair, or a table. An object can also be a navigation menu, a button, a text field or a style sheet. Objects can further be grouped into classes. Classes are collections of objects that share certain criteria but may vary from object to object. For example, using horses as a class, certain criteria are necessary for an object to be classified as a horse: four legs, hooves, mane. However, many aspects of these criteria can have different values: black mane, brown mane, white mane, and so on.

This is the basic structure of a class:

class classname
{
}

To create a class in PHP, we begin with the keyword class, and the classname will follow. Next we will create attributes and operations for our class and place them between the brackets. Attributes are declared as follows:

class classname
{
   var $attribute1;
   var $attribute2;
}

Operations are created by declaring functions within the class definition:

class classname
{
   function operation1()
   function operation2($param1, $param2)
}

The function operation1 takes no parameters, while operation2 takes two parameters (param1, param2).

Most classes will have a special operation called a constructor. A constructor is called as soon as an object is created and serves the purpose of setting reasonable values for attributes or creating other objects needed by the parent object. A constructor is called in the same way a class is called, but it shares the name of the class. A constructor can be called manually, but its main purpose is to be called automatically when an object is created. This is the structure of a class that uses a constructor:


class classname
{
   function classname($param)
   {
      echo "The Constructor will be called with the
            parameter $param";
   }
}

Now that we have declared a class, we need to create an object that belongs to that class. This is also called instantiation, creating an instance of the class. So we’ll declare a class, give it a constructor, and then create two objects. The object is created using the keyword new:

class classname
{
   function classname($param)
   {
      echo "The Constructor will be called with the
      parameter $param";
   }
}
 
$x = new classname('Ego');
$y = new classname('Sum');

Our constructor is called by both objects, so the output will look like this:

The Constructor will be called with the parameter Ego
The Constructor will be called with the parameter Sum

 

 


Attributes and Operations


Earlier, when we discussed the nature of objects we compared them to horses. In order to qualify as a “horse” an object must meet certain criteria such as four legs, hooves, mane. These are our object’s attributes. Without these atributes nothing will differentiate a “horse” from a “lizard”. Thank you Captain Obvious, no one will ever mistake a horse for a lizard! That is true, but it’s very easy to mix up a “home” button that takes a user to index.php and a “home” button that takes them to my_personal_index.php. While both buttons may look identical to the user, their individual purposes are quite different, and thus their individual attributes make all the difference in the world.

Variables allow us to keep elements our of code dynamic by replacing static values with values that change according to user intervention. Attributes are no different, and as such can be written to change fluidly as the user interacts with the page.

Within a class, you have access to a special variable called $this. If you have an attribute called $decide, you refer to it as $this->decide when you are setting the attribute from an operation within the class. For example:

class classname
{
   var $decide;
   function form($param)
   {
      $this->decide = $param;
      echo $this->decide;
   }
}

This class declares a variable $decide, then uses the operation form (which is passed the parameter $param) to set the parameter to $decide. Written in code-speak, the class looks like so: $this->decide = $param. Fianlly, it accesses the attribute by printing it: echo $this->decide.

Operations are called in the same way attributes are called. First we declare our class:

class classname
{
   function form1()
   {
   }
   function form2($param1, $param2)
   {
   }
}

Then create an object:

$z = new classname();

Finally, we call the operations in the same way we call other functions, by name. However, because these operations belong to an object rather than a normal function, we must identify the object to which they pertain. We use the object’s name in the same way as the object’s attributes:

$z->form1();
$z->form2(2, 3);

If our operations return values we can retrieve them as variables like so:

$a = $z->form1();
$b = $z->form2(2, 3);

Still with me? All of this is pretty simple, mostly thanks to PHP’s logical nature. Pretty soon, we’ll see how complete classes can be used to load major elements of a page. First, let’s see how classes inherit attributes and operations from the classes above them.


Page 5 — Inheritance


Inheritance is what makes using classes more robust than simply using an include file. With inheritance, we can create a hierarchal relationship between classes and subclasses. A subclass inherits attributes and operations from its superclass, (the class above it in the hierarchy). Once again, we can save time and effort by writing a base superclass instead of spreading redundant operations over several classes. This base can then be inherited by subclasses and refined to meet even more specialized criteria.

To implement inheritance in PHP we use the keyword extends. For instance, the statement “class B extends class A” creates a Class B that inherits from Class A.

So if we have these classes:

class A
{
   var $decide1;
   function form1()
   {
   }
}
 
class B extends A
{
   var $decide2;
   function form2()
   {
   }
}

The following are valid accesses of operations and attributes from an object of type “B”:

$b = new B();
$b->form1();
$b->form2();
$b->decide1 = x;
$b->decide2 = y;

In addition, the following are valid for an object of the type “A”:

$a = new A();
$a->form1();
$a->decide1 = x;

However, inheritance only works one-way, so the following:

$a->form2();
$a->decide2 = y;

are not valid because form2() and $decide2 were created in class B. Class A does not inherit from Class B. This inheritance dynamic is also used to override values. For instance, if we declare a class A and class B again:


class A
{
   var $y = 'the first value';
   function form1()
   {
      echo "Our variable is $this->y";
   }
}
 
class B extends A
{
   var $y = 'the new value';
   function form1()
   {
      echo "Our variable is $this->y";
   }
}

class A is unaffected by declaring class B. The following is still the output of declaring Class A and creating an object of type A:

$a = new A();
$a->form1();

The above declaration will return:

Our variable is the first value

If we create an object of type B, like this:

$b = new B();
$b->form1();

it will return:

Our variable is the new value

 

 


Classes Put Into Action


Now, with your knowledge of classes and of the include() function, you can start setting up pages which contain objects that reference classes contained in included files. It all sounds a little complicated, but trust me. You’ll thank me shortly.

Let’s begin by creating a simple navigation menu to display on all of our site’s pages. We’ll name this document mainmenu.inc:

<?php
 
class mainmenu
{
                function mainmenu()
                {
                   echo '<table align="center" width="360" cellpadding="0"
  cellspacing="5">';
                   echo '<td><h2><center><a 
href="home.php">HOME</a></h2></td>';
                   echo '<td><h2><center><a
  href="services.php">SERVICES</a></h2></td>';
                   echo '<td><h2><center><a
  href="portfolio.php">PORTFOLIO</a></h2></td>';
                   echo '<td><h2><center><a
  href="contact.php">CONTACT</a></h2></td>';
                   echo '</table>';
                }
}
?>

We have created a class named mainmenu, we have also created a constructor named mainmenu so that when an object of the mainmenu type is created, it will perform the code within the class. The code within the function mainmenu is a pretty straightforward horizontal menu. There are different methods for producing this effect, such as storing the button names and URLs as a variable array, but we’ll keep it simple for the sake of introduction and let you go wild on it when you put it into practice.

Let’s create one more class before we create the page, shall we? Let’s tackle a stylesheet. We’ll call this styles.inc:


<?php
 
class stylesMainMenu
{
                function stylesMainMenu()
                {
?>
   <style type="text/css">
                h1 {font-family:Arial, Helvetica, sans-serif;
                font-size:14pt; color:#666666}
                h2 {font-family:Arial, Helvetica, sans-serif;
                font-size:10pt; color:#820000}
                a:link {color:#820000; text-decoration:none}
                a:visited {color:#820000; text-decoration:none}
                a:hover {color:#666666; text-decoration:none}
                a:active {color:#820000; text-decoration:none}                                  
   </style>
<?php
                }
}
?>

Notice that ?> precedes the actual stylesheet, and <?php follows the </style> tag. This escapes from PHP so that the content will be read as HTML and treated accordingly. Just remember that you must return to PHP to close the function and also close the class.

Alright, now comes the fun part. Let’s create index.php which will contain a menu that is formatted by our stylesheet:

<?php
 
include('mainmenu.inc');
include('styles.inc');
 
$page = new mainmenu();
$page = new stylesMainMenu();
 
?>

That’s it.

No, really, that’s it! We included mainmenu.inc and styles.inc, these provide us with the code for the menu and for our stylesheet. We then created a new object named $page by calling our constructors from within the mainmenu and stylesMainMenu classes. Objects do not always need to share their name ($page in this case), however, in order for the stylesheet to apply to the menu they need the same name.

You can make this operation as complicated or as simple as you like. In this example, we separated the classes into two files, mainmenu.inc and styles.inc, but they can both be stored in the same .inc files if you prefer. Furthermore, you can keep an entire library of stylesheets in a file called styles.inc. By making each stylesheet its own class, you can call on the attributes from that stylesheet simply by calling on its classname or contructor and including styles.inc. The same pertains to libraries of functions as well as redundant page elements such as menus, picture displays and information bars.

You can also make the menu itself dynamic by manipulating the operations within the mainmenu class. Treat these operations as instructed on page three of this lesson, and write them to conform to specific parameters and situations. For instance, you can create a conditional menu. Write the mainmenu operation so that if you are on index.php all of the buttons leading to the pages will be present in the menu, but if you are on services page, all buttons will be available except “services,” if you are on the portfolio page all buttons will be available except “portfolio”, and so on. Or perhaps you would like a different background for the menu depending on the page.

A little more on the MySQL SELECT statement

. Introduction

1.1 What is C#?

C# is a programming language designed by Microsoft. It is loosely based on C/C++, and bears a striking similarity to Java. Microsoft describe C# as follows:

“C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# (pronounced ‘C sharp’) is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++.”

You can get the ECMA C# spec in PDF form here, or use Jon Jagger’s html version.

1.2 How do I develop C# apps?

The (free) .NET SDK contains the C# command-line compiler (csc.exe). Visual Studio has fully integrated support for C# development. On Linux you can use Mono.

1.3 Does C# replace C++?

There are three options open to the Windows developer from a C++ background:

• Stick with standard C++. Don’t use .NET at all.

• Use C++ with .NET. Microsoft supply a .NET C++ compiler that produces IL rather than machine code. However to make full use of the .NET environment (e.g. garbage collection), a set of extensions are required to standard C++. In .NET 1.x this extended language is called Managed Extensions for C++. In .NET 2.0 ME C++ has been completely redesigned under the stewardship of Stan Lippman, and renamed C++/CLI.

• Forget C++ and use C#.

Each of these options has merits, depending on the developer and the application. For my own part, I intend to use C# where possible, falling back to C++ only where necessary. ME C++ (soon to be C++/CLI) is very useful for interop between new .NET code and old C++ code – simply write a managed wrapper class using ME C++, then use the managed class from C#. From experience, this works well.

1.4 Does C# have its own class library?

Not exactly. The .NET Framework has a comprehensive class library, which C# can make use of. C# does not have its own class library.

2. Types

2.1 What standard types does C# use?

C# supports a very similar range of basic types to C++, including int, long, float, double, char, string, arrays, structs and classes. However, don’t assume too much. The names may be familiar, but many of the details are different. For example, a long is 64 bits in C#, whereas in C++ the size of a long depends on the platform (typically 32 bits on a 32-bit platform, 64 bits on a 64-bit platform). Also classes and structs are almost the same in C++ – this is not true for C#. Finally, chars and strings in .NET are 16-bit (Unicode/UTF-16), not 8-bit like C++.

2.2 Is it true that all C# types derive from a common base class?

Yes and no. All types can be treated as if they derive from object (System.Object), but in order to treat an instance of a value type (e.g. int, float) as object-derived, the instance must be converted to a reference type using a process called ‘boxing’. In theory a developer can forget about this and let the run-time worry about when the conversion is necessary, but in reality this implicit conversion can have side-effects that may trip up the unwary.

2.3 So I can pass an instance of a value type to a method that takes an object as a parameter?

Yes. For example:

class CApplication

{

public static void Main()

{

int x = 25;

string s = “fred”;

DisplayMe( x );

DisplayMe( s );

}

static void DisplayMe( object o )

{

System.Console.WriteLine( “You are {0}”, o );

}

}

This would display:

You are 25

You are fred

2.4 What are the fundamental differences between value types and reference types?

C# divides types into two categories – value types and reference types. Most of the intrinsic types (e.g. int, char) are value types. Structs are also value types. Reference types include classes, arrays and strings. The basic idea is straightforward – an instance of a value type represents the actual data, whereas an instance of a reference type represents a pointer or reference to the data.

The most confusing aspect of this for C++ developers is that C# has predetermined which types are represented as values, and which are represented as references. A C++ developer expects to take responsibility for this decision.

For example, in C++ we can do this:

int x1 = 3; // x1 is a value on the stack

int *x2 = new int(3) // x2 is a pointer to a value on the heap

but in C# there is no control:

int x1 = 3; // x1 is a value on the stack

int x2 = new int();

x2 = 3; // x2 is also a value on the stack!

2.5 Okay, so an int is a value type, and a class is a reference type. How can int be derived from object?

It isn’t, really. When an int is being used as an int, it is a value. However, when it is being used as an object, it is a reference to an integer value (on the managed heap). In other words, when you treat an int as an object, the runtime automatically converts the int value to an object reference. This process is called boxing. The conversion involves copying the int to the heap, and creating an object instance which refers to it. Unboxing is the reverse process – the object is converted back to a value.

int x = 3; // new int value 3 on the stack

object objx = x; // new int on heap, set to value 3 – still have x=3 on stack

int y = (int)objx; // new value 3 on stack, still got x=3 on stack and objx=3 on heap

2.6 Are C# references the same as C++ references?

Not quite. The basic idea is the same, but one significant difference is that C# references can be null . So you cannot rely on a C# reference pointing to a valid object. In that respect a C# reference is more like a C++ pointer than a C++ reference. If you try to use a null reference, a NullReferenceException is thrown.

For example, look at the following method:

void displayStringLength( string s )

{

Console.WriteLine( “String is length {0}”, s.Length );

}

The problem with this method is that it will throw a NullReferenceException if called like this:

string s = null;

displayStringLength( s );

Of course for some situations you may deem a NullReferenceException to be a perfectly acceptable outcome, but in this case it might be better to re-write the method like this:

void displayStringLength( string s )

{

if( s == null )

Console.WriteLine( “String is null” );

else

Console.WriteLine( “String is length {0}”, s.Length );

}

2.7 Can I use typedefs in C#?

No, C# has no direct equivalent of the C++ typedef. C# does allow an alias to be specified via the using keyword:

using IntList = System.Collections.Generic.List<int>;

but the alias only applies in the file in which it is declared. A workaround in some cases is to use inheritance:

public class IntList : List<int> { }

The pros and cons of this approach are discussed here.

3. Classes and Structs

3.1 Structs are largely redundant in C++. Why does C# have them?

In C++, a struct and a class are pretty much the same thing. The only difference is the default visibility level (public for structs, private for classes). However, in C# structs and classes are very different. In C#, structs are value types (instances stored directly on the stack, or inline within heap-based objects), whereas classes are reference types (instances stored on the heap, accessed indirectly via a reference). Also structs cannot inherit from structs or classes, though they can implement interfaces. Structs cannot have destructors. A C# struct is much more like a C struct than a C++ struct.

3.2 Does C# support multiple inheritance (MI)?

No, though it does support implementation of multiple interfaces on a single class or struct.

3.3 Is a C# interface the same as a C++ abstract class?

No, not quite. An abstract class in C++ cannot be instantiated, but it can (and often does) contain implementation code and/or data members. A C# interface cannot contain any implementation code or data members – it is simply a group of method names & signatures. A C# interface is more like a COM interface than a C++ abstract class.

3.4 Are C# constructors the same as C++ constructors?

Very similar, but there are some significant differences. First, C# supports constructor chaining. This means one constructor can call another:

class Person

{

public Person( string name, int age ) { … }

public Person( string name ) : this( name, 0 ) {}

public Person() : this( “”, 0 ) {}

}

Another difference is that virtual method calls within a constructor are routed to the most derived implementation – see Can I Call a virtual method from a constructor.

Error handling is also somewhat different. If an exception occurs during construction of a C# object, the destuctor (finalizer) will still be called. This is unlike C++ where the destructor is not called if construction is not completed. (Thanks to Jon Jagger for pointing this out.)

Finally, C# has static constructors. The static constructor for a class runs before the first instance of the class is created.

Also note that (like C++) some C# developers prefer the factory method pattern over constructors. See Brad Wilson’s article.

3.5 Are C# destructors the same as C++ destructors?

No. They look the same but they are very different. The C# destructor syntax (with the familiar ~ character) is just syntactic sugar for an override of the System.Object Finalize method. This Finalize method is called by the garbage collector when it determines that an object is no longer referenced, before it frees the memory associated with the object. So far this sounds like a C++ destructor. The difference is that the garbage collector makes no guarantees about when this procedure happens. Indeed, the algorithm employed by the CLR garbage collector means that it may be a long time after the application has finished with the object. This lack of certainty is often termed ‘non-deterministic finalization’, and it means that C# destructors are not suitable for releasing scarce resources such as database connections, file handles etc.

To achieve deterministic destruction, a class must offer a method to be used for the purpose. The standard approach is for the class to implement the IDisposable interface. The user of the object must call the Dispose() method when it has finished with the object. C# offers the ‘using’ construct to make this easier.

3.6 If C# destructors are so different to C++ destructors, why did MS use the same syntax?

Presumably they wanted C++ programmers to feel at home. I think they made a mistake.

3.7 Are all methods virtual in C#?

No. Like C++, methods are non-virtual by default, but can be marked as virtual.

3.8 How do I declare a pure virtual function in C#?

Use the abstract modifier on the method. The class must also be marked as abstract (naturally). Note that abstract methods cannot have an implementation (unlike pure virtual C++ methods).

3.9 Can I call a virtual method from a constructor/destructor?

Yes, but it’s generally not a good idea. The mechanics of object construction in .NET are quite different from C++, and this affects virtual method calls in constructors.

C++ constructs objects from base to derived, so when the base constructor is executing the object is effectively a base object, and virtual method calls are routed to the base class implementation. By contrast, in .NET the derived constructor is executed first, which means the object is always a derived object and virtual method calls are always routed to the derived implementation. (Note that the C# compiler inserts a call to the base class constructor at the start of the derived constructor, thus preserving standard OO semantics by creating the illusion that the base constructor is executed first.)

The same issue arises when calling virtual methods from C# destructors. A virtual method call in a base destructor will be routed to the derived implementation.

3.10 Should I make my destructor virtual?

A C# destructor is really just an override of the System.Object Finalize method, and so is virtual by definition.

4. Exceptions

4.1 Can I use exceptions in C#?

Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors.

4.2 What types of object can I throw as exceptions?

Only instances of the System.Exception classes, or classes derived from System.Exception. This is in sharp contrast with C++ where instances of almost any type can be thrown.

4.3 Can I define my own exceptions?

Yes, just derive your exception class from System.Exception.

Note that if you want your exception to cross remoting boundaries you’ll need to do some extra work – see http://www.thinktecture.com/Resources/RemotingFAQ/CustomExceptions.html for details.

4.4 Does the System.Exception class have any cool features?

Yes – the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from. For example, the following code:

using System;

class CApp

{

public static void Main()

{

try

{

f();

}

catch( Exception e )

{

Console.WriteLine( “System.Exception stack trace = \n{0}”, e.StackTrace );

}

}

static void f()

{

throw new Exception( “f went pear-shaped” );

}

}

produces this output:

System.Exception stack trace =

at CApp.f()

at CApp.Main()

Note, however, that this stack trace was produced from a debug build. A release build may optimise away some of the method calls which could mean that the call stack isn’t quite what you expect.

4.5 When should I throw an exception?

This is the subject of some debate, and is partly a matter of taste. However, it is accepted by many that exceptions should be thrown only when an ‘unexpected’ error occurs. How do you decide if an error is expected or unexpected? This is a judgement call, but a straightforward example of an expected error is failing to read from a file because the seek pointer is at the end of the file, whereas an example of an unexpected error is failing to allocate memory from the heap.

4.6 Does C# have a ‘throws’ clause?

No, unlike Java, C# does not require (or even allow) the developer to specify the exceptions that a method can throw.

5. Run-time Type Information

5.1 How can I check the type of an object at runtime?

You can use the is keyword. For example:

using System;

class CApp

{

public static void Main()

{

string s = “fred”;

long i = 10;

Console.WriteLine( “{0} is {1}an integer”, s, (IsInteger(s) ? “” : “not “) );

Console.WriteLine( “{0} is {1}an integer”, i, (IsInteger(i) ? “” : “not “) );

}

static bool IsInteger( object obj )

{

if( obj is int || obj is long )

return true;

else

return false;

}

}

produces the output:

fred is not an integer

10 is an integer

5.2 Can I get the name of a type at runtime?

Yes, use the GetType method of the object class (which all types inherit from). For example:

using System;

class CTest

{

class CApp

{

public static void Main()

{

long i = 10;

CTest ctest = new CTest();

DisplayTypeInfo( ctest );

DisplayTypeInfo( i );

}

static void DisplayTypeInfo( object obj )

{

Console.WriteLine( “Type name = {0}, full type name = {1}”, obj.GetType(), obj.GetType().FullName );

}

}

}

produces the following output:

Type name = CTest, full type name = CTest

Type name = Int64, full type name = System.Int64

5.3 What is the difference between typeof and GetType()?

Apart from the obvious (i.e. typeof operates on a type whereas GetType operates on an object), the main thing to watch out for is that GetType returns the underlying type of the object, which may not be the same as the type of the reference to the object. For example:

class Base { }

class Derived : Base { }

class Program

{

static void Main()

{

ShowType( new Derived() );

}

static void ShowType( Base b )

{

Console.WriteLine(typeof(Base));

Console.WriteLine(b.GetType());

}

}

gives the following output:

Base

Derived

6. Miscellaneous

6.1 How do I do a case-insensitive string comparison?

Use the String.Compare function. Its third parameter is a boolean which specifies whether case should be ignored or not.

“fred” == “Fred” // false

System.String.Compare( “fred”, “Fred”, true ) == 0 // true

For more control over the comparison, e.g. exotic features like width-sensitivity, consider using System.Globalization.CompareInfo.Compare(), e.g.

CultureInfo.CurrentCulture.CompareInfo.Compare(

“fred”, “Fred”,

CompareOptions.IgnoreCase |

CompareOptions.IgnoreKanaType |

CompareOptions.IgnoreWidth

);

6.2 Does C# support a variable number of arguments?

Yes, using the params keyword. The arguments are specified as a list of arguments of a specific type, e.g. int. For ultimate flexibility, the type can be object. The standard example of a method which uses this approach is System.Console.WriteLine().

6.3 How can I process command-line arguments?

Like this:

using System;

class CApp

{

public static void Main( string[] args )

{

Console.WriteLine( “You passed the following arguments:” );

foreach( string arg in args )

Console.WriteLine( arg );

}

}

6.4 Does C# do array bounds checking?

Yes. An IndexOutOfRange exception is used to signal an error.

6.5 How can I make sure my C# classes will interoperate with other .NET languages?

Make sure your C# code conforms to the Common Language Subset (CLS). To help with this, add the [assembly:CLSCompliant(true)] global attribute to your C# source files. The compiler will emit an error if you use a C# feature which is not CLS-compliant.

6.6 How do I use the ‘using’ keyword with multiple objects?

You can nest using statements, like this:

using( obj1 )

{

using( obj2 )

{

}

}

However consider using this more aesthetically pleasing (but functionally identical) formatting:

using( obj1 )

using( obj2 )

{

}

6.7 What is the difference between == and object.Equals?

For value types, == and Equals() usually compare two objects by value. For example:

int x = 10;

int y = 10;

Console.WriteLine( x == y );

Console.WriteLine( x.Equals(y) );

will display:

True

True

However things are more complex for reference types. Generally speaking, for reference types == is expected to perform an identity comparison, i.e. it will only return true if both references point to the same object. By contrast, Equals() is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent. For example:

StringBuilder s1 = new StringBuilder(“fred”);

StringBuilder s2 = new StringBuilder(“fred”);

Console.WriteLine( s1 == s2 );

Console.WriteLine( s1.Equals(s2) );

will display:

False

True

s1 and s2 are different objects (hence == returns false), but they are equivalent (hence Equals() returns true).

Unfortunately there are exceptions to these rules. The implementation of Equals() in System.Object (the one you’ll inherit by default if you write a class) compares identity, i.e. it’s the same as operator==. So Equals() only tests for equivalence if the class author overrides the method (and implements it correctly). Another exception is the string class – its operator== compares value rather than identity.

Bottom line: If you want to perform an identity comparison use the ReferenceEquals() method. If you want to perform a value comparison, use Equals() but be aware that it will only work if the type has overridden the default implementation. Avoid operator== with reference types (except perhaps strings), as it’s simply too ambiguous.

6.8 How do I enforce const correctness in C#?

You can’t – at least not in the same way you do in C++. C# (actually, the CLI) has no real concept of const correctness, For example, there’s no way to specify that a method should not modify an argument passed in to it. And there’s no way to specify that a method does not modify the object on which it is acting.

To get a feel for the angst this causes among some C++ programmers, read the feedback on this post from Raymond Chen.

There are of course ways of addressing this issue. For example, see Brad Abram’s post (and associated feedback) for some ideas on adding optional read-only behaviour to collection classes.

7. C# 2.0

7.1 What are the new features in C# 2.0?

Support for all of the new framework features such as generics, anonymous methods, partial classes, iterators and static classes. See the .NET FAQ for more on these features.

Delegate inference is a new feature of the C# compiler which makes delegate usage a little simpler. It allows you to write this:

Thread t = new Thread(ThreadFunc);

instead of this:

Thread t = new Thread( new ThreadStart(ThreadFunc) );

Another minor but welcome addition is the explicit global namespace, which fixes a hole in namespace usage in C# 1.x. You can prefix a type name with global:: to indicate that the type belongs to the global namespace, thus avoiding problems where the compiler infers the namespace and gets it wrong.

Finally C# 2.0 includes some syntactic sugar for the new System.Nullable type. You can use T? as a synonym for System.Nullable<T>, where T is a value type. As suggested by the name, this allows values of the type to be ‘null’, or ‘undefined’.

7.2 Are C# generics the same as C++ templates?

No, not really. There are some similarities, but there are also fundamental differences. See the .NET FAQ for more details.



  • None
  • Mr WordPress: Hi, this is a comment.To delete a comment, just log in, and view the posts' comments, there you will have the option to edit or delete them.

Categories