Operator overloading in C#.NET
The operators available in C# will work only on
standard data types like int, float and string. But not on user defined types
like class and structure. Making an operator work on user defined type like
class is called as operator overloading. To overload an operator, you have to
create an operator method in the class. Operator methods are created using the
keyword operator and they must be public and static.
Public static returntype operator #([Parameters])
{
}
Example : The following example creates a class Complex
that represents a complex number and overload the + operator to perform
addition of two complex objects using +.
namespace Inheritance
{
class Complex
{
float R, I;
public void Read()
{
Console.Write("Enter Imaginary
: ");
I = float.Parse(Console.ReadLine());
Console.Write("Enter Real :
");
R = float.Parse(Console.ReadLine());
}
public void Print()
{
Console.WriteLine("{0}i + {1}", I, R);
}
public static Complex operator +(Complex C1, Complex C2)
{
Complex T = new Complex();
T.I = C1.I + C2.I;
T.R = C1.R + C2.R;
return T;
}
}
class PlusOL
{
static void Main()
{
Complex C1 = new Complex();
Complex C2 = new Complex();
Complex C3;
C1.Read();
C2.Read();
C3 = C1 + C2;
Console.Clear();
C1.Print();
C2.Print();
Console.WriteLine("----------------");
C3.Print();
}
}
}
The following is the list of operators that can be overloaded and that can’t be overloaded.
Operators |
Overloadability |
+, -, *,
/, %, &, |, <<, >> |
All C# binary operators can be overloaded. |
+, -, !,
~, ++, --, true, false |
All C# unary operators can be overloaded. |
==, !=, <, >, <= , >= |
All relational operators can be overloaded, but only as
pairs. |
&&, || |
They can’t Be Overloaded |
() , (Conversion operator) |
They can’t Be Overloaded |
+=, -=, *=, /=, %= |
These compound assignment operators can be overloaded. But
in C#, these operators are automatically overloaded when the respective
binary operator is overloaded. |
=, . , ?:, ->, new, is, as,
sizeof |
They can’t Be Overloaded |
Partial class is a new
concept in .net 2.0. A partial class is a class whose definition is divided in
to more than one file. For example in windows application a windows form is
divided in to two files, a file with extension .cs that
contain the business logic and a file with extension .designer.cs that
contains the design related code. In the same way in ASP.net, a web
page is divided in to two files, a file with extension .Aspx that
contain the design related code and a file with extension .Aspx.cs that
contains the business logic. This is also possible only with partial classes. When
you have to divide a class into more than one file, then use partial classes.
To create a class as partial class, use the keyword partial while
creating the class. While creating the class as partial class, consider the
following points.
In every file class must be created with same name.
In every file class must
be created with the keyword partial.
In every file class must
be created with same access modifier.
Example : The following example creates a console application in C# that contains two files program.cs and class1.cs where a class Test is divided in to these two files.
Create a console application and write the following code within the file Program.cs
namespace PartialClasses
{
partial class Test
{
public void M1()
{
Console.WriteLine("M1 From
Program.Cs");
}
}
class Program
{
static void Main(string[] args)
{
Test T = new Test();
T.M1();
T.M2();
}
}
}
This will cause error at the statement T.M2. because the class Test Doesn’t contain a method with the name M2.
Add another class to the
project with the name Class1.cs and write the following code in it.
namespace PartialClasses
{
partial class Test
{
public void M2()
{
Console.WriteLine("M2 From
Class1.Cs");
}
}
class Class1
{
}
}
Now the error at the statement T.M2 will be removed in the file program.cs as now the class Test contains the method M2 within the file class1.cs
Nullable Types
Nullable type is another new concept in .net 2.0. A nullable type is a value type that can store null value along with the valid range of values for its data type. A value type variable in .net can store only the valid range of values for its data type and it can’t store null. But when you are working with databases like SQL server or Oracle and the data retrieved from table is stored in to variables that are of value type then if retrieved data contains null then an error will occur. A solution for this problem is nullable types. For declaring a variable as nullable type, suffix the data type in declaration with “?” or use the generic class Nullable.
DataType? Var;
Nullable<datatype> Var;
The following example declares the variable B as nullable type of byte.
Byte? B;
Nullable<Byte> B;
When a variable is declared as nullable type, then that variable will have a property called HasValue. This property can be used to determine whether nullable type contains a value or null. If this property contains the true then the variable contains a value and when it contains false then the variable contains null.
Example : The following example creates a variable B as nullable type of byte.
namespace NullableTypes
{
class Program
{
static void Main(string[] args)
{
byte? B;
B = null;
if (B.HasValue)
Console.WriteLine("Value Of B Is
{0}", B);
else
Console.WriteLine("B Has NULL");
}
}
}
Value Types And
Reference Types
All the data types in .net are classified in to value types and reference types. The data types whose values are directly stored in variable in stack memory area are called as value types and the data types whose values are stored in heap memory area and its address is stored in the variable in stack memory area are called as reference types. Among all built in data types of .net string and object are reference type and all remaining data types are value types. Among user defined data types, class, interface, delegate and arrays are reference type while structure and enumeration are value type.
Boxing And Unboxing
Converting value type to
reference type is called boxing and converting reference type to value type is
called as unboxing. Boxing and unboxing are only the technical terms for type
casting from value type to reference type and vice versa and there is no special
concept related to this. Access to value types will be fast when compared to
reference types. Because they directly contain the value and no need to refer
another memory location. It is recommended to avoid boxing and unboxing in the
program wherever it is possible. Because these operations take time and will
affect the performance of the application.
Using statements in C#.NET
Using statements are used to add the reference to a namespace
available in a class library to use all classes, structures and enumerations
available in that namespace in your application. This is similar to #include statement
in C language used to add the reference to a header file to use library
functions available in that header file in the program.
Structures in C#.NET
A structure is a user
defined data type that can store more than one value of dissimilar types. To
create a structure struct keyword is used and has the
following syntax.
[Access Modifier] struct structname
{
---
}
A structure is value
type and can contain variable and functions. Variable are used to store data
and functions are used to specify various operations that can be performed on
data. To use a structure you must first create a variable of the structure and
has the following syntax.
[Access
Modifier] StructureName Var = new StructureName;
After creating a
variable for the structure you can access its members by using .(dot) operator.
Example : The following example creates a structure for
storing student data and read and print a student details.
namespace Language
{
class Structure
{
struct Student
{
int Sid;
string Sname, Course;
public void Read()
{
Console.Write("Enter Student Id
: ");
Sid = int.Parse(Console.ReadLine());
Console.Write("Enter Student
Name : ");
Sname = Console.ReadLine();
Console.Write("Enter Course :
");
Course = Console.ReadLine();
}
public void Print()
{
Console.WriteLine("{0}\t{1}\t{2}", Sid, Sname, Course);
}
}
static void Main()
{
Student S = new Student();
S.Read();
S.Print();
}
}
}
Enumerations in C#.NET
An enumeration is a user
defined type that restricts the user from assigning only a specified list of
values to a variable. Enumeration is also a value type and to create an
enumeration keyword enum is used and has the following syntax.
[Access
Modifier] enum EnumName
{
---
}
To use an enumeration
first you have to create a variable for the enumeration using following syntax.
[Access
Modifier] EnumName Var;
Example : The following example creates an enumeration with week names as its list
Write program to illustrate Enumerations in C#.NET
namespace Language
{
class Enumeration
{
enum Weeks
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
static void Main()
{
Weeks W = Weeks.Thursday;
Console.WriteLine(W);
Console.WriteLine((int)W);
}
}
}
Within the enumeration for every constant a numeric value will be automatically given starting from 0(Zero). You can also provide your own values for the constants in enumeration and they may not be in a sequenece
For Part4 Click here
No comments:
Post a Comment