Monday, 27 August 2012
Programming World: ASP.NET Interview Question
Programming World: ASP.NET Interview Question: ASP.NET With C Sharp (Index) ASP.NET Interview Questions 1. When using an implicitly typed array, which of the fo...
Programming World: Copy records from one table to another in SQL
Programming World: Copy records from one table to another in SQL: SQL Interview Questions (Index) Copy records from one table to another in SQL Many times the following questions are asked regarding...
Thursday, 9 August 2012
System.Diagnostics.StackTrace
StackTrace
The .Net frameworks provides the System.Diagnostics.StackTrace class which allows you to get a stack trace at runtime. It is handy for diagnostic purposes. The StackTrace class has following features:
Example
void PrintStackTrace()
{
StackTrace st = new StackTrace(true); // true means get line numbers.
foreach(StackFrame f in st.GetFrames())
{
Console.Write(f);
}
- It represents the actual stack running.
- It only shows managed frames and does not show any native frames.
- The stack trace class can get method names and even IL offsets without symbols
Example
void PrintStackTrace()
{
StackTrace st = new StackTrace(true); // true means get line numbers.
foreach(StackFrame f in st.GetFrames())
{
Console.Write(f);
}
Monday, 30 July 2012
Attributes In C#
Attributes
Attributes extend the capabilities of C# language. A .NET application contains code, data and metadata. Metadata is the information about the data, which contains information about the types, code, methods, assemblies and so forth. Attributes are a mechanism of adding metadata like some declarative information about methods, classes, objects to the program itself. They can be extracted using runtime services.
Attributes can be mentioned as annotations that a program can store and use. Attribute is an extended way to document a code. We can use attributes to define both design-level information (such as help file, URL for documentation) and run – time information (such as associating XML field with class field). We can also create ‘self – describing” components using attributes.
Uses Of Attributes
Attributes provide a power method of associating declarative information with C# code. Some of the uses of attributes are:
- Attributes are used to indicate which field in a database a particular property should be written to.
- Attributes are declarative information to various program entities which can be retrieved at run-time.
- Attributes can be used to define both design-level information such as a help file or a URL for documentation and run-time information such as associating an XML field with a class field.
- Attributes describe how to serialize data, specify characteristics that are used to enforce security, and limit optimization by the just-in-time compiler so the code remains easy to debug.
Types of Attributes
There are two types of attributes namely:
- Built-in attributes
The built-in attributes are a part of CLR and they are integrated into .NET. The .NET Framework is equipped with a number of built-in attributes that performs a host of functions. Some of the predefined attributes are:- STAThread
- Conditional
- DllImport
- Obsolete
- Custom attributes
There are situations in which the predefined .NET Framework attributes does not satisfy a programmer’s requirements. In such a scenario, custom attributes can be created which can provide properties that allow to store and retrieve information.
Built In Attributes
- Conditional
- DllImport
“Conditional” Attribute
Conditional attribute can be used as debugging aid in the C# code. The C# conditional attribute basically allows you to control when a method should and should not be called. The benefit of the C# conditional attribute is that it is applied at the method level, which results in source code that is more readable. This attribute causes conditional compilation of method calls, depending on the value of the symbol that is defined. This method which is marked by a conditional attribute should always return void or else it will generate a compilation error. There are some restrictions on declaring a conditional method. They are:
using System;
using System.Diagnostics;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
string _name;
[Conditional ("DEBUG")]
public void GetName()
{
Console.WriteLine("Enter Name of the Employee: ");
_name = Console.ReadLine();
Console.WriteLine("Hi {0}. How are you!!", _name);
}
public static void Main()
{
Console.WriteLine("Before calling the method GetName()");
new Program().GetName();
}
}
}
- This method must be a method in a class or in a struct.
- This method must have a return type of void.
- This method can be marked with the virtual modifier but not with the override modifier.
- This method must not be an implementation of an interface method.
using System;
using System.Diagnostics;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
string _name;
[Conditional ("DEBUG")]
public void GetName()
{
Console.WriteLine("Enter Name of the Employee: ");
_name = Console.ReadLine();
Console.WriteLine("Hi {0}. How are you!!", _name);
}
public static void Main()
{
Console.WriteLine("Before calling the method GetName()");
new Program().GetName();
}
}
}
DllImport Attribute
DLL is an acronym for Dynamic Link Library. DllImport attribute can be used to invoke unmanaged code in C# program. Unmanaged code is the code that has been developed outside the .NET environment. By using this attribute, unmanaged code can be invoked residing in the DLLs from a managed C# environment. The namespace System.Runtime.InteropServices should be imported in order to work with the DllImport attribute.
Example – User32.dll
class Coffeeparlour is a sealed class in this example
using System;
using System.Collections.Generic;
using System.Text;
namespace Coffee
{
sealed class CoffeeParlour
{
[DllImport("User32.dll")]
public static extern int MessageBox(int hParent, string message, string caption, int type);
private const decimal _basePrice = 1.55M;
private string[] _flavor;
private string[] _ingredient;
private int _cups;
private decimal _totalPrice;
public CoffeeParlour()
{
_flavor = new string[3];
_flavor[0] = "Coffee";
_flavor[1] = "Mocha";
_flavor[2] = "Caramel";
_ingredient = new string[3];
_ingredient[0] = "No Ingredient";
_ingredient[1] = "Chocolate Cream";
_ingredient[2] = "Caramel Cream";
}
public int ChooseFlavor()
{
int choice = 0;
for (int i = 0; i < _flavor.Length; i++) { Console.WriteLine("{0} - {1}", i + 1, _flavor[i]); } do { try { Console.Write("Your Choice? "); choice = int.Parse(Console.ReadLine()); if (choice < 1 || choice > _flavor.Length)
Console.WriteLine("Invalid Choice - Try Again!\n");
}
catch (FormatException)
{
Console.WriteLine("Please enter a valid number!");
}
catch (Exception)
{
Console.WriteLine("Wrong input");
}
} while (choice < 1 || choice > _flavor.Length);
return choice;
}
public int ChooseIngredient()
{
int choice = 0;
Console.WriteLine("\nDo you want an ingredient?");
for (int i = 0; i < _ingredient.Length; i++) { Console.WriteLine("{0} - {1}", i + 1, _ingredient[i]); } do { try { Console.Write("Your Choice? "); choice = int.Parse(Console.ReadLine()); if (choice < 1 || choice > _ingredient.Length)
Console.WriteLine("Invalid Choice - Try Again!\n");
}
catch (FormatException)
{
Console.WriteLine("Please enter a valid number!");
}
catch (Exception)
{
Console.WriteLine("Wrong input");
}
} while (choice < 1 || choice > _ingredient.Length);
return choice;
}
public void SpecifyNumberOfCups()
{
do
{
try
{
Console.Write("How many cups(1,2 or 3)?");
_cups = int.Parse(Console.ReadLine());
if (_cups < 1 || _cups > 3)
Console.WriteLine("Invalid Choice - Try Again!");
}
catch (FormatException)
{
Console.WriteLine("Please enter a valid number!");
}
catch (Exception)
{
Console.WriteLine("Wrong input");
}
} while (_cups < 1 || _cups > 3);
}
public void ProcessCustomerOrder()
{
int choiceFlavor;
int choiceIngredient;
decimal priceIngredient, priceCup;
Console.WriteLine("David's Coffee parlour");
choiceFlavor = ChooseFlavor();
choiceIngredient = ChooseIngredient();
SpecifyNumberOfCups();
if (choiceIngredient == 2 || choiceIngredient == 3)
priceIngredient = 0.50M;
else
priceIngredient = 0;
if (_cups == 1)
priceCup = 0.65M;
else if (_cups == 2)
priceCup = 1.05M;
else
priceCup = 1.55M;
_totalPrice = priceCup + priceIngredient;
DisplayReceipt(ref choiceFlavor, ref choiceIngredient);
}
[Conditional("DEBUG")]
public void DisplayReceipt(ref int flavor, ref int ingredient)
{
String str = "Flavor: " + Convert.ToString(_flavor[flavor - 1]);
str += "\nIngredient: " + Convert.ToString(_ingredient[ingredient - 1]);
str += "\nCups: " + Convert.ToString(_cups);
str += "\nTotal Amount: $" + Convert.ToString(_totalPrice);
MessageBox(0, str, "Coffee Order", 0);
}
}
}
Class Program
using System;
using System.Collections.Generic;
using System.Text;
namespace Coffee
{
class Program
{
static void Main(string[] args)
{
CoffeeParlour objCoffeeParlour = new CoffeeParlour();
objCoffeeParlour.ProcessCustomerOrder();
}
}
}
Example – User32.dll
class Coffeeparlour is a sealed class in this example
using System;
using System.Collections.Generic;
using System.Text;
namespace Coffee
{
sealed class CoffeeParlour
{
[DllImport("User32.dll")]
public static extern int MessageBox(int hParent, string message, string caption, int type);
private const decimal _basePrice = 1.55M;
private string[] _flavor;
private string[] _ingredient;
private int _cups;
private decimal _totalPrice;
public CoffeeParlour()
{
_flavor = new string[3];
_flavor[0] = "Coffee";
_flavor[1] = "Mocha";
_flavor[2] = "Caramel";
_ingredient = new string[3];
_ingredient[0] = "No Ingredient";
_ingredient[1] = "Chocolate Cream";
_ingredient[2] = "Caramel Cream";
}
public int ChooseFlavor()
{
int choice = 0;
for (int i = 0; i < _flavor.Length; i++) { Console.WriteLine("{0} - {1}", i + 1, _flavor[i]); } do { try { Console.Write("Your Choice? "); choice = int.Parse(Console.ReadLine()); if (choice < 1 || choice > _flavor.Length)
Console.WriteLine("Invalid Choice - Try Again!\n");
}
catch (FormatException)
{
Console.WriteLine("Please enter a valid number!");
}
catch (Exception)
{
Console.WriteLine("Wrong input");
}
} while (choice < 1 || choice > _flavor.Length);
return choice;
}
public int ChooseIngredient()
{
int choice = 0;
Console.WriteLine("\nDo you want an ingredient?");
for (int i = 0; i < _ingredient.Length; i++) { Console.WriteLine("{0} - {1}", i + 1, _ingredient[i]); } do { try { Console.Write("Your Choice? "); choice = int.Parse(Console.ReadLine()); if (choice < 1 || choice > _ingredient.Length)
Console.WriteLine("Invalid Choice - Try Again!\n");
}
catch (FormatException)
{
Console.WriteLine("Please enter a valid number!");
}
catch (Exception)
{
Console.WriteLine("Wrong input");
}
} while (choice < 1 || choice > _ingredient.Length);
return choice;
}
public void SpecifyNumberOfCups()
{
do
{
try
{
Console.Write("How many cups(1,2 or 3)?");
_cups = int.Parse(Console.ReadLine());
if (_cups < 1 || _cups > 3)
Console.WriteLine("Invalid Choice - Try Again!");
}
catch (FormatException)
{
Console.WriteLine("Please enter a valid number!");
}
catch (Exception)
{
Console.WriteLine("Wrong input");
}
} while (_cups < 1 || _cups > 3);
}
public void ProcessCustomerOrder()
{
int choiceFlavor;
int choiceIngredient;
decimal priceIngredient, priceCup;
Console.WriteLine("David's Coffee parlour");
choiceFlavor = ChooseFlavor();
choiceIngredient = ChooseIngredient();
SpecifyNumberOfCups();
if (choiceIngredient == 2 || choiceIngredient == 3)
priceIngredient = 0.50M;
else
priceIngredient = 0;
if (_cups == 1)
priceCup = 0.65M;
else if (_cups == 2)
priceCup = 1.05M;
else
priceCup = 1.55M;
_totalPrice = priceCup + priceIngredient;
DisplayReceipt(ref choiceFlavor, ref choiceIngredient);
}
[Conditional("DEBUG")]
public void DisplayReceipt(ref int flavor, ref int ingredient)
{
String str = "Flavor: " + Convert.ToString(_flavor[flavor - 1]);
str += "\nIngredient: " + Convert.ToString(_ingredient[ingredient - 1]);
str += "\nCups: " + Convert.ToString(_cups);
str += "\nTotal Amount: $" + Convert.ToString(_totalPrice);
MessageBox(0, str, "Coffee Order", 0);
}
}
}
Class Program
using System;
using System.Collections.Generic;
using System.Text;
namespace Coffee
{
class Program
{
static void Main(string[] args)
{
CoffeeParlour objCoffeeParlour = new CoffeeParlour();
objCoffeeParlour.ProcessCustomerOrder();
}
}
}
Obsolete
using System;
using System.Collections.Generic;
using System.Text;
namespace BuiltInAttr
{
class Program
{
[Obsolete("Don't use Old method, use New method", true)]
static void Old() { }
static void New() { }
static void Main(string[] args)
{
Old();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace BuiltInAttr
{
class Program
{
[Obsolete("Don't use Old method, use New method", true)]
static void Old() { }
static void New() { }
static void Main(string[] args)
{
Old();
}
}
}
Custom Attributes
Custom attributes, like built-in attributes are objects that are associated with one or more programmatic elements. They are stored with the metadata of their associated elements, and provide mechanisms for a program to retrieve their values. E.g. a custom attribute can be created which would allow storing information about code modifications that is normally recorded as comments in a source code. The System.Attribute class represents the base class for custom attributes. This class provides all the necessary methods to retrieve custom attributes.
AttributeUsage attribute help to control the usage of custom attributes. The parameter to AttributeUsage contains values from the System.AttributeTarges enumeration to specify how the custom attribute can be used.
AttributeUsage has three properties that can be set by defining the parameters, ValidOn, AllowMultiple and Inherited. Defining or controlling Usage of Custom Attribute
1.
using System;
namespace ConsoleApplication1
{
class ParentAttribute : Attribute
{
protected String description;
public ParentAttribute(String Description_in)
{
this.description = Description_in;
}
public String Description
{
get
{
return this.description;
}
}
}
[Parent("this is a class")]
class Program
{
public static void Main() { }
}
}
2.
AttributeUsage is a pre – defined class that helps in controlling the usage of custom attributes. i.e. we can define attributes of custom attribute class. AttributeUsage has 3 properties which can be set while placing it on our custom attribute.
using System;
namespace ConsoleApplication1
{
[AttributeUsage(AttributeTargets.Class,AllowMultiple=true,Inherited=false)]
class ParentAttribute : Attribute
{
protected String description;
public ParentAttribute(String Description_in)
{
this.description = Description_in;
}
public String Description
{
get
{
return this.description;
}
}
}
[Parent("this is a class")]
class Program
{
//[Parent("this is a class")]
public static void Main() { }
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace TokyoSoftwares
{
[AttributeUsage(AttributeTargets.All,Inherited =true,AllowMultiple=true)]
class CodeAttributes: Attribute
{
private string _developerName;
private string _reviewerName;
private string _developmentDate;
private string _versionNo;
private string _reviewDate;
private string _comment;
public CodeAttributes(string developerName, string reviewerName, string developmentDate, string versionNo, string reviewDate)
{
this._developerName = developerName;
this._reviewerName = reviewerName;
this._developmentDate = developmentDate;
this._versionNo = versionNo;
this._reviewDate = reviewDate;
}
public string DeveloperName
{
get
{
return _developerName;
}
}
public string ReviewerName
{
get
{
return _reviewerName;
}
}
public string ReviewDate
{
get
{
return _reviewDate;
}
}
public string VersionNo
{
get
{
return _versionNo;
}
set
{
_versionNo = value;
}
}
public string Date
{
get
{
return _developmentDate;
}
}
public string Comment
{
get
{
return _comment;
}
set
{
_comment = value;
}
}
}
[CodeAttributes("Allan John","Paul Nixon","01/03/10","1.1","03/03/10",Comment="First Review")]
[CodeAttributes("Allan John","Paul Nixon","04/03/10","1.2","06/03/10",Comment="Fixed error in Caluclations")]
[CodeAttributes("Allan John","Paul Nixon","07/03/10","1.3","08/03/10",Comment="Error Closed")]
class Employee
{
private string _name;
protected float BillingRate;
private string _designation;
public Employee(){}
public Employee(string name, float billingRate, string designation)
{
this._name = name;
this.BillingRate = billingRate;
this._designation = designation;
}
public virtual float CalculateSalary(float hours)
{
return (hours * BillingRate);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace TokyoSoftwares
{
class Program
{
static void Main(string[] args)
{
Employee objManager;
objManager = new Employee("Smith", 600F, "Project Manager");
Console.WriteLine("Salary for Smith = {0}", objManager.CalculateSalary(2F));
Employee objManager1;
objManager1 = new Employee("Allan", 200.5F, "Software Developer");
Console.WriteLine("Salary for Allan = {0}", objManager1.CalculateSalary(2F));
MemberInfo objMemberInfo = typeof(Employee);
object[] attributes;
attributes = objMemberInfo.GetCustomAttributes(typeof(CodeAttributes), false);
Console.WriteLine("\n\tAttribute Information for class Employee");
foreach (Object attribute in attributes)
{
CodeAttributes objCodeInfo = (CodeAttributes)attribute;
Console.WriteLine("Developer Name: {0}", objCodeInfo.DeveloperName);
Console.WriteLine("Reviewer Name: {0}", objCodeInfo.ReviewerName);
Console.WriteLine("Date of Development: {0}", objCodeInfo.Date);
Console.WriteLine("Date of Review: {0}", objCodeInfo.ReviewDate);
Console.WriteLine("Version No. {0}", objCodeInfo.VersionNo);
Console.WriteLine("Comment: {0}\n", objCodeInfo.Comment);
}
}
}
}
using System;
using System.Runtime.InteropServices;
namespace ConditionalTest
{
class TestWin32
{
[DllImport("User32.dll")]
public static extern int MessageBox(int hParent, string message, string caption, int type);
public static void Main(string [] args)
{
int counter = 1;
while (counter < 5) { Console.WriteLine("This is Line {0}", counter); counter++; if (counter == 3) { MessageBox(0, "Program Execution Stopped", "Message",0); break; } } } } }
Custom Attributes – “AttributeUsage” Attribute
AttributeUsage attribute help to control the usage of custom attributes. The parameter to AttributeUsage contains values from the System.AttributeTarges enumeration to specify how the custom attribute can be used.
AttributeUsage has three properties that can be set by defining the parameters, ValidOn, AllowMultiple and Inherited. Defining or controlling Usage of Custom Attribute
1.
using System;
namespace ConsoleApplication1
{
class ParentAttribute : Attribute
{
protected String description;
public ParentAttribute(String Description_in)
{
this.description = Description_in;
}
public String Description
{
get
{
return this.description;
}
}
}
[Parent("this is a class")]
class Program
{
public static void Main() { }
}
}
2.
AttributeUsage is a pre – defined class that helps in controlling the usage of custom attributes. i.e. we can define attributes of custom attribute class. AttributeUsage has 3 properties which can be set while placing it on our custom attribute.
- ValidOn: Through this property, we can define the program entities on which our custom attribute can be placed. The set of all possible program entities on which an attribute can be placed is listed in the AttributeTargets enumerator. We can combine several AttributeTargets using a bitwise OR operation.
- AllowMultiple: This property marks whether our custom attribute can be placed more than once on the same program entity.
- Inherited: We can control the inheritance rules of our attribute using this property. This property marks whether our attribute will be inherited by the class derived from the class on which we have placed it.
using System;
namespace ConsoleApplication1
{
[AttributeUsage(AttributeTargets.Class,AllowMultiple=true,Inherited=false)]
class ParentAttribute : Attribute
{
protected String description;
public ParentAttribute(String Description_in)
{
this.description = Description_in;
}
public String Description
{
get
{
return this.description;
}
}
}
[Parent("this is a class")]
class Program
{
//[Parent("this is a class")]
public static void Main() { }
}
}
“AttributeUsage” - AttributeTargets.All
using System;
using System.Collections.Generic;
using System.Text;
namespace TokyoSoftwares
{
[AttributeUsage(AttributeTargets.All,Inherited =true,AllowMultiple=true)]
class CodeAttributes: Attribute
{
private string _developerName;
private string _reviewerName;
private string _developmentDate;
private string _versionNo;
private string _reviewDate;
private string _comment;
public CodeAttributes(string developerName, string reviewerName, string developmentDate, string versionNo, string reviewDate)
{
this._developerName = developerName;
this._reviewerName = reviewerName;
this._developmentDate = developmentDate;
this._versionNo = versionNo;
this._reviewDate = reviewDate;
}
public string DeveloperName
{
get
{
return _developerName;
}
}
public string ReviewerName
{
get
{
return _reviewerName;
}
}
public string ReviewDate
{
get
{
return _reviewDate;
}
}
public string VersionNo
{
get
{
return _versionNo;
}
set
{
_versionNo = value;
}
}
public string Date
{
get
{
return _developmentDate;
}
}
public string Comment
{
get
{
return _comment;
}
set
{
_comment = value;
}
}
}
[CodeAttributes("Allan John","Paul Nixon","01/03/10","1.1","03/03/10",Comment="First Review")]
[CodeAttributes("Allan John","Paul Nixon","04/03/10","1.2","06/03/10",Comment="Fixed error in Caluclations")]
[CodeAttributes("Allan John","Paul Nixon","07/03/10","1.3","08/03/10",Comment="Error Closed")]
class Employee
{
private string _name;
protected float BillingRate;
private string _designation;
public Employee(){}
public Employee(string name, float billingRate, string designation)
{
this._name = name;
this.BillingRate = billingRate;
this._designation = designation;
}
public virtual float CalculateSalary(float hours)
{
return (hours * BillingRate);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace TokyoSoftwares
{
class Program
{
static void Main(string[] args)
{
Employee objManager;
objManager = new Employee("Smith", 600F, "Project Manager");
Console.WriteLine("Salary for Smith = {0}", objManager.CalculateSalary(2F));
Employee objManager1;
objManager1 = new Employee("Allan", 200.5F, "Software Developer");
Console.WriteLine("Salary for Allan = {0}", objManager1.CalculateSalary(2F));
MemberInfo objMemberInfo = typeof(Employee);
object[] attributes;
attributes = objMemberInfo.GetCustomAttributes(typeof(CodeAttributes), false);
Console.WriteLine("\n\tAttribute Information for class Employee");
foreach (Object attribute in attributes)
{
CodeAttributes objCodeInfo = (CodeAttributes)attribute;
Console.WriteLine("Developer Name: {0}", objCodeInfo.DeveloperName);
Console.WriteLine("Reviewer Name: {0}", objCodeInfo.ReviewerName);
Console.WriteLine("Date of Development: {0}", objCodeInfo.Date);
Console.WriteLine("Date of Review: {0}", objCodeInfo.ReviewDate);
Console.WriteLine("Version No. {0}", objCodeInfo.VersionNo);
Console.WriteLine("Comment: {0}\n", objCodeInfo.Comment);
}
}
}
}
Using Win32API
using System;
using System.Runtime.InteropServices;
namespace ConditionalTest
{
class TestWin32
{
[DllImport("User32.dll")]
public static extern int MessageBox(int hParent, string message, string caption, int type);
public static void Main(string [] args)
{
int counter = 1;
while (counter < 5) { Console.WriteLine("This is Line {0}", counter); counter++; if (counter == 3) { MessageBox(0, "Program Execution Stopped", "Message",0); break; } } } } }
Friday, 27 July 2012
ASP.NET Utilities
ASP.NET Utilities
ASP.NET Model
ASP.Net is a web development platform, which provides a programming model, a comprehensive software infrastructure and various services required to build up robust web application for PC, as well as mobile devices.
ASP.Net works on top of the HTTP protocol and uses the HTTP commands and policies to set a browser-to-server two-way communication and cooperation.
ASP.Net is a part of Microsoft .Net platform. ASP.Net applications are complied codes, written using the extensible and reusable components or objects present in .Net framework. These codes can use the entire hierarchy of classes in .Net framework.
The ASP.Net application codes could be written in any of the following languages:
- C#
- Visual Basic .Net
- Jscript
- J#
ASP.Net is used to produce interactive, data-driven web applications over the internet. It consists of a large number of controls like text boxes, buttons and labels for assembling, configuring and manipulating code to create HTML pages.
ASP.Net Web Forms Model
ASP.Net web forms extend the event-driven model of interaction to the web applications. The browser submits a web form to the web server and the server returns a full markup page or HTML page in response.
All client side user activities are forwarded to the server for stateful processing. The server processes the output of the client actions and triggers the reactions.
Now, HTTP is a stateless protocol. ASP.Net framework helps in storing the information regarding the state of the application, which consists of:
- Page state
- Session state
The session state is the collective obtained from various pages the user visited and worked with, i.e., the overall session state.
The ASP.Net runtime carries the page state to and from the server across page requests while generating the ASP.Net runtime codes and incorporates the state of the server side components in hidden fields.
ASP.Net Component Model
The ASP.Net component model provides various building blocks of ASP.Net pages. Basically it is an object model, which describes:
- Server side counterparts of almost all HTML elements or tags, like <form> and <input>.
- Server controls, which help in developing complex user-interface for example the Calendar control or the Gridview control.
ASP.Net is a technology, which works on the .Net framework that contains all web-related functionalities. The .Net framework is made of an object-oriented hierarchy. An ASP.Net web application is made of pages. When a user requests an ASP.Net page, the IIS delegates the processing of the page to the ASP.Net runtime system.
The ASP.Net runtime transforms the .aspx page into an instance of a class, which inherits from the base class Page of the .Net framework. Therefore, each ASP.Net page is an object and all its components i.e., the server-side controls are also objects.
Components of .Net Framework 4
The various components the .Net framework 4 are:
- Common Language Runtime or CLR
It performs memory management, exception handling, debugging, security checking, thread execution, code execution, code safety, verification and compilation.Those codes which are directly managed by the CLR are called the managed code. When the managed code is compiled, the compiler converts the source code into a CPU independent intermediate language (IL) code. A Just in time compiler (JIT) compiles the IL code into native code, which is CPU specific. - .Net Framework Class Library
It contains a huge library of reusable types . classes, interfaces, structures and enumerated values, which are collectively called types. - Common Language Specification
It contains the specifications for the .Net supported languages and implementation of language integration. - Common Type System
It provides guidelines for declaring, using and managing types at runtime, and cross-language communication. - Metadata and Assemblies
Metadata is the binary information describing the program, which is either stored in a portable executable file (PE) or in the memory. Assembly is a logical unit consisting of the assembly manifest, type metadata, IL code and set of resources like image files etc. - Windows Forms
This contains the graphical representation of any window displayed in the application. - ASP.Net and ASP.Net AJAX
ASP.Net is the web development model and AJAX is an extension of ASP.Net for developing and implementing AJAX functionality. ASP.Net AJAX contains the components that allow the developer to update data on a website without a complete reload of the page. - ADO.Net
It is the technology used for working with data and databases. It provides accesses to data sources like SQL server, OLE DB, XML etc. The ADO .Net allows connection to data sources for retrieving, manipulating and updating data. - Windows Workflow Foundation (WF)
It helps in building workflow based applications in Windows. It contains activities, workflow runtime, workflow designer and a rules engine. - Windows Presentation Foundation
It provides a separation between the user interface and the business logic. It helps in developing visually stunning interfaces using documents, media, two and three dimensional graphics, animations and more. - Windows Communication Foundation (WCF)
It is the technology used for building and running connected systems. - Windows CardSpace
It provides safety of accessing resources and sharing personal information on the internet. - LINQ
It imparts data querying capabilities to .Net languages using a syntax which is similar to the tradition query language SQL.
Nullable Types In C#
Nullable Types
Nullable types represent value-type variables that can be assigned the value of null.
Nullable types are declared in one of two ways:
System.Nullable<t> variable
-or-
T? variable
T is the underlying type of the nullable type. T can be any value type including struct; it cannot be a reference type.
In many programming applications, where there is database interactions, variables can exist in an undefined state. For example, a field in a database may contain the values true or false, but it may also contain no value at all. Similarly, reference types can be set to null to indicate that they are not initialized.
The nullable type modifier enables C# to create value-type variables that indicate an undefined value.
Example - Nullable Types
using System;
public struct Prime
{
public int PrimeNum;
public Prime(int num)
{
PrimeNum = num;
Console.WriteLine(num);
}
}
class PrimeNumbers
{
static void Main(string [] args)
{
Prime? objPrime = new Prime?(new Prime(5));
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace School
{
class nullType
{
static void Main(string[] args)
{
System.Nullable<int> numOne = 34;
System.Nullable<int> numTwo = null;
System.Nullable<int> res = numOne + numTwo;
if (res.HasValue == true)
Console.WriteLine(res);
else
Console.WriteLine("Result Null");
}
}
}
class ImplicitConversion
{
static void Main (string [] args)
{
int? numOne = null;
if (numOne.HasValue == true)
{
Console.WriteLine("Value of numOne before conversion: " + numOne);
}
else
{
Console.WriteLine ("Value of numOne: null");
}
numOne = 20;
Console.WriteLine("Value of numOne after implicit conversion: " + numOne);
}
}
class ExplicitConversion
{
static void Main (string [] args)
{
int? numOne = null;
int numTwo = 20;
int? resultOne = numOne + numTwo;
if (resultOne.HasValue == true)
{
Console.WriteLine("Value of numOne before conversion: " + resultOne);
}
else
{
Console.WriteLine ("Value of resultOne: null");
}
numOne = 10;
int result = (int) (numOne + numTwo);
Console.WriteLine("Value of result after explicit conversion: " + result);
}
}
class Boxing
{
static void Main (string [] args)
{
int? number = null;
object objOne = number;
if (objOne != null)
{
Console.WriteLine("Value of object one : " + objOne);
}
else
{
Console.WriteLine ("Value of object one: null");
}
double? value = 10.26;
object objTwo = value;
if (objTwo != null)
{
Console.WriteLine("Value of object two: " + objTwo);
}
else
{
Console.WriteLine("Value of object two: null");
}
}
}
Nullable types are declared in one of two ways:
System.Nullable<t> variable
-or-
T? variable
T is the underlying type of the nullable type. T can be any value type including struct; it cannot be a reference type.
In many programming applications, where there is database interactions, variables can exist in an undefined state. For example, a field in a database may contain the values true or false, but it may also contain no value at all. Similarly, reference types can be set to null to indicate that they are not initialized.
The nullable type modifier enables C# to create value-type variables that indicate an undefined value.
Example - Nullable Types
using System;
public struct Prime
{
public int PrimeNum;
public Prime(int num)
{
PrimeNum = num;
Console.WriteLine(num);
}
}
class PrimeNumbers
{
static void Main(string [] args)
{
Prime? objPrime = new Prime?(new Prime(5));
}
}
System.Nullable<>
using System;
using System.Collections.Generic;
using System.Text;
namespace School
{
class nullType
{
static void Main(string[] args)
{
System.Nullable<int> numOne = 34;
System.Nullable<int> numTwo = null;
System.Nullable<int> res = numOne + numTwo;
if (res.HasValue == true)
Console.WriteLine(res);
else
Console.WriteLine("Result Null");
}
}
}
Converting Nullable Types. Implicit Conversion
using System;class ImplicitConversion
{
static void Main (string [] args)
{
int? numOne = null;
if (numOne.HasValue == true)
{
Console.WriteLine("Value of numOne before conversion: " + numOne);
}
else
{
Console.WriteLine ("Value of numOne: null");
}
numOne = 20;
Console.WriteLine("Value of numOne after implicit conversion: " + numOne);
}
}
Converting Nullable Types : Explicity Conversion
using System;class ExplicitConversion
{
static void Main (string [] args)
{
int? numOne = null;
int numTwo = 20;
int? resultOne = numOne + numTwo;
if (resultOne.HasValue == true)
{
Console.WriteLine("Value of numOne before conversion: " + resultOne);
}
else
{
Console.WriteLine ("Value of resultOne: null");
}
numOne = 10;
int result = (int) (numOne + numTwo);
Console.WriteLine("Value of result after explicit conversion: " + result);
}
}
Boxing Nullable Types
using System;class Boxing
{
static void Main (string [] args)
{
int? number = null;
object objOne = number;
if (objOne != null)
{
Console.WriteLine("Value of object one : " + objOne);
}
else
{
Console.WriteLine ("Value of object one: null");
}
double? value = 10.26;
object objTwo = value;
if (objTwo != null)
{
Console.WriteLine("Value of object two: " + objTwo);
}
else
{
Console.WriteLine("Value of object two: null");
}
}
}
Asymmetric Accessor Accessibility
Accessors
The get and set portions of a property or indexer are called accessors. By default these accessors have the same visibility, or access level. However, it is sometimes useful to restrict access to one of these accessors. Typically, this involves restricting the accessibility of the set accessor, while keeping the get accessor publicly accessible. For example:
public string Name
{
get
{
return name;
}
protected set
{
name = value;
}
}
In this example, a property called Name defines a get and set accessor. The get accessor receives the accessibility level of the property itself, public in this case, while the set accessor is explicitly restricted by applying the protected access modifier to the accessor itself.
public string Name
{
get
{
return name;
}
protected set
{
name = value;
}
}
In this example, a property called Name defines a get and set accessor. The get accessor receives the accessibility level of the property itself, public in this case, while the set accessor is explicitly restricted by applying the protected access modifier to the accessor itself.
Properties And Indexers
PROPERTIES
Properties provide the opportunity to protect a field in a class by reading and writing to it through the property. C# properties enable this type of protection while also letting you access the property just like it was a field.
Another benefit of properties over fields is that you can change their internal implementation over time. With a public field, the underlying data type must always be the same because calling code depends on the field being the same. However, with a property, you can change the implementation. For example, if a customer has an ID that is originally stored as an int, you might have a requirements change that made you perform a validation to ensure that calling code could never set the ID to a negative value. If it was a field, you would never be able to do this, but a property allows you to make such a change without breaking code.
Another benefit of properties over fields is that you can change their internal implementation over time. With a public field, the underlying data type must always be the same because calling code depends on the field being the same. However, with a property, you can change the implementation. For example, if a customer has an ID that is originally stored as an int, you might have a requirements change that made you perform a validation to ensure that calling code could never set the ID to a negative value. If it was a field, you would never be able to do this, but a property allows you to make such a change without breaking code.
Defining property
using System;
class Employee
{
string _empName;
public string EmpName
{
get
{
return _empName;
}
set
{
_empName = value;
}
}
}
class SalaryDetails : Employee
{
static void Main(string [] args)
{
SalaryDetails obj = new SalaryDetails();
obj.EmpName = "Frank";
Console.WriteLine ("Name : " + obj.EmpName);
}
}
class Employee
{
string _empName;
public string EmpName
{
get
{
return _empName;
}
set
{
_empName = value;
}
}
}
class SalaryDetails : Employee
{
static void Main(string [] args)
{
SalaryDetails obj = new SalaryDetails();
obj.EmpName = "Frank";
Console.WriteLine ("Name : " + obj.EmpName);
}
}
Defining several Properties
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Employee
{
string _empName;
int _empID;
float _salary;
public string EmpName
{
get
{
return _empName;
}
set
{
_empName = value;
}
}
public int EmpID
{
get
{
return _empID;
}
set
{
_empID = value;
}
}
public float Salary
{
get
{
return _salary;
}
set
{
_salary = value;
}
}
}
class SalaryDetails : Employee
{
static void Main(string[] args)
{
SalaryDetails obj = new SalaryDetails();
obj.EmpName = "Frank";
obj.EmpID = 10;
obj.Salary = 1000.25F;
Console.WriteLine("Name : " + obj.EmpName);
Console.WriteLine("ID : " + obj.EmpID);
Console.WriteLine("Salary : " + obj.Salary + "$");
}
}
}
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Employee
{
string _empName;
int _empID;
float _salary;
public string EmpName
{
get
{
return _empName;
}
set
{
_empName = value;
}
}
public int EmpID
{
get
{
return _empID;
}
set
{
_empID = value;
}
}
public float Salary
{
get
{
return _salary;
}
set
{
_salary = value;
}
}
}
class SalaryDetails : Employee
{
static void Main(string[] args)
{
SalaryDetails obj = new SalaryDetails();
obj.EmpName = "Frank";
obj.EmpID = 10;
obj.Salary = 1000.25F;
Console.WriteLine("Name : " + obj.EmpName);
Console.WriteLine("ID : " + obj.EmpID);
Console.WriteLine("Salary : " + obj.Salary + "$");
}
}
}
ToString() property
using System;
public class Person
{
private string myName="N/A";
private int myAge = 0;
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}
public int Age
{
get
{
return myAge;
}
set
{
myAge = value;
}
}
public override string ToString()
{
return "Name: " + Name + " Age: " + Age;
}
public static void Main ()
{
Person obj = new Person();
Console.WriteLine("Person Details: {0}", obj);
obj.Name = "Delhi";
obj.Age = 100;
Console.WriteLine("Person Details: {0}", obj);
obj.Age += 1;
Console.WriteLine("Person Details: {0}", obj);
}
}
public class Person
{
private string myName="N/A";
private int myAge = 0;
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}
public int Age
{
get
{
return myAge;
}
set
{
myAge = value;
}
}
public override string ToString()
{
return "Name: " + Name + " Age: " + Age;
}
public static void Main ()
{
Person obj = new Person();
Console.WriteLine("Person Details: {0}", obj);
obj.Name = "Delhi";
obj.Age = 100;
Console.WriteLine("Person Details: {0}", obj);
obj.Age += 1;
Console.WriteLine("Person Details: {0}", obj);
}
}
Properties: Implementing Polymorphism
Example 1
using System;
class Car
{
string _carType;
public virtual string CarType
{
get
{
return _carType;
}
set
{
_carType = value;
}
}
}
class Ferrari : Car
{
public override string CarType
{
get
{
return base.CarType;
}
set
{
base.CarType = value;
}
}
static void Main(string [] args)
{
Car objCar = new Car();
objCar.CarType = "Utility Vehicle";
Ferrari objFerrari = new Ferrari();
objFerrari.CarType = "Sports Car";
Console.WriteLine("Car Type: " + objCar.CarType);
Console.WriteLine("Ferrari Car Type : " + objFerrari.CarType);
}
}
Example 2:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Car
{
string _carType; v public virtual string CarType
{
get
{
return _carType;
}
set
{
_carType = value;
}
}
}
class Ferrari : Car
{
string _carType;
public override string CarType
{
get
{
return base.CarType;
}
set
{
base.CarType = value;
Console.Write("Enter car Name: ");
_carType = Console.ReadLine();
}
}
static void Main(string[] args)
{
Car objCar = new Car();
objCar.CarType = "Utility Vehicle";
Ferrari objFerrari = new Ferrari();
objFerrari.CarType = "Sports Car";
Console.WriteLine("Car Type: " + objCar.CarType);
Console.WriteLine("Ferrari Car Type : " + objFerrari.CarType);
Console.WriteLine(objFerrari._carType);
}
}
}
using System;
class Car
{
string _carType;
public virtual string CarType
{
get
{
return _carType;
}
set
{
_carType = value;
}
}
}
class Ferrari : Car
{
public override string CarType
{
get
{
return base.CarType;
}
set
{
base.CarType = value;
}
}
static void Main(string [] args)
{
Car objCar = new Car();
objCar.CarType = "Utility Vehicle";
Ferrari objFerrari = new Ferrari();
objFerrari.CarType = "Sports Car";
Console.WriteLine("Car Type: " + objCar.CarType);
Console.WriteLine("Ferrari Car Type : " + objFerrari.CarType);
}
}
Example 2:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Car
{
string _carType; v public virtual string CarType
{
get
{
return _carType;
}
set
{
_carType = value;
}
}
}
class Ferrari : Car
{
string _carType;
public override string CarType
{
get
{
return base.CarType;
}
set
{
base.CarType = value;
Console.Write("Enter car Name: ");
_carType = Console.ReadLine();
}
}
static void Main(string[] args)
{
Car objCar = new Car();
objCar.CarType = "Utility Vehicle";
Ferrari objFerrari = new Ferrari();
objFerrari.CarType = "Sports Car";
Console.WriteLine("Car Type: " + objCar.CarType);
Console.WriteLine("Ferrari Car Type : " + objFerrari.CarType);
Console.WriteLine(objFerrari._carType);
}
}
}
Types of Properties
Read-Only Property
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Books
{
string _bookName;
long _bookID;
public Books(string name, int value)
{
_bookName = name;
_bookID = value;
}
public string BookName
{
get
{
return _bookName;
}
}
public long BookID
{
get
{
return _bookID;
}
}
public void show()
{
Console.WriteLine(BookID + " " + BookName );
}
}
class BookStore
{
static void Main(string[] args)
{
Books obj = new Books("Learn C# in 21 Days", 10015);
Console.WriteLine("Book Name: " + obj.BookName);
Console.WriteLine("Book ID: " + obj.BookID);
obj.show();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Books
{
string _bookName;
long _bookID;
public Books(string name, int value)
{
_bookName = name;
_bookID = value;
}
public string BookName
{
get
{
return _bookName;
}
}
public long BookID
{
get
{
return _bookID;
}
}
public void show()
{
Console.WriteLine(BookID + " " + BookName );
}
}
class BookStore
{
static void Main(string[] args)
{
Books obj = new Books("Learn C# in 21 Days", 10015);
Console.WriteLine("Book Name: " + obj.BookName);
Console.WriteLine("Book ID: " + obj.BookID);
obj.show();
}
}
}
Write-Only Property
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Department
{
string _deptName;
int _deptID;
public string DeptName
{
set
{
_deptName = value;
}
}
public int DeptID
{
set
{
_deptID = value;
}
}
public void Display()
{
Console.WriteLine("Department Name: " + _deptName);
Console.WriteLine("Department ID: " + _deptID);
}
}
class Company
{
static void Main(string[] args)
{
Department obj = new Department();
obj.DeptID = 201;
obj.DeptName = "Sales";
obj.Display();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Department
{
string _deptName;
int _deptID;
public string DeptName
{
set
{
_deptName = value;
}
}
public int DeptID
{
set
{
_deptID = value;
}
}
public void Display()
{
Console.WriteLine("Department Name: " + _deptName);
Console.WriteLine("Department ID: " + _deptID);
}
}
class Company
{
static void Main(string[] args)
{
Department obj = new Department();
obj.DeptID = 201;
obj.DeptName = "Sales";
obj.Display();
}
}
}
Read-Write Property
using System;
namespace ConsoleApplication5
{
class Product
{
string _productName;
int _productID;
float _price;
public Product(string name, int val)
{
_productName = name;
_productID = val;
}
public float Price
{
get
{
return _price;
}
set
{
if (value < 0) { _price = 0; } else { _price = value; } } } public void Display() { Console.WriteLine("Product Name: " + _productName); Console.WriteLine("Product ID: " + _productID); Console.WriteLine("Price: " + _price + "$"); } } class Goods { static void Main(string[] args) { Product obj = new Product("Hard Disk", 101); obj.Price = 345.25F; obj.Display(); } } }
namespace ConsoleApplication5
{
class Product
{
string _productName;
int _productID;
float _price;
public Product(string name, int val)
{
_productName = name;
_productID = val;
}
public float Price
{
get
{
return _price;
}
set
{
if (value < 0) { _price = 0; } else { _price = value; } } } public void Display() { Console.WriteLine("Product Name: " + _productName); Console.WriteLine("Product ID: " + _productID); Console.WriteLine("Price: " + _price + "$"); } } class Goods { static void Main(string[] args) { Product obj = new Product("Hard Disk", 101); obj.Price = 345.25F; obj.Display(); } } }
Static Properties
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class University
{
private static string _department;
private static string _universityName;
public static string Department
{
get
{
return _department;
}
set
{
_department = value;
}
}
public static string UniversityName
{
get
{
return _universityName;
}
set
{
_universityName = value;
}
}
}
class Physics
{
static void Main(string[] args)
{
University.UniversityName = "University of MaryLand";
University.Department = "Physics";
Console.WriteLine("University Name: " + University.UniversityName);
Console.WriteLine("Department Name: " + University.Department);
}
}
}
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class University
{
private static string _department;
private static string _universityName;
public static string Department
{
get
{
return _department;
}
set
{
_department = value;
}
}
public static string UniversityName
{
get
{
return _universityName;
}
set
{
_universityName = value;
}
}
}
class Physics
{
static void Main(string[] args)
{
University.UniversityName = "University of MaryLand";
University.Department = "Physics";
Console.WriteLine("University Name: " + University.UniversityName);
Console.WriteLine("Department Name: " + University.Department);
}
}
}
Abstract properties
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
{
public abstract class Figure
{
public abstract float DimensionOne
{
set;
}
public abstract float DimensionTwo
{
set;
}
}
class Rectangle : Figure
{
float _dimensionOne;
float _dimensionTwo;
public override float DimensionOne
{
set
{
if (value <= 0) { _dimensionOne = 0; } else { _dimensionOne = value; } } } public override float DimensionTwo { set { if (value <= 0) { _dimensionTwo = 0; } else { _dimensionTwo = value; } } } float Area() { return _dimensionOne * _dimensionTwo; } static void Main(string[] args) { Rectangle obj = new Rectangle(); obj.DimensionOne = 4; obj.DimensionTwo = 8; Console.WriteLine("Area of Rectangle : " + obj.Area()); } } }
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
{
public abstract class Figure
{
public abstract float DimensionOne
{
set;
}
public abstract float DimensionTwo
{
set;
}
}
class Rectangle : Figure
{
float _dimensionOne;
float _dimensionTwo;
public override float DimensionOne
{
set
{
if (value <= 0) { _dimensionOne = 0; } else { _dimensionOne = value; } } } public override float DimensionTwo { set { if (value <= 0) { _dimensionTwo = 0; } else { _dimensionTwo = value; } } } float Area() { return _dimensionOne * _dimensionTwo; } static void Main(string[] args) { Rectangle obj = new Rectangle(); obj.DimensionOne = 4; obj.DimensionTwo = 8; Console.WriteLine("Area of Rectangle : " + obj.Area()); } } }
INDEXERS
Indexers are an elaboration of properties, and are used where you want to access some class property by index, in an array like manner. They are useful in cases where a class is a container for other objects.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Salary
{
private float[] salary = new float[3];
public float this[int index]
{
get
{
return salary[index];
}
set
{
if (value < 0) { Console.WriteLine("Salary cannot be negetive."); return; } else { salary[index] = value; } } } static void Main(string[] args) { Salary obj = new Salary(); obj[0] = 1000F; obj[1] = 2000F; obj[2] = 3000F; Console.WriteLine("Salary Details"); for (int i = 0; i < 3; i++) { Console.WriteLine(obj[i] + "$"); } } } } Example 2 using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public class IndexTest
{
double[] values;
public IndexTest()
{
values = new double[] { 1.1, 3.3, 5.5, 7.7, 9.9 };
}
public double this[int index]
{
get
{
if (index < 0 || index > values.Length)
throw new ArgumentOutOfRangeException();
return values[index];
}
set
{
values[index] = value;
}
}
}
public class test
{
public static int Main()
{
IndexTest it = new IndexTest();
Console.WriteLine("Index 1 is: " + it[4]);
return 0;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Salary
{
private float[] salary = new float[3];
public float this[int index]
{
get
{
return salary[index];
}
set
{
if (value < 0) { Console.WriteLine("Salary cannot be negetive."); return; } else { salary[index] = value; } } } static void Main(string[] args) { Salary obj = new Salary(); obj[0] = 1000F; obj[1] = 2000F; obj[2] = 3000F; Console.WriteLine("Salary Details"); for (int i = 0; i < 3; i++) { Console.WriteLine(obj[i] + "$"); } } } } Example 2 using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public class IndexTest
{
double[] values;
public IndexTest()
{
values = new double[] { 1.1, 3.3, 5.5, 7.7, 9.9 };
}
public double this[int index]
{
get
{
if (index < 0 || index > values.Length)
throw new ArgumentOutOfRangeException();
return values[index];
}
set
{
values[index] = value;
}
}
}
public class test
{
public static int Main()
{
IndexTest it = new IndexTest();
Console.WriteLine("Index 1 is: " + it[4]);
return 0;
}
}
}
Indexer - Inheritance
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Numbers
{
private int[] num = new int[3];
public int this[int index]
{
get
{
return num[index];
}
set
{
num[index] = value;
}
}
}
class EvenNumbers : Numbers
{
public static void Main()
{
EvenNumbers obj = new EvenNumbers();
obj[0] = 0;
obj[1] = 2;
obj[2] = 4;
for (int i = 0; i < 3; i++) { Console.WriteLine(obj[i]); } } } }
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Numbers
{
private int[] num = new int[3];
public int this[int index]
{
get
{
return num[index];
}
set
{
num[index] = value;
}
}
}
class EvenNumbers : Numbers
{
public static void Main()
{
EvenNumbers obj = new EvenNumbers();
obj[0] = 0;
obj[1] = 2;
obj[2] = 4;
for (int i = 0; i < 3; i++) { Console.WriteLine(obj[i]); } } } }
Indexer - Polymorphism
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Student
{
string[] studName = new string[2];
public virtual string this[int index]
{
get
{
return studName[index];
}
set
{
studName[index] = value;
}
}
}
class Result : Student
{
string[] result = new string[2];
public override string this[int index]
{
get
{
return base[index];
}
set
{
base[index] = value;
}
}
public static void Main(string[] args)
{
Result objResult = new Result();
objResult[0] = "First";
objResult[1] = "Pass";
Student objStu = new Student();
objStu[0] = "Peter";
objStu[1] = "Patrick";
for (int i = 0; i < 2; i++) { Console.WriteLine(objStu[i] + "\t\t" + objResult[i] + "class"); } } } }
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Student
{
string[] studName = new string[2];
public virtual string this[int index]
{
get
{
return studName[index];
}
set
{
studName[index] = value;
}
}
}
class Result : Student
{
string[] result = new string[2];
public override string this[int index]
{
get
{
return base[index];
}
set
{
base[index] = value;
}
}
public static void Main(string[] args)
{
Result objResult = new Result();
objResult[0] = "First";
objResult[1] = "Pass";
Student objStu = new Student();
objStu[0] = "Peter";
objStu[1] = "Patrick";
for (int i = 0; i < 2; i++) { Console.WriteLine(objStu[i] + "\t\t" + objResult[i] + "class"); } } } }
Multiple parameters in Indexers
using System;
class Account
{
string[,] accountDetails = new string[4, 2];
public string this[int pos, int column]
{
get
{
return (accountDetails[pos, column]);
}
set
{
accountDetails[pos, column] = value;
}
}
public static void Main(string[] args)
{
Account obj = new Account();
obj[0,0] = "aptech";
Console.WriteLine(obj[0, 0]);
}
}
class Account
{
string[,] accountDetails = new string[4, 2];
public string this[int pos, int column]
{
get
{
return (accountDetails[pos, column]);
}
set
{
accountDetails[pos, column] = value;
}
}
public static void Main(string[] args)
{
Account obj = new Account();
obj[0,0] = "aptech";
Console.WriteLine(obj[0, 0]);
}
}
Indexers in Interfaces
using System;
public interface IDetails
{
string this [int index ]
{
get;
set;
}
}
class Students : IDetails
{
string [] studentName = new string[3];
//int [] studentID = new int[3];
public string this [int index]
{
get
{
return studentName[index];
}
set
{
studentName[index] = value;
}
}
public static void Main(string [] args)
{
Students obj = new Students();
obj [0] = "James";
obj [1] = "Wilson";
obj [2] = "Patrick";
Console.WriteLine("Student Names:");
Console.WriteLine();
for(int i=0; i<3; i++) { Console.Write (obj[i] + " "); } } }
public interface IDetails
{
string this [int index ]
{
get;
set;
}
}
class Students : IDetails
{
string [] studentName = new string[3];
//int [] studentID = new int[3];
public string this [int index]
{
get
{
return studentName[index];
}
set
{
studentName[index] = value;
}
}
public static void Main(string [] args)
{
Students obj = new Students();
obj [0] = "James";
obj [1] = "Wilson";
obj [2] = "Patrick";
Console.WriteLine("Student Names:");
Console.WriteLine();
for(int i=0; i<3; i++) { Console.Write (obj[i] + " "); } } }
Common Type System (CTS)
Common Type System (CTS) In .NET
Common Type System (CTS) describes a set of types that can be used in different .Net languages in common . That is , the Common Type System (CTS) ensure that objects written in different .Net languages can interact with each other. For Communicating between programs written in any .NET complaint language, the types have to be compatible on the basic level.
These types can be Value Types or Reference Types . The Value Types are passed by values and stored in the stack. The Reference Types are passed by references and stored in the heap. Common Type System (CTS) provides base set of Data Types which is responsible for cross language integration. The Common Language Runtime (CLR) can load and execute the source code written in any .Net language, only if the type is described in the Common Type System (CTS) .Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types.
These types can be Value Types or Reference Types . The Value Types are passed by values and stored in the stack. The Reference Types are passed by references and stored in the heap. Common Type System (CTS) provides base set of Data Types which is responsible for cross language integration. The Common Language Runtime (CLR) can load and execute the source code written in any .Net language, only if the type is described in the Common Type System (CTS) .Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types.
Common Language Specification (CLS) In .NET
Common Language Specification (CLS)
Common Language Specification (CLS) is a set of basic language features that .Net Languages needed to develop Applications and Services , which are compatible with the .Net Framework. When there is a situation to communicate Objects written in different .Net Complaint languages , those objects must expose the features that are common to all the languages . Common Language Specification (CLS) ensures complete interoperability among applications, regardless of the language used to create the application.
Common Language Specification (CLS) defines a subset of Common Type System (CTS) . Common Type System (CTS) describes a set of types that can use different .Net languages have in common , which ensure that objects written in different languages can interact with each other. Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types. Moreover Common Language Specification (CLS) are standardized by ECMA (European Computer Manufacturers Association).
Common Language Specification (CLS) defines a subset of Common Type System (CTS) . Common Type System (CTS) describes a set of types that can use different .Net languages have in common , which ensure that objects written in different languages can interact with each other. Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types. Moreover Common Language Specification (CLS) are standardized by ECMA (European Computer Manufacturers Association).
Thursday, 26 July 2012
Inheritance in C#
class Animal
{
public Animal()
{
Console.WriteLine("Animal constructor");
}
public void Greet()
{
Console.WriteLine("Animal says Hello");
}
public void Talk()
{
Console.WriteLine("Animal talk");
}
public virtual void
Sing()
{
Console.WriteLine("Animal song");
}
};
class Dog : Animal
{
public Dog()
{
Console.WriteLine("Dog
constructor");
}
public new void
Talk()
{
Console.WriteLine("Dog talk");
}
public override void
Sing()
{
Console.WriteLine("Dog song");
}
};
Animal a1 = new Animal();
a1.Talk();
a1.Sing();
a1.Greet();
Dog d1 = new Dog();
d1.Talk();
d1.Sing();
d1.Greet();
class Color
{
public virtual void
Fill()
{
Console.WriteLine("Fill me up with
color");
}
public void Fill(string s)
{
Console.WriteLine("Fill me up with {0}",s);
}
};
Color c1 = new Color();
c1.Fill();
c1.Fill("red");
class Green : Color
{
public override void
Fill()
{
Console.WriteLine("Fill me up with green");
}
};
Green g1 = new Green();
g1.Fill();
g1.Fill("violet");
//Output
Fill me up with green
Fill me up with violet
class Software
{
public Software()
{
m_x = 100;
}
public Software(int y)
{
m_x = y;
}
protected int m_x;
};
class MicrosoftSoftware : Software
{
public MicrosoftSoftware()
{
Console.WriteLine(m_x);
}
};
MicrosoftSoftware m1 = new MicrosoftSoftware();
class DundasSoftware : Software
{
public DundasSoftware(int y) : base(y)
{
Console.WriteLine(m_x);
}
//Here we are telling the
compiler to first
//call the other overload
of the constructor
public DundasSoftware(string s, int f) : this(f)
{
Console.WriteLine(s);
}
};
Subscribe to:
Posts (Atom)