Operators, Types, and Variables
This lesson introduces C# operators, types, and variables. Its goal is to meet the following objectives:
Understand what a variable is.
Familiarization with C# built-in types.
Get an introduction to C# operators.
Learn how to use Arrays.
Variables and Types
"Variables" are simply storage locations for data. You can place data into them and retrieve their contents as part of a C# expression. The interpretation of the data in a variable is controlled through "Types".
C# is a "Strongly Typed" language. Thus all operations on variables are performed with consideration of what the variable's "Type" is. There are rules that define what operations are legal in order to maintain the integrity of the data you put in a variable.
The C# simple types consist of the Boolean type and three numeric types - Integrals, Floating Point, Decimal, and String. The term "Integrals", which is defined in the C# Programming Language Specification, refers to the classification of types that include sbyte, byte, short, ushort, int, uint, long, ulong, and char. The term "Floating Point" refers to the float and double types, which are discussed, along with the decimal type, in more detail in the Floating Point and Decimal Types section later in this lesson. The string type represents a string of characters and is discussed in The String Type section, later in this lesson. The next section introduces the boolean type.
The Boolean Type
Boolean types are declared using the keyword, bool. They have two values: true or false. In other languages, such as C and C++, boolean conditions can be satisfied where 0 means false and anything else means true. However, in C# the only values that satisfy a boolean condition is true and false, which are official keywords. Listing 2-1 shows one of many ways that boolean types can be used in a program.
Listing 2-1. Displaying Boolean Values: Boolean.cs
using System;
class Booleans
{
public static void Main()
{
bool content = true;
bool noContent = false;
Console.WriteLine("It is {0} that C# Station provides C# programming language content.", content);
Console.WriteLine("The statement above is not {0}.", noContent);
}
}
In Listing 2-1, the boolean values are written to the console as a part of a sentence. The only legal values for the bool type are either true or false, as shown by the assignment of true to content and false to noContent. When run, this program produces the following output:
It is True that C# Station provides C# programming language content.
The statement above is not False.
Integral Types
In C#, an integral is a category of types. For anyone confused because the word Integral sounds like a mathematical term, from the perspective of C# programming, these are actually defined as Integral types in the C# programming language specification. They are whole numbers, either signed or unsigned, and the char type. The char type is a Unicode character, as defined by the Unicode Standard. For more information, visit The Unicode Home Page. table 2-1 shows the integral types, their size, and range.
Table 2-1. The Size and Range of C# Integral Types
Type Size (in bits) Range
sbyte 8 -128 to 127
byte 8 0 to 255
short 16 -32768 to 32767
ushort 16 0 to 65535
int 32 -2147483648 to 2147483647
uint 32 0 to 4294967295
long 64 -9223372036854775808 to 9223372036854775807
ulong 64 0 to 18446744073709551615
char 16 0 to 65535
Integral types are well suited for those operations involving whole number calculations. The char type is the exception, representing a single Unicode character. As you can see from the table above, you have a wide range of options to choose from, depending on your requirements.
Floating Point and Decimal Types
A C# floating point type is either a float or double. They are used any time you need to represent a real number, as defined by IEEE 754. For more information on IEEE 754, visit the IEEE Web Site. Decimal types should be used when representing financial or money values. table 2-2 shows the floating point and decimal types, their size, precision, and range.
Table 2-2. The Floating Point and Decimal Types with Size, precision, and Range
Type Size (in bits) precision Range
float 32 7 digits 1.5 x 10-45 to 3.4 x 1038
double 64 15-16 digits 5.0 x 10-324 to 1.7 x 10308
decimal 128 28-29 decimal places 1.0 x 10-28 to 7.9 x 1028
Floating point types are used when you need to perform operations requiring fractional representations. However, for financial calculations, the decimal type is the best choice because you can avoid rounding errors.
The string Type
A string is a sequence of text characters. You typically create a string with a string literal, enclosed in quotes: "This is an example of a string." You've seen strings being used in Lesson 1, where we used the Console.WriteLine method to send output to the console.
Some characters aren't printable, but you still need to use them in strings. Therefore, C# has a special syntax where characters can be escaped to represent non-printable characters. For example, it is common to use newlines in text, which is represented by the '\n' char. The backslash, '\', represents the escape. When preceded by the escape character, the 'n' is no longer interpreted as an alphabetical character, but now represents a newline.
You may be now wondering how you could represent a backslash character in your code. We have to escape that too by typing two backslashes, as in '\\'. table 2-3 shows a list of common escape sequences.
Table 2-3. C# Character Escape Sequences
Escape Sequence Meaning
\' Single Quote
\" Double Quote
\\ Backslash
\0 Null, not the same as the C# null value
\a Bell
\b Backspace
\f form Feed
\n Newline
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab
Another useful feature of C# strings is the verbatim literal, which is a string with a @ symbol prefix, as in @"Some string". Verbatim literals make escape sequences translate as normal characters to enhance readability. To appreciate the value of verbatim literals, consider a path statement such as "c:\\topdir\\subdir\\subdir\\myapp.exe". As you can see, the backslashes are escaped, causing the string to be less readable. You can improve the string with a verbatim literal, like this: @"c:\topdir\subdir\subdir\myapp.exe".
That is fine, but now you have the problem where quoting text is not as easy. In that case, you would specify double double quotes. For example, the string "copy \"c:\\source file name with spaces.txt\" c:\\newfilename.txt" would be written as the verbatim literal @"copy ""c:\source file name with spaces.txt"" c:\newfilename.txt".
C# Operators
Results are computed by building expressions. These expressions are built by combining variables and operators together into statements. The following table describes the allowable operators, their precedence, and associativity.
Table 2-4. Operators with their precedence and Associativity
Category (by precedence) Operator(s) Associativity
Primary x.y f(x) a[x] x++ x-- new typeof default checked unchecked delegate left
Unary + - ! ~ ++x --x (T)x left
Multiplicative * / % left
Additive + - left
Shift << >> left
Relational < > <= >= is as left
Equality == != right
Logical AND & left
Logical XOR ^ left
Logical OR | left
Conditional AND && left
Conditional OR || left
Null Coalescing ?? left
Ternary ?: right
Assignment = *= /= %= += -= <<= >>= &= ^= |= => right
Left associativity means that operations are evaluated from left to right. Right associativity mean all operations occur from right to left, such as assignment operators where everything to the right is evaluated before the result is placed into the variable on the left.
Most operators are either unary or binary. Unary operators form expressions on a single variable, but binary operators form expressions with two variables. Listing 2-2 demonstrates how unary operators are used.
Listing 2-2. Unary Operators: Unary.cs
using System;
class Unary
{
public static void Main()
{
int unary = 0;
int preIncrement;
int preDecrement;
int postIncrement;
int postDecrement;
int positive;
int negative;
sbyte bitNot;
bool logNot;
preIncrement = ++unary;
Console.WriteLine("pre-Increment: {0}", preIncrement);
preDecrement = --unary;
Console.WriteLine("pre-Decrement: {0}", preDecrement);
postDecrement = unary--;
Console.WriteLine("Post-Decrement: {0}", postDecrement);
postIncrement = unary++;
Console.WriteLine("Post-Increment: {0}", postIncrement);
Console.WriteLine("Final Value of Unary: {0}", unary);
positive = -postIncrement;
Console.WriteLine("Positive: {0}", positive);
negative = +postIncrement;
Console.WriteLine("Negative: {0}", negative);
bitNot = 0;
bitNot = (sbyte)(~bitNot);
Console.WriteLine("Bitwise Not: {0}", bitNot);
logNot = false;
logNot = !logNot;
Console.WriteLine("Logical Not: {0}", logNot);
}
}
When evaluating expressions, post-increment (x++) and post-decrement (x--) operators return their current value and then apply the operators. However, when using pre-increment (++x) and pre-decrement (--x) operators, the operator is applied to the variable prior to returning the final value.
In Listing 2-2, the unary variable is initialized to zero. When the pre-increment (++x) operator is used, unary is incremented to 1 and the value 1 is assigned to the preIncrement variable. The pre-decrement (--x) operator turns unary back to a 0 and then assigns the value to the preDecrement variable.
When the post-decrement (x--) operator is used, the value of unary, 0, is placed into the postDecrement variable and then unary is decremented to -1. Next the post-increment (x++) operator moves the current value of unary, -1, to the postIncrement variable and then increments unary to 0.
The variable bitNot is initialized to 0 and the bitwise not (~) operator is applied. The bitwise not (~) operator flips the bits in the variable. In this case, the binary representation of 0, "00000000", was transformed into -1, "11111111".
While the (~) operator works by flipping bits, the logical negation operator (!) is a logical operator that works on bool values, changing true to false or false to true. In the case of the logNot variable in Listing 2-2, the value is initialized to false, and the next line applies the logical negation operator, (!), which returns true and reassigns the new value, true, to logNot. Essentially, it is toggling the value of the bool variable, logNot.
The setting of positive is a little tricky. At the time that it is set, the postIncrement variable is equal to -1. Applying the minus (-) operator to a negative number results in a positive number, meaning that postitive will equal 1, instead of -1. The minus operator (-), which is not the same as the pre-decrement operator (--), doesn't change the value of postInc - it just applies a sign negation. The plus operator (+) doesn't affect the value of a number, assigning negative with the same value as postIncrement, -1.
Notice the expression (sbyte)(~bitNot). Any operation performed on types sbyte, byte, short, or ushort return int values. To assign the result into the bitNot variable we had to use a cast, (Type), operator, where Type is the type you wish to convert to (in this case - sbyte). The cast operator is shown as the Unary operator, (T)x, in table 2-4. Cast operators must be performed explicity when you go from a larger type to a smaller type because of the potential for lost data. Generally speaking, assigning a smaller type to a larger type is no problem, since the larger type has room to hold the entire value. Also be aware of the dangers of casting between signed and unsigned types. You want to be sure to preserve the integrity of your data. Many basic programming texts contain good descriptions of bit representations of variables and the dangers of explicit casting.
Here's the output from the Listing 2-2:
pre-Increment: 1
pre-Decrement 0
Post-Decrement: 0
Post-Increment: -1
Final Value of Unary: 0
Positive: 1
Negative: -1
Bitwise Not: -1
Logical Not: true
In addition to unary operators, C# has binary operators that form expressions of two variables. Listing 2-3 shows how to use the binary operators.
Listing 2-3. Binary Operators: Binary.cs
using System;
class Binary
{
public static void Main()
{
int x, y, result;
float floatresult;
x = 7;
y = 5;
result = x+y;
Console.WriteLine("x+y: {0}", result);
result = x-y;
Console.WriteLine("x-y: {0}", result);
result = x*y;
Console.WriteLine("x*y: {0}", result);
result = x/y;
Console.WriteLine("x/y: {0}", result);
floatresult = (float)x/(float)y;
Console.WriteLine("x/y: {0}", floatresult);
result = x%y;
Console.WriteLine("x%y: {0}", result);
result += x;
Console.WriteLine("result+=x: {0}", result);
}
}
And here's the output:
x+y: 12
x-y: 2
x*y: 35
x/y: 1
x/y: 1.4
x%y: 2
result+=x: 9
Listing 2-3 shows several examples of binary operators. As you might expect, the results of addition (+), subtraction (-), multiplication (*), and division (/) produce the expected mathematical results.
The floatresult variable is a floating point type. We explicitly cast the integer variables x and y to calculate a floating point value.
There is also an example of the remainder(%) operator. It performs a division operation on two values and returns the remainder.
The last statement shows another form of the assignment with operation (+=) operator. Any time you use the assignment with operation operator, it is the same as applying the binary operator to both the left hand and right hand sides of the operator and putting the results into the left hand side. The example could have been written as result = result + x; and returned the same value.
The Array Type
Another data type is the Array, which can be thought of as a container that has a list of storage locations for a specified type. When declaring an Array, specify the type, name, dimensions, and size.
Listing 2-4. Array Operations: Array.cs
using System;
class Array
{
public static void Main()
{
int[] myInts = { 5, 10, 15 };
bool[][] myBools = new bool[2][];
myBools[0] = new bool[2];
myBools[1] = new bool[1];
double[,] myDoubles = new double[2, 2];
string[] myStrings = new string[3];
Console.WriteLine("myInts[0]: {0}, myInts[1]: {1}, myInts[2]: {2}", myInts[0], myInts[1], myInts[2]);
myBools[0][0] = true;
myBools[0][1] = false;
myBools[1][0] = true;
Console.WriteLine("myBools[0][0]: {0}, myBools[1][0]: {1}", myBools[0][0], myBools[1][0]);
myDoubles[0, 0] = 3.147;
myDoubles[0, 1] = 7.157;
myDoubles[1, 1] = 2.117;
myDoubles[1, 0] = 56.00138917;
Console.WriteLine("myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}", myDoubles[0, 0], myDoubles[1, 0]);
myStrings[0] = "Joe";
myStrings[1] = "Matt";
myStrings[2] = "Robert";
Console.WriteLine("myStrings[0]: {0}, myStrings[1]: {1}, myStrings[2]: {2}", myStrings[0], myStrings[1], myStrings[2]);
}
}
And here's the output:
myInts[0]: 5, myInts[1]: 10, myInts[2]: 15
myBools[0][0]: true, myBools[1][0]: true
myDoubles[0, 0]: 3.147, myDoubles[1, 0]: 56.00138917
myStrings[0]: Joe, myStrings[1]: Matt, myStrings[2]: Robert
Listing 2-4 shows different implementations of Arrays. The first example is the myInts Array, which is a single-dimension array. It is initialized at declaration time with explicit values.
Next is a jagged array, myBools. It is essentially an array of arrays. We needed to use the new operator to instantiate the size of the primary array and then use the new operator again for each sub-array.
The third example is a two dimensional array, myDoubles. Arrays can be multi-dimensional, with each dimension separated by a comma. It must also be instantiated with the new operator.
One of the differences between jagged arrays, myBools[][], and multi-dimension arrays, myDoubles[,], is that a multi-dimension array will allocate memory for every element of each dimension, whereas a jagged array will only allocate memory for the size of each array in each dimension that you define. Most of the time, you'll be using multi-dimension arrays, if you need multiple dimensions, and will only use jagged arrays in very special circumstances when you are able to save significant memory by explicitly specifying the sizes of the arrays in each dimension.
Finally, we have the single-dimensional array of string types, myStrings.
In each case, you can see that array elements are accessed by identifying the integer index for the item you wish to refer to. Arrays sizes can be any int type value. Their indexes begin at 0.
Monday, 14 December 2009
Monday, 30 November 2009
Unique Features of Visual Studio 2008
Visual Studio 2008 ships with the expected GUI designers, code snippet support, database manipulation
tools, object and project browsing utilities, and an integrated help system. Unlike many of
the IDEs we have already examined, Visual Studio 2008 provides numerous additions. Here is a
partial list:
� Visual XML editors/designers
� Support for mobile device development (such as Smartphones and Pocket PC devices)
� Support for Microsoft Office development
� Designer support for Windows Workflow Foundation projects
� Integrated support for code refactoring
� Visual class design utilities
� The Object Test Bench window, which allows you to create objects and invoke their members
directly within the IDE
To be completely honest, Visual Studio 2008 provides so many features that it would take an
entire book (a rather large book at that) to fully describe every aspect of the IDE. This is not that
book. However, I do want to point out some of the major features in the pages that follow. As you
progress through the text, you�ll learn more about the Visual Studio 2008 IDE where appropriate.
tools, object and project browsing utilities, and an integrated help system. Unlike many of
the IDEs we have already examined, Visual Studio 2008 provides numerous additions. Here is a
partial list:
� Visual XML editors/designers
� Support for mobile device development (such as Smartphones and Pocket PC devices)
� Support for Microsoft Office development
� Designer support for Windows Workflow Foundation projects
� Integrated support for code refactoring
� Visual class design utilities
� The Object Test Bench window, which allows you to create objects and invoke their members
directly within the IDE
To be completely honest, Visual Studio 2008 provides so many features that it would take an
entire book (a rather large book at that) to fully describe every aspect of the IDE. This is not that
book. However, I do want to point out some of the major features in the pages that follow. As you
progress through the text, you�ll learn more about the Visual Studio 2008 IDE where appropriate.
over view of Common Language Runtime (CLR)
In addition to the CTS and CLS specifications, the final TLA (three-letter abbreviation) to contend
with at the moment is the CLR. Programmatically speaking, the term runtime can be understood as
a collection of external services that are required to execute a given compiled unit of code. For
example, when developers make use of the MFC to create a new application, they are aware that
their program requires the MFC runtime library (i.e., mfc42.dll). Other popular languages also
have a corresponding runtime. VB6 programmers are also tied to a runtime module or two (e.g.,
msvbvm60.dll). Java developers are tied to the Java Virtual Machine (JVM), and so forth.
The .NET platformoffers yet another runtime system. The key difference between the .NET
runtime and the various other runtimes I just mentioned is the fact that the .NET runtime provides
a single well-defined runtime layer that is shared by all languages and platforms that are .NETaware.
The crux of the CLR is physically represented by a library named mscoree.dll (a.k.a. the Common
Object Runtime Execution Engine). When an assembly is referenced for use, mscoree.dll is
loaded automatically, which in turn loads the required assembly into memory. The runtime engine
is responsible for a number of tasks. First and foremost, it is the entity in charge of resolving the
location of an assembly and finding the requested type within the binary by reading the contained
metadata. The CLR then lays out the type in memory, compiles the associated CIL into platformspecific
instructions, performs any necessary security checks, and then executes the code in
question.
In addition to loading your custom assemblies and creating your custom types, the CLR will
also interact with the types contained within the .NET base class libraries when required. Although
the entire base class library has been broken into a number of discrete assemblies, the key assembly
is mscorlib.dll. mscorlib.dll contains a large number of core types that encapsulate a wide variety
of common programming tasks as well as the core data types used by all .NET languages. When you
build .NET solutions, you automatically have access to this particular assembly.
Figure 1-4 illustrates the workflow that takes place between your source code (which is making
use of base class library types), a given .NET compiler, and the .NET execution engine.
with at the moment is the CLR. Programmatically speaking, the term runtime can be understood as
a collection of external services that are required to execute a given compiled unit of code. For
example, when developers make use of the MFC to create a new application, they are aware that
their program requires the MFC runtime library (i.e., mfc42.dll). Other popular languages also
have a corresponding runtime. VB6 programmers are also tied to a runtime module or two (e.g.,
msvbvm60.dll). Java developers are tied to the Java Virtual Machine (JVM), and so forth.
The .NET platformoffers yet another runtime system. The key difference between the .NET
runtime and the various other runtimes I just mentioned is the fact that the .NET runtime provides
a single well-defined runtime layer that is shared by all languages and platforms that are .NETaware.
The crux of the CLR is physically represented by a library named mscoree.dll (a.k.a. the Common
Object Runtime Execution Engine). When an assembly is referenced for use, mscoree.dll is
loaded automatically, which in turn loads the required assembly into memory. The runtime engine
is responsible for a number of tasks. First and foremost, it is the entity in charge of resolving the
location of an assembly and finding the requested type within the binary by reading the contained
metadata. The CLR then lays out the type in memory, compiles the associated CIL into platformspecific
instructions, performs any necessary security checks, and then executes the code in
question.
In addition to loading your custom assemblies and creating your custom types, the CLR will
also interact with the types contained within the .NET base class libraries when required. Although
the entire base class library has been broken into a number of discrete assemblies, the key assembly
is mscorlib.dll. mscorlib.dll contains a large number of core types that encapsulate a wide variety
of common programming tasks as well as the core data types used by all .NET languages. When you
build .NET solutions, you automatically have access to this particular assembly.
Figure 1-4 illustrates the workflow that takes place between your source code (which is making
use of base class library types), a given .NET compiler, and the .NET execution engine.
Over view of Common Language Specification (CLS)
As you are aware, different languages express the same programming constructs in unique, language-
specific terms. For example, in C# you denote string concatenation using the plus operator
(+), while in VB .NET you typically make use of the ampersand (&). Even when two distinct languages
express the same programmatic idiom (e.g., a function with no return value), the chances
are very good that the syntax will appear quite different on the surface:
// C# method returning nothing.
public void MyMethod()
{
// Some interesting code...
}
' VB method returning nothing.
Public Sub MyMethod()
' Some interesting code...
End Sub
As you have already seen, these minor syntactic variations are inconsequential in the eyes of
the .NET runtime, given that the respective compilers (csc.exe or vbc.exe, in this case) emit a similar
set of CIL instructions. However, languages can also differ with regard to their overall level of
functionality. For example, a .NET language may or may not have a keyword to represent unsigned
data, and may or may not support pointer types. Given these possible variations, it would be ideal
to have a baseline to which all .NET-aware languages are expected to conform.
The CLS is a set of rules that describe in vivid detail the minimal and complete set of features a
given .NET-aware compiler must support to produce code that can be hosted by the CLR, while at
the same time be accessed in a uniform manner by all languages that target the .NET platform. In
many ways, the CLS can be viewed as a subset of the full functionality defined by the CTS.
The CLS is ultimately a set of rules that compiler builders must conform to, if they intend their
products to function seamlessly within the .NET universe. Each rule is assigned a simple name (e.g.,
�CLS Rule 6�) and describes how this rule affects those who build the compilers as well as those
who (in some way) interact with them. The cr�me de la cr�me of the CLS is the mighty Rule 1:
� Rule 1: CLS rules apply only to those parts of a type that are exposed outside the defining
assembly.
Given this rule, you can (correctly) infer that the remaining rules of the CLS do not apply to the
logic used to build the inner workings of a .NET type. The only aspects of a type that must conform
to the CLS are the member definitions themselves (i.e., naming conventions, parameters, and
return types). The implementation logic for a member may use any number of non-CLS techniques,
as the outside world won�t know the difference.
To illustrate, the following Add() method is not CLS-compliant, as the parameters and return
values make use of unsigned data (which is not a requirement of the CLS):
class Calc
{
// Exposed unsigned data is not CLS compliant!
public ulong Add(ulong x, ulong y)
{ return x + y;}
}
However, if you were to simply make use of unsigned data internally as follows:
class Calc
{
public int Add(int x, int y)
{
// As this ulong variable is only used internally,
// we are still CLS compliant.
ulong temp = 0;
...
return x + y;
}
}
you have still conformed to the rules of the CLS, and can rest assured that all .NET languages are
able to invoke the Add() method.
Of course, in addition to Rule 1, the CLS defines numerous other rules. For example, the
CLS describes how a given language must represent text strings, how enumerations should be
represented internally (the base type used for storage), how to define static members, and so forth.
Luckily, you don�t have to commit these rules to memory to be a proficient .NET developer. Again,
by and large, an intimate understanding of the CTS and CLS specifications is only of interest to
tool/compiler builders.
specific terms. For example, in C# you denote string concatenation using the plus operator
(+), while in VB .NET you typically make use of the ampersand (&). Even when two distinct languages
express the same programmatic idiom (e.g., a function with no return value), the chances
are very good that the syntax will appear quite different on the surface:
// C# method returning nothing.
public void MyMethod()
{
// Some interesting code...
}
' VB method returning nothing.
Public Sub MyMethod()
' Some interesting code...
End Sub
As you have already seen, these minor syntactic variations are inconsequential in the eyes of
the .NET runtime, given that the respective compilers (csc.exe or vbc.exe, in this case) emit a similar
set of CIL instructions. However, languages can also differ with regard to their overall level of
functionality. For example, a .NET language may or may not have a keyword to represent unsigned
data, and may or may not support pointer types. Given these possible variations, it would be ideal
to have a baseline to which all .NET-aware languages are expected to conform.
The CLS is a set of rules that describe in vivid detail the minimal and complete set of features a
given .NET-aware compiler must support to produce code that can be hosted by the CLR, while at
the same time be accessed in a uniform manner by all languages that target the .NET platform. In
many ways, the CLS can be viewed as a subset of the full functionality defined by the CTS.
The CLS is ultimately a set of rules that compiler builders must conform to, if they intend their
products to function seamlessly within the .NET universe. Each rule is assigned a simple name (e.g.,
�CLS Rule 6�) and describes how this rule affects those who build the compilers as well as those
who (in some way) interact with them. The cr�me de la cr�me of the CLS is the mighty Rule 1:
� Rule 1: CLS rules apply only to those parts of a type that are exposed outside the defining
assembly.
Given this rule, you can (correctly) infer that the remaining rules of the CLS do not apply to the
logic used to build the inner workings of a .NET type. The only aspects of a type that must conform
to the CLS are the member definitions themselves (i.e., naming conventions, parameters, and
return types). The implementation logic for a member may use any number of non-CLS techniques,
as the outside world won�t know the difference.
To illustrate, the following Add() method is not CLS-compliant, as the parameters and return
values make use of unsigned data (which is not a requirement of the CLS):
class Calc
{
// Exposed unsigned data is not CLS compliant!
public ulong Add(ulong x, ulong y)
{ return x + y;}
}
However, if you were to simply make use of unsigned data internally as follows:
class Calc
{
public int Add(int x, int y)
{
// As this ulong variable is only used internally,
// we are still CLS compliant.
ulong temp = 0;
...
return x + y;
}
}
you have still conformed to the rules of the CLS, and can rest assured that all .NET languages are
able to invoke the Add() method.
Of course, in addition to Rule 1, the CLS defines numerous other rules. For example, the
CLS describes how a given language must represent text strings, how enumerations should be
represented internally (the base type used for storage), how to define static members, and so forth.
Luckily, you don�t have to commit these rules to memory to be a proficient .NET developer. Again,
by and large, an intimate understanding of the CTS and CLS specifications is only of interest to
tool/compiler builders.
Common Type System (CTS)
A given assembly may contain any number of distinct types. In the world of .NET, type is simply a
general term used to refer to a member from the set {class, interface, structure, enumeration, delegate}.
When you build solutions using a .NET-aware language, you will most likely interact with
many of these types. For example, your assembly may define a single class that implements some
number of interfaces. Perhaps one of the interface methods takes an enumeration type as an input
parameter and returns a structure to the caller.
Recall that the CTS is a formal specification that documents how types must be defined in
order to be hosted by the CLR. Typically, the only individuals who are deeply concerned with the
inner workings of the CTS are those building tools and/or compilers that target the .NET platform.
It is important, however, for all .NET programmers to learn about how to work with the five types
defined by the CTS in their language of choice. Here is a brief overview.
CTS Class Types
Every .NET-aware language supports, at the very least, the notion of a class type, which is the cornerstone
of object-oriented programming (OOP). A class may be composed of any number of
members (such as properties, methods, and events) and data points (fields). In C#, classes are
declared using the class keyword:
// A C# class type.
class Calc
{
public int Add(int x, int y)
{ return x + y; }
}
CTS Interface Types
Interfaces are nothing more than a named collection of abstract member definitions, which may be
supported (i.e., implemented) by a given class or structure. Unlike COM, .NET interfaces do not
derive a common base interface such as IUnknown. In C#, interface types are defined using the
interface keyword, for example:
// A C# interface type is usually
// declared as public, to allow types in other
// assemblies to implement their behavior.
public interface IDraw
{
void Draw();
}
On their own, interfaces are of little use. However, when a class or structure implements a given
interface in its unique way, you are able to request access to the supplied functionality using an
interface reference in a polymorphic manner.
CTS Structure Types
The concept of a structure is also formalized under the CTS. If you have a C background, you should
be pleased to know that these user-defined types (UDTs) have survived in the world of .NET (although
they behave a bit differently under the hood). Simply put, a structure can be thought of as a lightweight
class type having value-based semantics. For more details on the subtleties of structures, Typically, structures are best suited for modeling geometric and mathematical data, and
are created in C# using the struct keyword:
// A C# structure type.
struct Point
{
// Structures can contain fields.
public int xPos, yPos;
// Structures can contain parameterized constructors.
public Point(int x, int y)
{ xPos = x; yPos = y;}
// Structures may define methods.
public void Display()
{
Console.WriteLine("({0}, {1}", xPos, yPos);
}
}
CTS Enumeration Types
Enumerations are handy programming constructs that allow you to group name/value pairs. For
example, assume you are creating a video-game application that allows the player to select one of
three character categories (Wizard, Fighter, or Thief). Rather than keeping track of raw numerical
values to represent each possibility, you could build a custom enumeration using the enum keyword:
// A C# enumeration type.
enum CharacterType
{
Wizard = 100,
Fighter = 200,
Thief = 300
}
By default, the storage used to hold each item is a 32-bit integer; however, it is possible to alter
this storage slot if need be (e.g., when programming for a low-memory device such as a Pocket PC).
Also, the CTS demands that enumerated types derive from a common base class, System.Enum. this base class defines a number of interesting members that allow you to
extract, manipulate, and transform the underlying name/value pairs programmatically.
CTS Delegate Types
Delegates are the .NET equivalent of a type-safe C-style function pointer. The key difference is that a
.NET delegate is a class that derives from System.MulticastDelegate, rather than a simple pointer to
a raw memory address. In C#, delegates are declared using the delegate keyword:
// This C# delegate type can "point to" any method
// returning an integer and taking two integers as input.
delegate int BinaryOp(int x, int y);
Delegates are useful when you wish to provide a way for one entity to forward a call to another
entity, and provide the foundation for the .NET event architecture. delegates have intrinsic support for multicasting (i.e., forwarding a request to multiple
recipients) and asynchronous method invocations.
CTS Type Members
Now that you have previewed each of the types formalized by the CTS, realize that most types take
any number of members. Formally speaking, a type member is constrained by the set {constructor,
finalizer, static constructor, nested type, operator, method, property, indexer, field, read-only field,
constant, event}.
The CTS defines various �adornments� that may be associated with a given member. For example,
each member has a given visibility trait (e.g., public, private, protected, and so forth). Some
members may be declared as abstract to enforce a polymorphic behavior on derived types as well as
virtual to define a canned (but overridable) implementation. Also, most members may be configured
as static (bound at the class level) or instance (bound at the object level). The construction of
type members is examined over the course of the next several chapters.
nNote, the C# language also supports the construction of generic types and generic
members.
Intrinsic CTS Data Types
The final aspect of the CTS to be aware of for the time being is that it establishes a well-defined set
of fundamental data types. Although a given language typically has a unique keyword used to
declare an intrinsic CTS data type, all language keywords ultimately resolve to the same type
defined in an assembly named mscorlib.dll.
data types are expressed in various .NET languages.
The Intrinsic CTS Data Types
CTS Data Type VB .NET Keyword C# Keyword C++/CLI Keyword
System.Byte Byte byte unsigned char
System.SByte SByte sbyte signed char
System.Int16 Short short short
System.Int32 Integer int int or long
System.Int64 Long long __int64
System.UInt16 UShort ushort unsigned short
System.UInt32 UInteger uint unsigned int or unsigned long
System.UInt64 ULong ulong unsigned __int64
System.Single Single float Float
System.Double Double double Double
System.Object Object object Object^
System.Char Char char wchar_t
System.String String string String^
System.Decimal Decimal decimal Decimal
System.Boolean Boolean bool Bool
Given the fact that the unique keywords of a managed language are simply shorthand notations
for a real type in the System namespace, we no longer have to worry about overflow/underflow
conditions for numerical data, or how strings and Booleans are internally represented across different
languages. Consider the following code snippets, which define 32-bit numerical variables in C#
and VB .NET, using language keywords as well as the formal CTS type:
// Define some "ints" in C#.
int i = 0;
System.Int32 j = 0;
' Define some "ints" in VB .NET.
Dim i As Integer = 0
Dim j As System.Int32 = 0
general term used to refer to a member from the set {class, interface, structure, enumeration, delegate}.
When you build solutions using a .NET-aware language, you will most likely interact with
many of these types. For example, your assembly may define a single class that implements some
number of interfaces. Perhaps one of the interface methods takes an enumeration type as an input
parameter and returns a structure to the caller.
Recall that the CTS is a formal specification that documents how types must be defined in
order to be hosted by the CLR. Typically, the only individuals who are deeply concerned with the
inner workings of the CTS are those building tools and/or compilers that target the .NET platform.
It is important, however, for all .NET programmers to learn about how to work with the five types
defined by the CTS in their language of choice. Here is a brief overview.
CTS Class Types
Every .NET-aware language supports, at the very least, the notion of a class type, which is the cornerstone
of object-oriented programming (OOP). A class may be composed of any number of
members (such as properties, methods, and events) and data points (fields). In C#, classes are
declared using the class keyword:
// A C# class type.
class Calc
{
public int Add(int x, int y)
{ return x + y; }
}
CTS Interface Types
Interfaces are nothing more than a named collection of abstract member definitions, which may be
supported (i.e., implemented) by a given class or structure. Unlike COM, .NET interfaces do not
derive a common base interface such as IUnknown. In C#, interface types are defined using the
interface keyword, for example:
// A C# interface type is usually
// declared as public, to allow types in other
// assemblies to implement their behavior.
public interface IDraw
{
void Draw();
}
On their own, interfaces are of little use. However, when a class or structure implements a given
interface in its unique way, you are able to request access to the supplied functionality using an
interface reference in a polymorphic manner.
CTS Structure Types
The concept of a structure is also formalized under the CTS. If you have a C background, you should
be pleased to know that these user-defined types (UDTs) have survived in the world of .NET (although
they behave a bit differently under the hood). Simply put, a structure can be thought of as a lightweight
class type having value-based semantics. For more details on the subtleties of structures, Typically, structures are best suited for modeling geometric and mathematical data, and
are created in C# using the struct keyword:
// A C# structure type.
struct Point
{
// Structures can contain fields.
public int xPos, yPos;
// Structures can contain parameterized constructors.
public Point(int x, int y)
{ xPos = x; yPos = y;}
// Structures may define methods.
public void Display()
{
Console.WriteLine("({0}, {1}", xPos, yPos);
}
}
CTS Enumeration Types
Enumerations are handy programming constructs that allow you to group name/value pairs. For
example, assume you are creating a video-game application that allows the player to select one of
three character categories (Wizard, Fighter, or Thief). Rather than keeping track of raw numerical
values to represent each possibility, you could build a custom enumeration using the enum keyword:
// A C# enumeration type.
enum CharacterType
{
Wizard = 100,
Fighter = 200,
Thief = 300
}
By default, the storage used to hold each item is a 32-bit integer; however, it is possible to alter
this storage slot if need be (e.g., when programming for a low-memory device such as a Pocket PC).
Also, the CTS demands that enumerated types derive from a common base class, System.Enum. this base class defines a number of interesting members that allow you to
extract, manipulate, and transform the underlying name/value pairs programmatically.
CTS Delegate Types
Delegates are the .NET equivalent of a type-safe C-style function pointer. The key difference is that a
.NET delegate is a class that derives from System.MulticastDelegate, rather than a simple pointer to
a raw memory address. In C#, delegates are declared using the delegate keyword:
// This C# delegate type can "point to" any method
// returning an integer and taking two integers as input.
delegate int BinaryOp(int x, int y);
Delegates are useful when you wish to provide a way for one entity to forward a call to another
entity, and provide the foundation for the .NET event architecture. delegates have intrinsic support for multicasting (i.e., forwarding a request to multiple
recipients) and asynchronous method invocations.
CTS Type Members
Now that you have previewed each of the types formalized by the CTS, realize that most types take
any number of members. Formally speaking, a type member is constrained by the set {constructor,
finalizer, static constructor, nested type, operator, method, property, indexer, field, read-only field,
constant, event}.
The CTS defines various �adornments� that may be associated with a given member. For example,
each member has a given visibility trait (e.g., public, private, protected, and so forth). Some
members may be declared as abstract to enforce a polymorphic behavior on derived types as well as
virtual to define a canned (but overridable) implementation. Also, most members may be configured
as static (bound at the class level) or instance (bound at the object level). The construction of
type members is examined over the course of the next several chapters.
nNote, the C# language also supports the construction of generic types and generic
members.
Intrinsic CTS Data Types
The final aspect of the CTS to be aware of for the time being is that it establishes a well-defined set
of fundamental data types. Although a given language typically has a unique keyword used to
declare an intrinsic CTS data type, all language keywords ultimately resolve to the same type
defined in an assembly named mscorlib.dll.
data types are expressed in various .NET languages.
The Intrinsic CTS Data Types
CTS Data Type VB .NET Keyword C# Keyword C++/CLI Keyword
System.Byte Byte byte unsigned char
System.SByte SByte sbyte signed char
System.Int16 Short short short
System.Int32 Integer int int or long
System.Int64 Long long __int64
System.UInt16 UShort ushort unsigned short
System.UInt32 UInteger uint unsigned int or unsigned long
System.UInt64 ULong ulong unsigned __int64
System.Single Single float Float
System.Double Double double Double
System.Object Object object Object^
System.Char Char char wchar_t
System.String String string String^
System.Decimal Decimal decimal Decimal
System.Boolean Boolean bool Bool
Given the fact that the unique keywords of a managed language are simply shorthand notations
for a real type in the System namespace, we no longer have to worry about overflow/underflow
conditions for numerical data, or how strings and Booleans are internally represented across different
languages. Consider the following code snippets, which define 32-bit numerical variables in C#
and VB .NET, using language keywords as well as the formal CTS type:
// Define some "ints" in C#.
int i = 0;
System.Int32 j = 0;
' Define some "ints" in VB .NET.
Dim i As Integer = 0
Dim j As System.Int32 = 0
The Role of the Assembly Manifest
Last but not least, remember that a .NET assembly also contains metadata that describes the
assembly itself (technically termed a manifest). Among other details, the manifest documents all
external assemblies required by the current assembly to function correctly, the assembly�s version
number, copyright information, and so forth. Like type metadata, it is always the job of the compiler
to generate the assembly�s manifest. Here are some relevant details of the manifest generated
when compiling the Calc.cs code file shown earlier in this chapter (assume we instructed the compiler
to name our assembly Calc.exe):
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 2:0:0:0
}
.assembly Calc
{
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.module Calc.exe
.imagebase 0x00400000
.subsystem 0x00000003
.file alignment 512
.corflags 0x00000001
16 CHAPTER 1 n THE PHILOSOPHY OF .NET
In a nutshell, this manifest documents the list of external assemblies required by Calc.exe (via
the .assembly extern directive) as well as various characteristics of the assembly itself (version
number, module name, and so on). Chapter 15 will examine the usefulness of manifest data in
much more detail.
assembly itself (technically termed a manifest). Among other details, the manifest documents all
external assemblies required by the current assembly to function correctly, the assembly�s version
number, copyright information, and so forth. Like type metadata, it is always the job of the compiler
to generate the assembly�s manifest. Here are some relevant details of the manifest generated
when compiling the Calc.cs code file shown earlier in this chapter (assume we instructed the compiler
to name our assembly Calc.exe):
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 2:0:0:0
}
.assembly Calc
{
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.module Calc.exe
.imagebase 0x00400000
.subsystem 0x00000003
.file alignment 512
.corflags 0x00000001
16 CHAPTER 1 n THE PHILOSOPHY OF .NET
In a nutshell, this manifest documents the list of external assemblies required by Calc.exe (via
the .assembly extern directive) as well as various characteristics of the assembly itself (version
number, module name, and so on). Chapter 15 will examine the usefulness of manifest data in
much more detail.
The Role of .NET Type Metadata
In addition to CIL instructions, a .NET assembly contains full, complete, and accurate metadata,
which describes each and every type (class, structure, enumeration, and so forth) defined in the
binary, as well as the members of each type (properties, methods, events, and so on). Thankfully, it
is always the job of the compiler (not the programmer) to emit the latest and greatest type metadata.
Because .NET metadata is so wickedly meticulous, assemblies are completely self-describing
entities.
To illustrate the format of .NET type metadata, let�s take a look at the metadata that has been
generated for the Add() method of the C# Calc class you examined previously (the metadata generated
for the VB .NET version of the Add() method is similar):
CHAPTER 1 n THE PHILOSOPHY OF .NET 15
TypeDef #2 (02000003)
-------------------------------------------------------
TypDefName: CalculatorExample.Calc (02000003)
Flags : [NotPublic] [AutoLayout] [Class]
[AnsiClass] [BeforeFieldInit] (00100001)
Extends : 01000001 [TypeRef] System.Object
Method #1 (06000003)
-------------------------------------------------------
MethodName: Add (06000003)
Flags : [Public] [HideBySig] [ReuseSlot] (00000086)
RVA : 0x00002090
ImplFlags : [IL] [Managed] (00000000)
CallCnvntn: [DEFAULT]
hasThis
ReturnType: I4
2 Arguments
Argument #1: I4
Argument #2: I4
2 Parameters
(1) ParamToken : (08000001) Name : x flags: [none] (00000000)
(2) ParamToken : (08000002) Name : y flags: [none] (00000000)
Metadata is used by numerous aspects of the .NET runtime environment, as well as by various
development tools. For example, the IntelliSense feature provided by tools such as Visual Studio
2008 is made possible by reading an assembly�s metadata at design time. Metadata is also used by
various object browsing utilities, debugging tools, and the C# compiler itself. To be sure, metadata is
the backbone of numerous .NET technologies including Windows Communication Foundation
(WCF), XML web services/the .NET remoting layer, reflection, late binding, and object serialization.
Chapter 16 will formalize the role of .NET metadata.
which describes each and every type (class, structure, enumeration, and so forth) defined in the
binary, as well as the members of each type (properties, methods, events, and so on). Thankfully, it
is always the job of the compiler (not the programmer) to emit the latest and greatest type metadata.
Because .NET metadata is so wickedly meticulous, assemblies are completely self-describing
entities.
To illustrate the format of .NET type metadata, let�s take a look at the metadata that has been
generated for the Add() method of the C# Calc class you examined previously (the metadata generated
for the VB .NET version of the Add() method is similar):
CHAPTER 1 n THE PHILOSOPHY OF .NET 15
TypeDef #2 (02000003)
-------------------------------------------------------
TypDefName: CalculatorExample.Calc (02000003)
Flags : [NotPublic] [AutoLayout] [Class]
[AnsiClass] [BeforeFieldInit] (00100001)
Extends : 01000001 [TypeRef] System.Object
Method #1 (06000003)
-------------------------------------------------------
MethodName: Add (06000003)
Flags : [Public] [HideBySig] [ReuseSlot] (00000086)
RVA : 0x00002090
ImplFlags : [IL] [Managed] (00000000)
CallCnvntn: [DEFAULT]
hasThis
ReturnType: I4
2 Arguments
Argument #1: I4
Argument #2: I4
2 Parameters
(1) ParamToken : (08000001) Name : x flags: [none] (00000000)
(2) ParamToken : (08000002) Name : y flags: [none] (00000000)
Metadata is used by numerous aspects of the .NET runtime environment, as well as by various
development tools. For example, the IntelliSense feature provided by tools such as Visual Studio
2008 is made possible by reading an assembly�s metadata at design time. Metadata is also used by
various object browsing utilities, debugging tools, and the C# compiler itself. To be sure, metadata is
the backbone of numerous .NET technologies including Windows Communication Foundation
(WCF), XML web services/the .NET remoting layer, reflection, late binding, and object serialization.
Chapter 16 will formalize the role of .NET metadata.
Common Intermediate Language
Let�s examine CIL code, type metadata, and the assembly manifest in a bit more detail. CIL is a language
that sits above any particular platform-specific instruction set. For example, the following C#
code models a trivial calculator. Don�t concern yourself with the exact syntax for now, but do notice
the format of the Add() method in the Calc class:
// Calc.cs
using System;
namespace CalculatorExample
{
// This class contains the app's entry point.
class Program
{
static void Main()
{
Calc c = new Calc();
int ans = c.Add(10, 84);
Console.WriteLine("10 + 84 is {0}.", ans);
// Wait for user to press the Enter key before shutting down.
Console.ReadLine();
}
}
// The C# calculator.
class Calc
{
public int Add(int x, int y)
{ return x + y; }
}
}
Once you compile this code file using the C# compiler (csc.exe), you end up with a single-file
*.exe assembly that contains a manifest, CIL instructions, and metadata describing each aspect of
the Calc and Program classes.
nNote Chapter 2 examines the details of compiling code using the C# compiler, as well as the use of graphical
IDEs such as Visual Studio, Visual C# Express, and SharpDevelop.
For example, if you were to open this assembly using ildasm.exe (examined a little later in this
chapter), you would find that the Add() method is represented using CIL such as the following:
.method public hidebysig instance int32 Add(int32 x,
int32 y) cil managed
{
// Code size 9 (0x9)
.maxstack 2
.locals init (int32 V_0)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldarg.2
IL_0003: add
IL_0004: stloc.0
CHAPTER 1 n THE PHILOSOPHY OF .NET 13
IL_0005: br.s IL_0007
IL_0007: ldloc.0
IL_0008: ret
} // end of method Calc::Add
Don�t worry if you are unable to make heads or tails of the resulting CIL for this method�
Chapter 19 will describe the basics of the CIL programming language. The point to concentrate on
is that the C# compiler emits CIL, not platform-specific instructions.
Now, recall that this is true of all .NET-aware compilers. To illustrate, assume you created this
same application using Visual Basic .NET, rather than C#:
' Calc.vb
Imports System
Namespace CalculatorExample
' A VB "Module" is a class that contains only
' static members.
Module Program
Sub Main()
Dim c As New Calc
Dim ans As Integer = c.Add(10, 84)
Console.WriteLine("10 + 84 is {0}.", ans)
Console.ReadLine()
End Sub
End Module
Class Calc
Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Return x + y
End Function
End Class
End Namespace
If you examine the CIL for the Add() method, you find similar instructions (slightly tweaked by
the VB .NET compiler, vbc.exe):
.method public instance int32 Add(int32 x,
int32 y) cil managed
{
// Code size 8 (0x8)
.maxstack 2
.locals init (int32 V_0)
IL_0000: ldarg.1
IL_0001: ldarg.2
IL_0002: add.ovf
IL_0003: stloc.0
IL_0004: br.s IL_0006
IL_0006: ldloc.0
IL_0007: ret
} // end of method Calc::Add
that sits above any particular platform-specific instruction set. For example, the following C#
code models a trivial calculator. Don�t concern yourself with the exact syntax for now, but do notice
the format of the Add() method in the Calc class:
// Calc.cs
using System;
namespace CalculatorExample
{
// This class contains the app's entry point.
class Program
{
static void Main()
{
Calc c = new Calc();
int ans = c.Add(10, 84);
Console.WriteLine("10 + 84 is {0}.", ans);
// Wait for user to press the Enter key before shutting down.
Console.ReadLine();
}
}
// The C# calculator.
class Calc
{
public int Add(int x, int y)
{ return x + y; }
}
}
Once you compile this code file using the C# compiler (csc.exe), you end up with a single-file
*.exe assembly that contains a manifest, CIL instructions, and metadata describing each aspect of
the Calc and Program classes.
nNote Chapter 2 examines the details of compiling code using the C# compiler, as well as the use of graphical
IDEs such as Visual Studio, Visual C# Express, and SharpDevelop.
For example, if you were to open this assembly using ildasm.exe (examined a little later in this
chapter), you would find that the Add() method is represented using CIL such as the following:
.method public hidebysig instance int32 Add(int32 x,
int32 y) cil managed
{
// Code size 9 (0x9)
.maxstack 2
.locals init (int32 V_0)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldarg.2
IL_0003: add
IL_0004: stloc.0
CHAPTER 1 n THE PHILOSOPHY OF .NET 13
IL_0005: br.s IL_0007
IL_0007: ldloc.0
IL_0008: ret
} // end of method Calc::Add
Don�t worry if you are unable to make heads or tails of the resulting CIL for this method�
Chapter 19 will describe the basics of the CIL programming language. The point to concentrate on
is that the C# compiler emits CIL, not platform-specific instructions.
Now, recall that this is true of all .NET-aware compilers. To illustrate, assume you created this
same application using Visual Basic .NET, rather than C#:
' Calc.vb
Imports System
Namespace CalculatorExample
' A VB "Module" is a class that contains only
' static members.
Module Program
Sub Main()
Dim c As New Calc
Dim ans As Integer = c.Add(10, 84)
Console.WriteLine("10 + 84 is {0}.", ans)
Console.ReadLine()
End Sub
End Module
Class Calc
Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Return x + y
End Function
End Class
End Namespace
If you examine the CIL for the Add() method, you find similar instructions (slightly tweaked by
the VB .NET compiler, vbc.exe):
.method public instance int32 Add(int32 x,
int32 y) cil managed
{
// Code size 8 (0x8)
.maxstack 2
.locals init (int32 V_0)
IL_0000: ldarg.1
IL_0001: ldarg.2
IL_0002: add.ovf
IL_0003: stloc.0
IL_0004: br.s IL_0006
IL_0006: ldloc.0
IL_0007: ret
} // end of method Calc::Add
Thursday, 5 November 2009
What are the different kind of parsers used in XML?
There are 2 parsers:
1) DOM (Document object model): This will interpret Complete XML document.Microsoft major concentration is DOM Parser.
2) SAX Parser (Simple Aplication programming Interface for XML): This will interpret XML document based on the event occurrence only it wont interpret complete document at a time. Sun mycrosystems major concentration is SAX Parser.What is XPath?
XPath is used to navigate through elements and attributes in an XML document.
1) DOM (Document object model): This will interpret Complete XML document.Microsoft major concentration is DOM Parser.
2) SAX Parser (Simple Aplication programming Interface for XML): This will interpret XML document based on the event occurrence only it wont interpret complete document at a time. Sun mycrosystems major concentration is SAX Parser.What is XPath?
XPath is used to navigate through elements and attributes in an XML document.
Wednesday, 4 November 2009
What is SOAP?
SOAP is an XML-based protocol for exchanging information between computers. Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the main focus of SOAP is Remote Procedure Calls (RPC) transported via HTTP. Like XML-RPC, SOAP is platform independent, and therefore enables diverse applications to communicate with one another.
Tuesday, 20 October 2009
ADO.Net
1. What is ADO.Net?
ActiveX Data Object (ADO).NET is the primary relational data access model for Microsoft .NET-based applications. ADO.Net provides consistent data access from database management system (DBMS) such as SQL Server, Oracle etc. ADO.NET is exclusively designed to meet the requirements of web-based applications model such as disconnected data architecture, integration with XML, common data representation, combining data from multiple data sources, and optimization in interacting with the database.
ActiveX Data Object (ADO).NET is the primary relational data access model for Microsoft .NET-based applications. ADO.Net provides consistent data access from database management system (DBMS) such as SQL Server, Oracle etc. ADO.NET is exclusively designed to meet the requirements of web-based applications model such as disconnected data architecture, integration with XML, common data representation, combining data from multiple data sources, and optimization in interacting with the database.
Difference between shadowing and overriden
Shadowing :- This is a VB.Net Concept by which you can provide a new implementation for the base class member without overriding the member. You can shadow a base class member in the derived class by using the keyword Shadows . The method signature access level and return type of the shadowed member can be completely different than the base class member.
Hiding : - This is a C# Concept by which you can provide a new implementation for the base class member without overriding the member. You can hide a base class member in the derived class by using the keyword new . The method signature access level and return type of the hidden member has to be same as the base class member.Comparing the three :-
1) The access level signature and the return type can only be changed when you are shadowing with VB.NET. Hiding and overriding demands the these parameters as same.
2) The difference lies when you call the derived class object with a base class variable.In class of overriding although you assign a derived class object to base class variable it will call the derived class function. In case of shadowing or hiding the base class function will be called.
Hiding : - This is a C# Concept by which you can provide a new implementation for the base class member without overriding the member. You can hide a base class member in the derived class by using the keyword new . The method signature access level and return type of the hidden member has to be same as the base class member.Comparing the three :-
1) The access level signature and the return type can only be changed when you are shadowing with VB.NET. Hiding and overriding demands the these parameters as same.
2) The difference lies when you call the derived class object with a base class variable.In class of overriding although you assign a derived class object to base class variable it will call the derived class function. In case of shadowing or hiding the base class function will be called.
Difference between Constant and Readonly
Constant : The constants are the one whose value remain same at all the time.
it will be used if u want to define something at compile time.
Read only:
if you don't know value at compile time but u can find that at runtime that time u can use readonly ..
Read only are the things which are not to allowed to alter by the user but it can be altered by itself. Readonly is generally use in Constructor of the classes.
Like the path of the application exe is read only. If you copy exe to some other directory the path will change. But still it is read only
it will be used if u want to define something at compile time.
Read only:
if you don't know value at compile time but u can find that at runtime that time u can use readonly ..
Read only are the things which are not to allowed to alter by the user but it can be altered by itself. Readonly is generally use in Constructor of the classes.
Like the path of the application exe is read only. If you copy exe to some other directory the path will change. But still it is read only
Interface Vs Delegate
Interfaces allow us to extend some object's functionality, it's a contract
between the interface and the object that implements it. It is used to
simulate multiple inheritance in C#.
In the other hand, we have delegates...
They're just safe callbacks or function pointers. They allow us to notify
that something has happened (Events). As you can see they're different as
well as their use.
between the interface and the object that implements it. It is used to
simulate multiple inheritance in C#.
In the other hand, we have delegates...
They're just safe callbacks or function pointers. They allow us to notify
that something has happened (Events). As you can see they're different as
well as their use.
Monday, 19 October 2009
Unified Modeling Language
What is UML?
UML is Unified Modeling Language. It is a graphical language for visualizing specifying constructing and documenting the artifacts of the system. It allows you to create a blue print of all the aspects of the system, before actually physically implementing the system.
.
UML is Unified Modeling Language. It is a graphical language for visualizing specifying constructing and documenting the artifacts of the system. It allows you to create a blue print of all the aspects of the system, before actually physically implementing the system.
.
Monday, 28 September 2009
What is observableCollection in WPF
In many cases the data that you work with is a collection of objects. For example, a common scenario in data binding is to use anItemsControl such as a ListBox, ListView, or TreeView to display a collection of records.
You can enumerate over any collection that implements the IEnumerable interface. However, to set up dynamic bindings so that insertions or deletions in the collection update the UI automatically, the collection must implement the INotifyCollectionChanged interface. This interface exposes the CollectionChanged event, an event that should be raised whenever the underlying collection changes.
WPF provides the ObservableCollection(T) class, which is a built-in implementation of a data collection that implements theINotifyCollectionChanged interface.
Before implementing your own collection, consider using ObservableCollection(T) or one of the existing collection classes, such as List(T),Collection(T), and BindingList(T), among many others. If you have an advanced scenario and want to implement your own collection, consider using IList, which provides a non-generic collection of objects that can be individually accessed by index. Implementing IList provides the best performance with the data binding engine.
You can enumerate over any collection that implements the IEnumerable interface. However, to set up dynamic bindings so that insertions or deletions in the collection update the UI automatically, the collection must implement the INotifyCollectionChanged interface. This interface exposes the CollectionChanged event, an event that should be raised whenever the underlying collection changes.
WPF provides the ObservableCollection(T) class, which is a built-in implementation of a data collection that implements theINotifyCollectionChanged interface.
Before implementing your own collection, consider using ObservableCollection(T) or one of the existing collection classes, such as List(T),Collection(T), and BindingList(T), among many others. If you have an advanced scenario and want to implement your own collection, consider using IList, which provides a non-generic collection of objects that can be individually accessed by index. Implementing IList provides the best performance with the data binding engine.
Thursday, 17 September 2009
What is SaaS
Software as a service (or SaaS) is a way of delivering applications over the Internet�as a service. Instead of installing and maintaining software, you simply access it via the Internet, freeing yourself from complex software and hardware management.
SaaS applications are sometimes called Web-based software, on-demand software, or hosted software. Whatever the name, SaaS applications run on a SaaS provider�s servers. The provider manages access to the application, including security, availability, and performance.
SaaS applications are sometimes called Web-based software, on-demand software, or hosted software. Whatever the name, SaaS applications run on a SaaS provider�s servers. The provider manages access to the application, including security, availability, and performance.
Saturday, 12 September 2009
What are the three kinds of routed events in WPF and how do they differ?
Routed events in WPF are direct, tunneling a bubbling. A direct event can be raised only by the element in which it originated. A bubbling event is raised first by the element in which it originates and then is raised by each successive container in the visual tree. A tunneling event is raised first by the topmost container in the visual tree and then down through each successive container until it is finally raised by the element in which it originated. Tunneling and bubbling events allow elements of the user interface to respond to events raised by their contained elements.
Friday, 28 August 2009
What is Microsoft SharePoint Portal Server?
SharePoint Portal Server is a portal server that connects people, teams, and knowledge across business processes. SharePoint Portal Server integrates information from various systems into one secure solution through single sign-on and enterprise application integration capabilities. It provides flexible deployment and management tools, and facilitates end-to-end collaboration through data aggregation, organization, and searching. SharePoint Portal Server also enables users to quickly find relevant information through customization and personalization of portal content and layout as well as through audience targeting.
What is Microsoft Windows SharePoint Services?
Windows SharePoint Services is the solution that enables you to create Web sites for information sharing and document collaboration. Windows SharePoint Services " a key piece of the information worker infrastructure delivered in Microsoft Windows Server 2003 " provides additional functionality to the Microsoft Office system and other desktop applications, and it serves as a platform for application development.
Office SharePoint Server 2007 builds on top of Windows SharePoint Services 3.0 to provide additional capabilities including collaboration, portal, search, enterprise content management, business process and forms, and business intelligence.
Office SharePoint Server 2007 builds on top of Windows SharePoint Services 3.0 to provide additional capabilities including collaboration, portal, search, enterprise content management, business process and forms, and business intelligence.
What are the advantages of jQuery
The advantages of using jQuery are:
1. JavaScript enhancement without the overhead of learning new syntax
2. Ability to keep the code simple, clear, readable and reusable
3. Eradication of the requirement of writing repetitious and complex loops and DOM scripting library calls
What is JQuery
JQuery is a light weight JavaScript library which provides fast and easy way of HTML DOM traversing and manipulation, its event handling, its client side animations, etc. One of the greatest features of jQuery is that jQuery supports an efficient way to implement AJAX applications because of its light weight nature and make normalize and efficient web programs.
Sunday, 15 March 2009
Is multiple inheritance possible in .NET
Question :Is multiple inheritance possible in .NET?
Answer:No. Multiple inheritance is not possible in .NET. This means it is not possible for one class to inherit from multiple classes. However, a class may implement multiple interfaces. We may also declare objects of different classes in a class. This way, the encapsulated class may be instantiated in other classes.
Answer:No. Multiple inheritance is not possible in .NET. This means it is not possible for one class to inherit from multiple classes. However, a class may implement multiple interfaces. We may also declare objects of different classes in a class. This way, the encapsulated class may be instantiated in other classes.
What is the difference between abstract class and interface
Question :What is the difference between abstract class and interface?
Answer :If a class is to serve the purpose of providing common fields and members to all subclasses, we create an Abstract class. For creating an abstract class, we make use of the abstract keyword. Such a class cannot be instantiated. Syntax below:
abstract public class Vehicle { }
Above, an abstract class named Vehicle has been defined. We may use the fields, properties and member functions defined within this abstract class to create child classes like Car, Truck, Bike etc. that inherit the features defined within the abstract class. To prevent directly creating an instance of the class Vehicle, we make use of the abstract keyword. To use the definitions defined in the abstract class, the child class inherits from the abstract class, and then instances of the Child class may be easily created.
Further, we may define abstract methods within an abstract class (analogous to C++ pure virtual functions) when we wish to define a method that does not have any default implementation. Its then in the hands of the descendant class to provide the details of the method. There may be any number of abstract methods in an abstract class. We define an abstract method using the abstract keyword. If we do not use the abstract keyword, and use the virtual keyword instead, we may provide an implementation of the method that can be used by the child class, but this is not an abstract method.
Remember, abstract class can have an abstract method, that does not have any implementation, for which we use the abstract keyword, OR the abstract class may have a virtual method, that can have an implementation, and can be overriden in the child class as well, using the override keyword. Read example below
Example: Abstract Class with Abstract method
namespace Automobiles
{
public abstract class Vehicle
{
public abstract void Speed() //No Implementation here, only definition
}
}
Example: Abstract Class with Virtual method
namespace Automobiles
{
public abstract class Vehicle
{
public virtual void Speed() //Can have an implementation, that may be overriden in child class
{
...
}
}
Public class Car : Vehicle
{
Public override void Speed()
//Here, we override whatever implementation is there in the abstract class
{
... //Child class implementation of the method Speed()
}
}
}
An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used. See code below:
Public interface IVehicle //As a convention, an interface is prefixed by letter I
{
Boolean HasFourWheels()
}
Time to discuss the Difference between Abstract Class and Interface
1) A class may inherit only one abstract class, but may implement multiple number of Interfaces. Say a class named Car needs to inherit some basic features of a vehicle, it may inherit from an Aabstract class named Vehicle. A car may be of any kind, it may be a vintage car, a sedan, a coupe, or a racing car. For these kind of requirements, say a car needs to have only two seats (means it is a coupe), then the class Car needs to implement a member field from an interface, that we make, say ICoupe.
2) Members of an abstract class may have any access modifier, but members of an interface are public by default, and cant have any other access modifier.
3) Abstract class methods may OR may not have an implementation, while methods in an Interface only have a definition, no implementation.
Delegate in C#
Definition:
Delegate is type which holds the method(s) reference in an object. It is also reffered as a type safe function pointers.
Advantages:
� Encapsulating the method's call from caller.
� Effective use of Delegat improves the performance of application.
� Used to call a method asynchronously.
Declaration:
public delegate type_of_delegate delegate_name()
Example : public delegate int mydelegate(int delvar1,int delvar2)
Note:
� you can use delegeate without parameter or with parameter list.
� you should follow the same syntax as in the method.
(if you are reffering the method with two int parameters and int return type the delegate which you are declaring should be the same format.This is how it is reffered as type safe function pointer)
Sample Program using Delegate :
public delegate double Delegate_Prod(int a,int b);
class Class1
{
static double fn_Prodvalues(int val1,int val2)
{
return val1*val2;
}
static void Main(string[] args)
{
//Creating the Delegate Instance
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
Console.Write("Please Enter Values");
int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());
//use a delegate for processing
double res = delObj(v1,v2);
Console.WriteLine ("Result :"+res);
Console.ReadLine();
}
}
Explanation:
Here I have used a small program which demonstrates the use of delegate.
The delegate "Delegate_Prod" is declared with double return type and which accepts only two interger parameters.
Inside the Class the method named fn_Prodvalues is defined with double return type and two integer parameters.(The delegate and method is having the same signature and
parameters type)
Inside the Main method the delegate instance is created and the function name is passed to the delegae instace as following.
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
After this we are accepting the two values from the user and passing those values to the delegate as we do using method .
delObj(v1,v2);
Here delegate object encapsulates the method functionalities and return the result as we specified in the method.
Multicast Delegate
It is a Delegate which holds the reference of more than one methods.
Multicast delegates must contain only methods that return void, else there is a run-time exception.
Simple Program using Multicast Delegate
delegate void Delegate_Multicast(int x, int y);
Class Class2
{
static void Method1(int x, int y) {
Console.WriteLine("You r in Method 1");
}
static void Method2(int x, int y) {
Console.WriteLine("You r in Method 2");
}
public static void Main()
{
Delegate_Multicast func = new Delegate_Multicast(Method1);
func += new Delegate_Multicast(Method2);
func(1,2); // Method1 and Method2 are called
func -= new Delegate_Multicast(Method1);
func(2,3); // Only Method2 is called
}
}
Explanation:
In the above example you can see that two methods are defined named method1 and method2 whchi takes two integer parameters and return type as void.
In the main method the Delegate object is created using the following statement
Delegate_Multicast func = new Delegate_Multicast(Method1);
Then the Delegate is added using the += operator and removed using -= operator.
What is an interface? How to implement an interface?
An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used.
An interface is implemented using implements keyword. A class may implement more than one keyword.
When a class inherits and implements at the same time, the inherited parent class name is written first, followed by the names of the interfaces to be implemented.
Answer :If a class is to serve the purpose of providing common fields and members to all subclasses, we create an Abstract class. For creating an abstract class, we make use of the abstract keyword. Such a class cannot be instantiated. Syntax below:
abstract public class Vehicle { }
Above, an abstract class named Vehicle has been defined. We may use the fields, properties and member functions defined within this abstract class to create child classes like Car, Truck, Bike etc. that inherit the features defined within the abstract class. To prevent directly creating an instance of the class Vehicle, we make use of the abstract keyword. To use the definitions defined in the abstract class, the child class inherits from the abstract class, and then instances of the Child class may be easily created.
Further, we may define abstract methods within an abstract class (analogous to C++ pure virtual functions) when we wish to define a method that does not have any default implementation. Its then in the hands of the descendant class to provide the details of the method. There may be any number of abstract methods in an abstract class. We define an abstract method using the abstract keyword. If we do not use the abstract keyword, and use the virtual keyword instead, we may provide an implementation of the method that can be used by the child class, but this is not an abstract method.
Remember, abstract class can have an abstract method, that does not have any implementation, for which we use the abstract keyword, OR the abstract class may have a virtual method, that can have an implementation, and can be overriden in the child class as well, using the override keyword. Read example below
Example: Abstract Class with Abstract method
namespace Automobiles
{
public abstract class Vehicle
{
public abstract void Speed() //No Implementation here, only definition
}
}
Example: Abstract Class with Virtual method
namespace Automobiles
{
public abstract class Vehicle
{
public virtual void Speed() //Can have an implementation, that may be overriden in child class
{
...
}
}
Public class Car : Vehicle
{
Public override void Speed()
//Here, we override whatever implementation is there in the abstract class
{
... //Child class implementation of the method Speed()
}
}
}
An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used. See code below:
Public interface IVehicle //As a convention, an interface is prefixed by letter I
{
Boolean HasFourWheels()
}
Time to discuss the Difference between Abstract Class and Interface
1) A class may inherit only one abstract class, but may implement multiple number of Interfaces. Say a class named Car needs to inherit some basic features of a vehicle, it may inherit from an Aabstract class named Vehicle. A car may be of any kind, it may be a vintage car, a sedan, a coupe, or a racing car. For these kind of requirements, say a car needs to have only two seats (means it is a coupe), then the class Car needs to implement a member field from an interface, that we make, say ICoupe.
2) Members of an abstract class may have any access modifier, but members of an interface are public by default, and cant have any other access modifier.
3) Abstract class methods may OR may not have an implementation, while methods in an Interface only have a definition, no implementation.
Delegate in C#
Definition:
Delegate is type which holds the method(s) reference in an object. It is also reffered as a type safe function pointers.
Advantages:
� Encapsulating the method's call from caller.
� Effective use of Delegat improves the performance of application.
� Used to call a method asynchronously.
Declaration:
public delegate type_of_delegate delegate_name()
Example : public delegate int mydelegate(int delvar1,int delvar2)
Note:
� you can use delegeate without parameter or with parameter list.
� you should follow the same syntax as in the method.
(if you are reffering the method with two int parameters and int return type the delegate which you are declaring should be the same format.This is how it is reffered as type safe function pointer)
Sample Program using Delegate :
public delegate double Delegate_Prod(int a,int b);
class Class1
{
static double fn_Prodvalues(int val1,int val2)
{
return val1*val2;
}
static void Main(string[] args)
{
//Creating the Delegate Instance
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
Console.Write("Please Enter Values");
int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());
//use a delegate for processing
double res = delObj(v1,v2);
Console.WriteLine ("Result :"+res);
Console.ReadLine();
}
}
Explanation:
Here I have used a small program which demonstrates the use of delegate.
The delegate "Delegate_Prod" is declared with double return type and which accepts only two interger parameters.
Inside the Class the method named fn_Prodvalues is defined with double return type and two integer parameters.(The delegate and method is having the same signature and
parameters type)
Inside the Main method the delegate instance is created and the function name is passed to the delegae instace as following.
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
After this we are accepting the two values from the user and passing those values to the delegate as we do using method .
delObj(v1,v2);
Here delegate object encapsulates the method functionalities and return the result as we specified in the method.
Multicast Delegate
It is a Delegate which holds the reference of more than one methods.
Multicast delegates must contain only methods that return void, else there is a run-time exception.
Simple Program using Multicast Delegate
delegate void Delegate_Multicast(int x, int y);
Class Class2
{
static void Method1(int x, int y) {
Console.WriteLine("You r in Method 1");
}
static void Method2(int x, int y) {
Console.WriteLine("You r in Method 2");
}
public static void Main()
{
Delegate_Multicast func = new Delegate_Multicast(Method1);
func += new Delegate_Multicast(Method2);
func(1,2); // Method1 and Method2 are called
func -= new Delegate_Multicast(Method1);
func(2,3); // Only Method2 is called
}
}
Explanation:
In the above example you can see that two methods are defined named method1 and method2 whchi takes two integer parameters and return type as void.
In the main method the Delegate object is created using the following statement
Delegate_Multicast func = new Delegate_Multicast(Method1);
Then the Delegate is added using the += operator and removed using -= operator.
What is an interface? How to implement an interface?
An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used.
An interface is implemented using implements keyword. A class may implement more than one keyword.
When a class inherits and implements at the same time, the inherited parent class name is written first, followed by the names of the interfaces to be implemented.
Can a class be created without a constructor
Question :Can a class be created without a constructor?
Answer :No. In case we dont define the constructor, the class will access the no-argument constructor from its base class. The compiler will make this happen during compilation.
Answer :No. In case we dont define the constructor, the class will access the no-argument constructor from its base class. The compiler will make this happen during compilation.
What is a static constructor
Question :What is a static constructor?
Answer :Static Constructor - It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below.
Example:
public class SomeClass()
{
static SomeClass()
{
//Static members may be accessed from here
//Code for Initialization
}
}
While creating a static constructor, a few things need to be kept in mind:
* There is no access modifier require to define a static constructor
* There may be only one static constructor in a class
* The static constructor may not have any parameters
* This constructor may only access the static members of the class
* We may create more than one static constructor for a class
Answer :Static Constructor - It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below.
Example:
public class SomeClass()
{
static SomeClass()
{
//Static members may be accessed from here
//Code for Initialization
}
}
While creating a static constructor, a few things need to be kept in mind:
* There is no access modifier require to define a static constructor
* There may be only one static constructor in a class
* The static constructor may not have any parameters
* This constructor may only access the static members of the class
* We may create more than one static constructor for a class
What is a static constructor
Question :What is a static constructor?
Answer :Static Constructor - It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below.
Example:
public class SomeClass()
{
static SomeClass()
{
//Static members may be accessed from here
//Code for Initialization
}
}
While creating a static constructor, a few things need to be kept in mind:
* There is no access modifier require to define a static constructor
* There may be only one static constructor in a class
* The static constructor may not have any parameters
* This constructor may only access the static members of the class
* We may create more than one static constructor for a class
Answer :Static Constructor - It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below.
Example:
public class SomeClass()
{
static SomeClass()
{
//Static members may be accessed from here
//Code for Initialization
}
}
While creating a static constructor, a few things need to be kept in mind:
* There is no access modifier require to define a static constructor
* There may be only one static constructor in a class
* The static constructor may not have any parameters
* This constructor may only access the static members of the class
* We may create more than one static constructor for a class
What is the difference between Overriding and Shadowing
Question :What is the difference between Overriding and Shadowing?
Answer :Both Overriding and Shadowing are ways to alter the behaviour of members of a base class. Shadowing is a VB.NET concept. In C#, this concept is called Hiding, though there is a difference between the two.
When we do shadowing, we provide a new implementation to the base class member without overriding it. We may shadow a base class member in a derived class, by using the keyword shadows. The access level, return type, and the signature (means the datatypes of the arguments passed & the order of the types) of the derived class members which are shadowed, may differ from the base class.
In C#, we may achieve shadowing using the keyword new. However, when Hiding in C#, the access level, the signature, return type of the derived class must be same as the base class.
Overriding is the concept of providing a new implementation of derived class member as compared to its based class. In VB.NET, we do overriding using the overrides keyword, while in C#, overriding is achieved using the override keyword. For a class member to be overridable, we use the keyword virtual while defining it (in C#), and we use the keyword overridable (in VB.NET), though if we leave out specifying the overridable keyword, the member is overridable by default.
Answer :Both Overriding and Shadowing are ways to alter the behaviour of members of a base class. Shadowing is a VB.NET concept. In C#, this concept is called Hiding, though there is a difference between the two.
When we do shadowing, we provide a new implementation to the base class member without overriding it. We may shadow a base class member in a derived class, by using the keyword shadows. The access level, return type, and the signature (means the datatypes of the arguments passed & the order of the types) of the derived class members which are shadowed, may differ from the base class.
In C#, we may achieve shadowing using the keyword new. However, when Hiding in C#, the access level, the signature, return type of the derived class must be same as the base class.
Overriding is the concept of providing a new implementation of derived class member as compared to its based class. In VB.NET, we do overriding using the overrides keyword, while in C#, overriding is achieved using the override keyword. For a class member to be overridable, we use the keyword virtual while defining it (in C#), and we use the keyword overridable (in VB.NET), though if we leave out specifying the overridable keyword, the member is overridable by default.
What is the difference between Shared and Static
Question :What is the difference between Shared and Static?
Answer :They both mean the same. Shared is used in VB.NET. Static is used in C#.
When the static keyword is used to declare a class, the member in context must be directly invoked from the class, rather than from the instance. Consider the following example
//Consider writing the following line of code...
Console obj = new Console();
obj.Writeline("Vishal likes static members"); //This line does'nt print
//This does'nt work, because WriteLine is a static method defined in the class Console
//The Console class is a static class
To use static members, give a reference to the exact class, as an instance in this case won't work.
To make this work, write...
Console.Writeline("Vishal likes static members");
To work with members of static classes, no need to create their instances.
Static Member - A class member declared with the keyword static is a static member. A static member is owned by the class, not by its instances (objects of the class).
Note that static members are actually class members, while non-static members are instance members (means they are owned by the instances). Both in C# & VB.NET, we may create static/shared events, properties, fields and functions.
Note Indexers in C# cannot be declared static.
Note Static member functions cannot access non-static members directly.
Virtual - If a base class method is to be overriden, it is defined using the keyword virtual (otherwise the sealed keyword is used to prevent overriding).
Note that the class member method may be overriden even if the virtual keyword is not used, but its usage makes the code more transparent & meaningful. In VB.NET, we may use the overridable keyword for this purpose.
When the override keyword is used to override the virtual method, in a scenario where the base class method is required in a child class along with the overriden method, then the base keyword may be used to access the parent class member. The following code example will make the usage more clear.
public class Employee
{
public virtual void SetBasic(float money) //This method may be overriden
{ Basic += money; }
}
public class Manager : Employee
{
public override void SetBasic(float money) //This method is being overriden
{
float managerIncentive = 10000;
base.SetSalary(money + managerIncentive); //Calling base class method
}
}
Explain overridable, overrides, notoverridable,mustoverride
These keywords are used in VB.NET.
Overridable -The Overridable keyword is used when defining a property or method of an inherited class, as overridable by the inheriting class.
Overides - The Overides keyword allows the inheriting class to disregard the property or method of the inherited class and implements ts own code.
NotOverridable - The NotOverridable keyword explicitly declares a property or method as not overridable by an inheriting class, and all properties are "not overridable" by default. The only real advantage to using this keyword is to make your code more readable.
MustOverride - The MustOverride keyword forces the inheriting class to implement its own code for the property or method.
Answer :They both mean the same. Shared is used in VB.NET. Static is used in C#.
When the static keyword is used to declare a class, the member in context must be directly invoked from the class, rather than from the instance. Consider the following example
//Consider writing the following line of code...
Console obj = new Console();
obj.Writeline("Vishal likes static members"); //This line does'nt print
//This does'nt work, because WriteLine is a static method defined in the class Console
//The Console class is a static class
To use static members, give a reference to the exact class, as an instance in this case won't work.
To make this work, write...
Console.Writeline("Vishal likes static members");
To work with members of static classes, no need to create their instances.
Static Member - A class member declared with the keyword static is a static member. A static member is owned by the class, not by its instances (objects of the class).
Note that static members are actually class members, while non-static members are instance members (means they are owned by the instances). Both in C# & VB.NET, we may create static/shared events, properties, fields and functions.
Note Indexers in C# cannot be declared static.
Note Static member functions cannot access non-static members directly.
Virtual - If a base class method is to be overriden, it is defined using the keyword virtual (otherwise the sealed keyword is used to prevent overriding).
Note that the class member method may be overriden even if the virtual keyword is not used, but its usage makes the code more transparent & meaningful. In VB.NET, we may use the overridable keyword for this purpose.
When the override keyword is used to override the virtual method, in a scenario where the base class method is required in a child class along with the overriden method, then the base keyword may be used to access the parent class member. The following code example will make the usage more clear.
public class Employee
{
public virtual void SetBasic(float money) //This method may be overriden
{ Basic += money; }
}
public class Manager : Employee
{
public override void SetBasic(float money) //This method is being overriden
{
float managerIncentive = 10000;
base.SetSalary(money + managerIncentive); //Calling base class method
}
}
Explain overridable, overrides, notoverridable,mustoverride
These keywords are used in VB.NET.
Overridable -The Overridable keyword is used when defining a property or method of an inherited class, as overridable by the inheriting class.
Overides - The Overides keyword allows the inheriting class to disregard the property or method of the inherited class and implements ts own code.
NotOverridable - The NotOverridable keyword explicitly declares a property or method as not overridable by an inheriting class, and all properties are "not overridable" by default. The only real advantage to using this keyword is to make your code more readable.
MustOverride - The MustOverride keyword forces the inheriting class to implement its own code for the property or method.
What is Overloading What is Overloads What is Overload
Question :What is Overloading? What is Overloads? What is Overload?
Answer :Overloading - is the concept of using one function or class in different ways by changing the signature of its parameters. We can define a function with multiple signatures without using the keyword Overloads, but if you use the Overloads keyword in one, you must use it in all of the function's Overloaded signatures.
The Overloads keyword is used in VB.NET, while the Overload keyword is used in C# (There is no other difference). The Overloads property allows a function to be described using deferent combinations of parameters. Each combination is considered a signature, thereby uniquely defining an instance of the method being defined.
Overloading is a way through which polymorphism is achieved.
Answer :Overloading - is the concept of using one function or class in different ways by changing the signature of its parameters. We can define a function with multiple signatures without using the keyword Overloads, but if you use the Overloads keyword in one, you must use it in all of the function's Overloaded signatures.
The Overloads keyword is used in VB.NET, while the Overload keyword is used in C# (There is no other difference). The Overloads property allows a function to be described using deferent combinations of parameters. Each combination is considered a signature, thereby uniquely defining an instance of the method being defined.
Overloading is a way through which polymorphism is achieved.
What is polymorphism
Question :What is polymorphism?
Answer :Polymorphism means allowing a single definition to be used with different types of data (specifically, different classes of objects). For example, a polymorphic function definition can replace several type-specific ones, and a single polymorphic operator can act in expressions of various types. Many programming languages implement some forms of polymorphism.
The concept of polymorphism applies to data types in addition to functions. A function that can evaluate to and be applied to values of different types is known as a polymorphic function. A data type that contains elements of different types is known as a polymorphic data type.
Polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context.
Example:
Public Class Calc
{
public void fnMultiply(int x, int y)
{ return x * y; }
public void fnMultiply(int x, int y, int z)
{ return x * y * z; }
}
...
...
Calc obj;
int Result;
Result = obj.fnMultiply(2,3,4); // The second fnMultiply would be called
Result = obj.fnMultiply(3,4); // The first fnMultiply would be called
//Here, the call depends on the number of parameters passed, polymorphism is achieved using overloading
Answer :Polymorphism means allowing a single definition to be used with different types of data (specifically, different classes of objects). For example, a polymorphic function definition can replace several type-specific ones, and a single polymorphic operator can act in expressions of various types. Many programming languages implement some forms of polymorphism.
The concept of polymorphism applies to data types in addition to functions. A function that can evaluate to and be applied to values of different types is known as a polymorphic function. A data type that contains elements of different types is known as a polymorphic data type.
Polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context.
Example:
Public Class Calc
{
public void fnMultiply(int x, int y)
{ return x * y; }
public void fnMultiply(int x, int y, int z)
{ return x * y * z; }
}
...
...
Calc obj;
int Result;
Result = obj.fnMultiply(2,3,4); // The second fnMultiply would be called
Result = obj.fnMultiply(3,4); // The first fnMultiply would be called
//Here, the call depends on the number of parameters passed, polymorphism is achieved using overloading
Is multiple inheritance possible in .NET
Question :Is multiple inheritance possible in .NET?
Answer:No. Multiple inheritance is not possible in .NET. This means it is not possible for one class to inherit from multiple classes. However, a class may implement multiple interfaces. We may also declare objects of different classes in a class. This way, the encapsulated class may be instantiated in other classes.
Answer:No. Multiple inheritance is not possible in .NET. This means it is not possible for one class to inherit from multiple classes. However, a class may implement multiple interfaces. We may also declare objects of different classes in a class. This way, the encapsulated class may be instantiated in other classes.
What is the difference between abstract class and interface
:If a class is to serve the purpose of providing common fields and members to all subclasses, we create an Abstract class.
For creating an abstract class, we make use of the abstract keyword. Such a class cannot be instantiated. Syntax below:
abstract public class Vehicle { }
Above, an abstract class named Vehicle has been defined. We may use the fields, properties and member functions defined within this abstract class to create child classes like Car, Truck, Bike etc. that inherit the features defined within the abstract class. To prevent directly creating an instance of the class Vehicle, we make use of the abstract keyword. To use the definitions defined in the abstract class, the child class inherits from the abstract class, and then instances of the Child class may be easily created.
Further, we may define abstract methods within an abstract class (analogous to C++ pure virtual functions) when we wish to define a method that does not have any default implementation. Its then in the hands of the descendant class to provide the details of the method. There may be any number of abstract methods in an abstract class. We define an abstract method using the abstract keyword. If we do not use the abstract keyword, and use the virtual keyword instead, we may provide an implementation of the method that can be used by the child class, but this is not an abstract method.
Remember, abstract class can have an abstract method, that does not have any implementation, for which we use the abstract keyword, OR the abstract class may have a virtual method, that can have an implementation, and can be overriden in the child class as well, using the override keyword. Read example below
Example: Abstract Class with Abstract method
namespace Automobiles
{
public abstract class Vehicle
{
public abstract void Speed() //No Implementation here, only definition
}
}
Example: Abstract Class with Virtual method
namespace Automobiles
{
public abstract class Vehicle
{
public virtual void Speed() //Can have an implementation, that may be overriden in child class
{
...
}
}
Public class Car : Vehicle
{
Public override void Speed()
//Here, we override whatever implementation is there in the abstract class
{
... //Child class implementation of the method Speed()
}
}
}
An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used. See code below:
Public interface IVehicle //As a convention, an interface is prefixed by letter I
{
Boolean HasFourWheels()
}
Time to discuss the Difference between Abstract Class and Interface
1) A class may inherit only one abstract class, but may implement multiple number of Interfaces. Say a class named Car needs to inherit some basic features of a vehicle, it may inherit from an Aabstract class named Vehicle. A car may be of any kind, it may be a vintage car, a sedan, a coupe, or a racing car. For these kind of requirements, say a car needs to have only two seats (means it is a coupe), then the class Car needs to implement a member field from an interface, that we make, say ICoupe.
2) Members of an abstract class may have any access modifier, but members of an interface are public by default, and cant have any other access modifier.
3) Abstract class methods may OR may not have an implementation, while methods in an Interface only have a definition, no implementation.
Delegate in C#
Definition:
Delegate is type which holds the method(s) reference in an object. It is also reffered as a type safe function pointers.
Advantages:
� Encapsulating the method's call from caller.
� Effective use of Delegat improves the performance of application.
� Used to call a method asynchronously.
Declaration:
public delegate type_of_delegate delegate_name()
Example : public delegate int mydelegate(int delvar1,int delvar2)
Note:
� you can use delegeate without parameter or with parameter list.
� you should follow the same syntax as in the method.
(if you are reffering the method with two int parameters and int return type the delegate which you are declaring should be the same format.This is how it is reffered as type safe function pointer)
Sample Program using Delegate :
public delegate double Delegate_Prod(int a,int b);
class Class1
{
static double fn_Prodvalues(int val1,int val2)
{
return val1*val2;
}
static void Main(string[] args)
{
//Creating the Delegate Instance
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
Console.Write("Please Enter Values");
int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());
//use a delegate for processing
double res = delObj(v1,v2);
Console.WriteLine ("Result :"+res);
Console.ReadLine();
}
}
Explanation:
Here I have used a small program which demonstrates the use of delegate.
The delegate "Delegate_Prod" is declared with double return type and which accepts only two interger parameters.
Inside the Class the method named fn_Prodvalues is defined with double return type and two integer parameters.(The delegate and method is having the same signature and
parameters type)
Inside the Main method the delegate instance is created and the function name is passed to the delegae instace as following.
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
After this we are accepting the two values from the user and passing those values to the delegate as we do using method .
delObj(v1,v2);
Here delegate object encapsulates the method functionalities and return the result as we specified in the method.
Multicast Delegate
It is a Delegate which holds the reference of more than one methods.
Multicast delegates must contain only methods that return void, else there is a run-time exception.
Simple Program using Multicast Delegate
delegate void Delegate_Multicast(int x, int y);
Class Class2
{
static void Method1(int x, int y) {
Console.WriteLine("You r in Method 1");
}
static void Method2(int x, int y) {
Console.WriteLine("You r in Method 2");
}
public static void Main()
{
Delegate_Multicast func = new Delegate_Multicast(Method1);
func += new Delegate_Multicast(Method2);
func(1,2); // Method1 and Method2 are called
func -= new Delegate_Multicast(Method1);
func(2,3); // Only Method2 is called
}
}
Explanation:
In the above example you can see that two methods are defined named method1 and method2 whchi takes two integer parameters and return type as void.
In the main method the Delegate object is created using the following statement
Delegate_Multicast func = new Delegate_Multicast(Method1);
Then the Delegate is added using the += operator and removed using -= operator.
What is an interface? How to implement an interface?
An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used.
An interface is implemented using implements keyword. A class may implement more than one keyword.
When a class inherits and implements at the same time, the inherited parent class name is written first, followed by the names of the interfaces to be implemented.
For creating an abstract class, we make use of the abstract keyword. Such a class cannot be instantiated. Syntax below:
abstract public class Vehicle { }
Above, an abstract class named Vehicle has been defined. We may use the fields, properties and member functions defined within this abstract class to create child classes like Car, Truck, Bike etc. that inherit the features defined within the abstract class. To prevent directly creating an instance of the class Vehicle, we make use of the abstract keyword. To use the definitions defined in the abstract class, the child class inherits from the abstract class, and then instances of the Child class may be easily created.
Further, we may define abstract methods within an abstract class (analogous to C++ pure virtual functions) when we wish to define a method that does not have any default implementation. Its then in the hands of the descendant class to provide the details of the method. There may be any number of abstract methods in an abstract class. We define an abstract method using the abstract keyword. If we do not use the abstract keyword, and use the virtual keyword instead, we may provide an implementation of the method that can be used by the child class, but this is not an abstract method.
Remember, abstract class can have an abstract method, that does not have any implementation, for which we use the abstract keyword, OR the abstract class may have a virtual method, that can have an implementation, and can be overriden in the child class as well, using the override keyword. Read example below
Example: Abstract Class with Abstract method
namespace Automobiles
{
public abstract class Vehicle
{
public abstract void Speed() //No Implementation here, only definition
}
}
Example: Abstract Class with Virtual method
namespace Automobiles
{
public abstract class Vehicle
{
public virtual void Speed() //Can have an implementation, that may be overriden in child class
{
...
}
}
Public class Car : Vehicle
{
Public override void Speed()
//Here, we override whatever implementation is there in the abstract class
{
... //Child class implementation of the method Speed()
}
}
}
An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used. See code below:
Public interface IVehicle //As a convention, an interface is prefixed by letter I
{
Boolean HasFourWheels()
}
Time to discuss the Difference between Abstract Class and Interface
1) A class may inherit only one abstract class, but may implement multiple number of Interfaces. Say a class named Car needs to inherit some basic features of a vehicle, it may inherit from an Aabstract class named Vehicle. A car may be of any kind, it may be a vintage car, a sedan, a coupe, or a racing car. For these kind of requirements, say a car needs to have only two seats (means it is a coupe), then the class Car needs to implement a member field from an interface, that we make, say ICoupe.
2) Members of an abstract class may have any access modifier, but members of an interface are public by default, and cant have any other access modifier.
3) Abstract class methods may OR may not have an implementation, while methods in an Interface only have a definition, no implementation.
Delegate in C#
Definition:
Delegate is type which holds the method(s) reference in an object. It is also reffered as a type safe function pointers.
Advantages:
� Encapsulating the method's call from caller.
� Effective use of Delegat improves the performance of application.
� Used to call a method asynchronously.
Declaration:
public delegate type_of_delegate delegate_name()
Example : public delegate int mydelegate(int delvar1,int delvar2)
Note:
� you can use delegeate without parameter or with parameter list.
� you should follow the same syntax as in the method.
(if you are reffering the method with two int parameters and int return type the delegate which you are declaring should be the same format.This is how it is reffered as type safe function pointer)
Sample Program using Delegate :
public delegate double Delegate_Prod(int a,int b);
class Class1
{
static double fn_Prodvalues(int val1,int val2)
{
return val1*val2;
}
static void Main(string[] args)
{
//Creating the Delegate Instance
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
Console.Write("Please Enter Values");
int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());
//use a delegate for processing
double res = delObj(v1,v2);
Console.WriteLine ("Result :"+res);
Console.ReadLine();
}
}
Explanation:
Here I have used a small program which demonstrates the use of delegate.
The delegate "Delegate_Prod" is declared with double return type and which accepts only two interger parameters.
Inside the Class the method named fn_Prodvalues is defined with double return type and two integer parameters.(The delegate and method is having the same signature and
parameters type)
Inside the Main method the delegate instance is created and the function name is passed to the delegae instace as following.
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
After this we are accepting the two values from the user and passing those values to the delegate as we do using method .
delObj(v1,v2);
Here delegate object encapsulates the method functionalities and return the result as we specified in the method.
Multicast Delegate
It is a Delegate which holds the reference of more than one methods.
Multicast delegates must contain only methods that return void, else there is a run-time exception.
Simple Program using Multicast Delegate
delegate void Delegate_Multicast(int x, int y);
Class Class2
{
static void Method1(int x, int y) {
Console.WriteLine("You r in Method 1");
}
static void Method2(int x, int y) {
Console.WriteLine("You r in Method 2");
}
public static void Main()
{
Delegate_Multicast func = new Delegate_Multicast(Method1);
func += new Delegate_Multicast(Method2);
func(1,2); // Method1 and Method2 are called
func -= new Delegate_Multicast(Method1);
func(2,3); // Only Method2 is called
}
}
Explanation:
In the above example you can see that two methods are defined named method1 and method2 whchi takes two integer parameters and return type as void.
In the main method the Delegate object is created using the following statement
Delegate_Multicast func = new Delegate_Multicast(Method1);
Then the Delegate is added using the += operator and removed using -= operator.
What is an interface? How to implement an interface?
An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used.
An interface is implemented using implements keyword. A class may implement more than one keyword.
When a class inherits and implements at the same time, the inherited parent class name is written first, followed by the names of the interfaces to be implemented.
Can a class be created without a constructor
Question :Can a class be created without a constructor?
Answer :No. In case we dont define the constructor, the class will access the no-argument constructor from its base class. The compiler will make this happen during compilation.
Answer :No. In case we dont define the constructor, the class will access the no-argument constructor from its base class. The compiler will make this happen during compilation.
What is a static constructor
It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See example below.
Example:
public class SomeClass()
{
static SomeClass()
{
//Static members may be accessed from here
//Code for Initialization
}
}
While creating a static constructor, a few things need to be kept in mind:
* There is no access modifier require to define a static constructor
* There may be only one static constructor in a class
* The static constructor may not have any parameters
* This constructor may only access the static members of the class
* We may create more than one static constructor for a class
Example:
public class SomeClass()
{
static SomeClass()
{
//Static members may be accessed from here
//Code for Initialization
}
}
While creating a static constructor, a few things need to be kept in mind:
* There is no access modifier require to define a static constructor
* There may be only one static constructor in a class
* The static constructor may not have any parameters
* This constructor may only access the static members of the class
* We may create more than one static constructor for a class
What is the difference between Overriding and Shadowing
Both Overriding and Shadowing are ways to alter the behaviour of members of a base class. Shadowing is a VB.NET concept. In C#, this concept is called Hiding, though there is a difference between the two.
When we do shadowing, we provide a new implementation to the base class member without overriding it. We may shadow a base class member in a derived class, by using the keyword shadows. The access level, return type, and the signature (means the datatypes of the arguments passed & the order of the types) of the derived class members which are shadowed, may differ from the base class.
In C#, we may achieve shadowing using the keyword new. However, when Hiding in C#, the access level, the signature, return type of the derived class must be same as the base class.
Overriding is the concept of providing a new implementation of derived class member as compared to its based class. In VB.NET, we do overriding using the overrides keyword, while in C#, overriding is achieved using the override keyword. For a class member to be overridable, we use the keyword virtual while defining it (in C#), and we use the keyword overridable (in VB.NET), though if we leave out specifying the overridable keyword, the member is overridable by default.
When we do shadowing, we provide a new implementation to the base class member without overriding it. We may shadow a base class member in a derived class, by using the keyword shadows. The access level, return type, and the signature (means the datatypes of the arguments passed & the order of the types) of the derived class members which are shadowed, may differ from the base class.
In C#, we may achieve shadowing using the keyword new. However, when Hiding in C#, the access level, the signature, return type of the derived class must be same as the base class.
Overriding is the concept of providing a new implementation of derived class member as compared to its based class. In VB.NET, we do overriding using the overrides keyword, while in C#, overriding is achieved using the override keyword. For a class member to be overridable, we use the keyword virtual while defining it (in C#), and we use the keyword overridable (in VB.NET), though if we leave out specifying the overridable keyword, the member is overridable by default.
What is the difference between Shared and Static ??
Answer :They both mean the same. Shared is used in VB.NET. Static is used in C#.
When the static keyword is used to declare a class, the member in context must be directly invoked from the class, rather than from the instance. Consider the following example
//Consider writing the following line of code...
Console obj = new Console();
obj.Writeline("Vishal likes static members"); //This line does'nt print
//This does'nt work, because WriteLine is a static method defined in the class Console
//The Console class is a static class
To use static members, give a reference to the exact class, as an instance in this case won't work.
To make this work, write...
Console.Writeline("Vishal likes static members");
To work with members of static classes, no need to create their instances.
Static Member - A class member declared with the keyword static is a static member. A static member is owned by the class, not by its instances (objects of the class).
Note that static members are actually class members, while non-static members are instance members (means they are owned by the instances). Both in C# & VB.NET, we may create static/shared events, properties, fields and functions.
Note Indexers in C# cannot be declared static.
Note Static member functions cannot access non-static members directly.
Virtual - If a base class method is to be overriden, it is defined using the keyword virtual (otherwise the sealed keyword is used to prevent overriding).
Note that the class member method may be overriden even if the virtual keyword is not used, but its usage makes the code more transparent & meaningful. In VB.NET, we may use the overridable keyword for this purpose.
When the override keyword is used to override the virtual method, in a scenario where the base class method is required in a child class along with the overriden method, then the base keyword may be used to access the parent class member. The following code example will make the usage more clear.
public class Employee
{
public virtual void SetBasic(float money) //This method may be overriden
{ Basic += money; }
}
public class Manager : Employee
{
public override void SetBasic(float money) //This method is being overriden
{
float managerIncentive = 10000;
base.SetSalary(money + managerIncentive); //Calling base class method
}
}
Explain overridable, overrides, notoverridable,mustoverride
These keywords are used in VB.NET.
Overridable -The Overridable keyword is used when defining a property or method of an inherited class, as overridable by the inheriting class.
Overides - The Overides keyword allows the inheriting class to disregard the property or method of the inherited class and implements ts own code.
NotOverridable - The NotOverridable keyword explicitly declares a property or method as not overridable by an inheriting class, and all properties are "not overridable" by default. The only real advantage to using this keyword is to make your code more readable.
MustOverride - The MustOverride keyword forces the inheriting class to implement its own code for the property or method.
When the static keyword is used to declare a class, the member in context must be directly invoked from the class, rather than from the instance. Consider the following example
//Consider writing the following line of code...
Console obj = new Console();
obj.Writeline("Vishal likes static members"); //This line does'nt print
//This does'nt work, because WriteLine is a static method defined in the class Console
//The Console class is a static class
To use static members, give a reference to the exact class, as an instance in this case won't work.
To make this work, write...
Console.Writeline("Vishal likes static members");
To work with members of static classes, no need to create their instances.
Static Member - A class member declared with the keyword static is a static member. A static member is owned by the class, not by its instances (objects of the class).
Note that static members are actually class members, while non-static members are instance members (means they are owned by the instances). Both in C# & VB.NET, we may create static/shared events, properties, fields and functions.
Note Indexers in C# cannot be declared static.
Note Static member functions cannot access non-static members directly.
Virtual - If a base class method is to be overriden, it is defined using the keyword virtual (otherwise the sealed keyword is used to prevent overriding).
Note that the class member method may be overriden even if the virtual keyword is not used, but its usage makes the code more transparent & meaningful. In VB.NET, we may use the overridable keyword for this purpose.
When the override keyword is used to override the virtual method, in a scenario where the base class method is required in a child class along with the overriden method, then the base keyword may be used to access the parent class member. The following code example will make the usage more clear.
public class Employee
{
public virtual void SetBasic(float money) //This method may be overriden
{ Basic += money; }
}
public class Manager : Employee
{
public override void SetBasic(float money) //This method is being overriden
{
float managerIncentive = 10000;
base.SetSalary(money + managerIncentive); //Calling base class method
}
}
Explain overridable, overrides, notoverridable,mustoverride
These keywords are used in VB.NET.
Overridable -The Overridable keyword is used when defining a property or method of an inherited class, as overridable by the inheriting class.
Overides - The Overides keyword allows the inheriting class to disregard the property or method of the inherited class and implements ts own code.
NotOverridable - The NotOverridable keyword explicitly declares a property or method as not overridable by an inheriting class, and all properties are "not overridable" by default. The only real advantage to using this keyword is to make your code more readable.
MustOverride - The MustOverride keyword forces the inheriting class to implement its own code for the property or method.
What is polymorphism
Polymorphism means allowing a single definition to be used with different types of data (specifically, different classes of objects). For example, a polymorphic function definition can replace several type-specific ones, and a single polymorphic operator can act in expressions of various types. Many programming languages implement some forms of polymorphism.
The concept of polymorphism applies to data types in addition to functions. A function that can evaluate to and be applied to values of different types is known as a polymorphic function. A data type that contains elements of different types is known as a polymorphic data type.
Polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context.
Example:
Public Class Calc
{
public void fnMultiply(int x, int y)
{ return x * y; }
public void fnMultiply(int x, int y, int z)
{ return x * y * z; }
}
...
...
Calc obj;
int Result;
Result = obj.fnMultiply(2,3,4); // The second fnMultiply would be called
Result = obj.fnMultiply(3,4); // The first fnMultiply would be called
//Here, the call depends on the number of parameters passed, polymorphism is achieved using overloading
The concept of polymorphism applies to data types in addition to functions. A function that can evaluate to and be applied to values of different types is known as a polymorphic function. A data type that contains elements of different types is known as a polymorphic data type.
Polymorphism may be achieved by overloading a function, overloading an operator, changing the order of types, changing the types using the same name for the member in context.
Example:
Public Class Calc
{
public void fnMultiply(int x, int y)
{ return x * y; }
public void fnMultiply(int x, int y, int z)
{ return x * y * z; }
}
...
...
Calc obj;
int Result;
Result = obj.fnMultiply(2,3,4); // The second fnMultiply would be called
Result = obj.fnMultiply(3,4); // The first fnMultiply would be called
//Here, the call depends on the number of parameters passed, polymorphism is achieved using overloading
Whats the difference between a class and an object
Question :Whats the difference between a class and an object?
Answer :In any object Oriented language, an object is the backbone of everything that we see. A class is a blueprint that describes how an instance of it (object) will behave. To create a class, we define it in a "Code File", with an extension *.cs or *.vb. We make use of the keyword class.
Example
Lets create a class named Laptop
public class Laptop
{
private string sbrand;
public Laptop() {}
public Laptop(string name)
{
sbrand = name;
}
}
From our code that references this class, we write...
Laptop lp = new Laptop("Lenovo"); //Passing a variable to the class constructor
Once the class object is created, the object may be used to invoke the member functions defined within the class. We may allocate any number of objects using the new keyword. The new keyword returns a reference to an object on the heap. This reference is not to the actual object itself. The variable being refered is stored on a stack for usage in the application. When we allocate an object to a heap, its managed by the .NET runtime. The garbage collector takes care of the object by removing it from the heap, when it is no longer reachable by any part of the code.
Answer :In any object Oriented language, an object is the backbone of everything that we see. A class is a blueprint that describes how an instance of it (object) will behave. To create a class, we define it in a "Code File", with an extension *.cs or *.vb. We make use of the keyword class.
Example
Lets create a class named Laptop
public class Laptop
{
private string sbrand;
public Laptop() {}
public Laptop(string name)
{
sbrand = name;
}
}
From our code that references this class, we write...
Laptop lp = new Laptop("Lenovo"); //Passing a variable to the class constructor
Once the class object is created, the object may be used to invoke the member functions defined within the class. We may allocate any number of objects using the new keyword. The new keyword returns a reference to an object on the heap. This reference is not to the actual object itself. The variable being refered is stored on a stack for usage in the application. When we allocate an object to a heap, its managed by the .NET runtime. The garbage collector takes care of the object by removing it from the heap, when it is no longer reachable by any part of the code.
Whats the difference between a class and an object
In any object Oriented language, an object is the backbone of everything that we see. A class is a blueprint that describes how an instance of it (object) will behave. To create a class, we define it in a "Code File", with an extension *.cs or *.vb. We make use of the keyword class.
Example
Lets create a class named Laptop
public class Laptop
{
private string sbrand;
public Laptop() {}
public Laptop(string name)
{
sbrand = name;
}
}
From our code that references this class, we write...
Laptop lp = new Laptop("Lenovo"); //Passing a variable to the class constructor
Once the class object is created, the object may be used to invoke the member functions defined within the class. We may allocate any number of objects using the new keyword. The new keyword returns a reference to an object on the heap. This reference is not to the actual object itself. The variable being refered is stored on a stack for usage in the application. When we allocate an object to a heap, its managed by the .NET runtime. The garbage collector takes care of the object by removing it from the heap, when it is no longer reachable by any part of the code.
Example
Lets create a class named Laptop
public class Laptop
{
private string sbrand;
public Laptop() {}
public Laptop(string name)
{
sbrand = name;
}
}
From our code that references this class, we write...
Laptop lp = new Laptop("Lenovo"); //Passing a variable to the class constructor
Once the class object is created, the object may be used to invoke the member functions defined within the class. We may allocate any number of objects using the new keyword. The new keyword returns a reference to an object on the heap. This reference is not to the actual object itself. The variable being refered is stored on a stack for usage in the application. When we allocate an object to a heap, its managed by the .NET runtime. The garbage collector takes care of the object by removing it from the heap, when it is no longer reachable by any part of the code.
What is a class member What is an object
Question :What is a class member? What is an object?
Answer :The entities like events, properties, fields and functions encapsulated within a class are called class members. A constructor of a class that resides within it is also a form of a class member.
When we instantiate a class in order to use its encapsulated class members, this instantiated class entity is called the object.
Answer :The entities like events, properties, fields and functions encapsulated within a class are called class members. A constructor of a class that resides within it is also a form of a class member.
When we instantiate a class in order to use its encapsulated class members, this instantiated class entity is called the object.
What is a class member What is an object
What is a class member? What is an object?
Answer :The entities like events, properties, fields and functions encapsulated within a class are called class members. A constructor of a class that resides within it is also a form of a class member.
When we instantiate a class in order to use its encapsulated class members, this instantiated class entity is called the object.
Answer :The entities like events, properties, fields and functions encapsulated within a class are called class members. A constructor of a class that resides within it is also a form of a class member.
When we instantiate a class in order to use its encapsulated class members, this instantiated class entity is called the object.
What is inheritance
Question :What is inheritance?
Answer :Inheritance - is the concept of passing the traits of a class to another class.
A class comprises of a collection of types of encapsulated instance variables and types of methods, events, properties, possibly with implementation of those types together with a constructor function that can be used to create objects of the class. A class is a cohesive package that comprises of a particular kind of compile-time metadata. A Class describes the rules by which objects behave; these objects are referred to as "instances" of that class. (Reference)
Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit from�the base class�after the colon. (Reference)
Answer :Inheritance - is the concept of passing the traits of a class to another class.
A class comprises of a collection of types of encapsulated instance variables and types of methods, events, properties, possibly with implementation of those types together with a constructor function that can be used to create objects of the class. A class is a cohesive package that comprises of a particular kind of compile-time metadata. A Class describes the rules by which objects behave; these objects are referred to as "instances" of that class. (Reference)
Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit from�the base class�after the colon. (Reference)
What is inheritance
Answer :Inheritance - is the concept of passing the traits of a class to another class.
A class comprises of a collection of types of encapsulated instance variables and types of methods, events, properties, possibly with implementation of those types together with a constructor function that can be used to create objects of the class. A class is a cohesive package that comprises of a particular kind of compile-time metadata. A Class describes the rules by which objects behave; these objects are referred to as "instances" of that class. (Reference)
Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit from�the base class�after the colon. (Reference)
A class comprises of a collection of types of encapsulated instance variables and types of methods, events, properties, possibly with implementation of those types together with a constructor function that can be used to create objects of the class. A class is a cohesive package that comprises of a particular kind of compile-time metadata. A Class describes the rules by which objects behave; these objects are referred to as "instances" of that class. (Reference)
Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit from�the base class�after the colon. (Reference)
What is Class
qUESTION :What is Class?
aNSWER :A class is an organized store-house in object-oriented programming that gives coherent functional abilities to a group of related code. It is the definition of an object, made up of software code. Using classes, we may wrap data and behaviour together (Encapsulation). We may define classes in terms of classes (Inheritance). We can also override the behaviour of a class using an alternate behaviour (Polymorphism).
A Base Class is a class that is inherited by another class. In .NET, a class may inherit from only one class.
aNSWER :A class is an organized store-house in object-oriented programming that gives coherent functional abilities to a group of related code. It is the definition of an object, made up of software code. Using classes, we may wrap data and behaviour together (Encapsulation). We may define classes in terms of classes (Inheritance). We can also override the behaviour of a class using an alternate behaviour (Polymorphism).
A Base Class is a class that is inherited by another class. In .NET, a class may inherit from only one class.
What is Class
What is Class?
A class is an organized store-house in object-oriented programming that gives coherent functional abilities to a group of related code. It is the definition of an object, made up of software code. Using classes, we may wrap data and behaviour together (Encapsulation). We may define classes in terms of classes (Inheritance). We can also override the behaviour of a class using an alternate behaviour (Polymorphism).
A Base Class is a class that is inherited by another class. In .NET, a class may inherit from only one class.
A class is an organized store-house in object-oriented programming that gives coherent functional abilities to a group of related code. It is the definition of an object, made up of software code. Using classes, we may wrap data and behaviour together (Encapsulation). We may define classes in terms of classes (Inheritance). We can also override the behaviour of a class using an alternate behaviour (Polymorphism).
A Base Class is a class that is inherited by another class. In .NET, a class may inherit from only one class.
What is Encapsulation
Question :What is Encapsulation?
Answer :Encapsulation - is the ability of an object to hide its data and methods from the rest of the world. It is one of the fundamental principles of OOPs.
Say we create a class, named Calculations. This class may contain a few members in the form of properties, events, fields or methods. Once the class is created, we may instantiate the class by creating an object out of it. The object acts as an instance of this class, the members of the class are not exposed to the outer world directly, rather, they are encapsulated by the class.
Example:
Public class Calculations
{
private void fnMultiply(int x, int y)
{
return x * y;
}
}
...
...
Calculations obj;
int Result;
Result = obj.fnMultiply(5,10);
Answer :Encapsulation - is the ability of an object to hide its data and methods from the rest of the world. It is one of the fundamental principles of OOPs.
Say we create a class, named Calculations. This class may contain a few members in the form of properties, events, fields or methods. Once the class is created, we may instantiate the class by creating an object out of it. The object acts as an instance of this class, the members of the class are not exposed to the outer world directly, rather, they are encapsulated by the class.
Example:
Public class Calculations
{
private void fnMultiply(int x, int y)
{
return x * y;
}
}
...
...
Calculations obj;
int Result;
Result = obj.fnMultiply(5,10);
What is Encapsulation
Question :What is Encapsulation?
Answer :Encapsulation - is the ability of an object to hide its data and methods from the rest of the world. It is one of the fundamental principles of OOPs.
Say we create a class, named Calculations. This class may contain a few members in the form of properties, events, fields or methods. Once the class is created, we may instantiate the class by creating an object out of it. The object acts as an instance of this class, the members of the class are not exposed to the outer world directly, rather, they are encapsulated by the class.
Example:
Public class Calculations
{
private void fnMultiply(int x, int y)
{
return x * y;
}
}
...
...
Calculations obj;
int Result;
Result = obj.fnMultiply(5,10);
Answer :Encapsulation - is the ability of an object to hide its data and methods from the rest of the world. It is one of the fundamental principles of OOPs.
Say we create a class, named Calculations. This class may contain a few members in the form of properties, events, fields or methods. Once the class is created, we may instantiate the class by creating an object out of it. The object acts as an instance of this class, the members of the class are not exposed to the outer world directly, rather, they are encapsulated by the class.
Example:
Public class Calculations
{
private void fnMultiply(int x, int y)
{
return x * y;
}
}
...
...
Calculations obj;
int Result;
Result = obj.fnMultiply(5,10);
Tuesday, 20 January 2009
ASP.NET 3.5 with VS 2008
I found a good presentation on new features in Asp.NET 3.5 with VS 2008 and journey from Asp, Asp.NET 1.1 to Asp.NET 3.5 with Visual studio 2008. Visual studio 2008 completely replaces VS 2005. It provides new features like JavaScript intellisense, JavaScript debugging and new CSS editor, and also Unit test automation tools.NET 3.5 built on top of 2.0 and 3.0. In it, Membership, Role, and
Subscribe to:
Comments (Atom)