Question 1
Question 1
Question 1
Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with
classes, fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types other than classes. For
example, the following class is declared as static, and contains only static methods:
Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members
can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the
object. Static classes can be used when there is no data or behavior in the class that depends on object identity.
Static Classes
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword.
Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is
loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that
do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor
prevents the class from being instantiated.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will
guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static
constructor to assign initial values or set up some static state. For more information, see Static Constructors (C# Programming Guide).
Suppose you have a class CompanyInfo that contains the following methods to get information about the company name and address.
C# Copy Code
class CompanyInfo
{
public string GetCompanyName() { return "CompanyName"; }
public string GetCompanyAddress() { return "CompanyAddress"; }
//...
}
These methods do not need to be attached to a specific instance of the class. Therefore, instead of creating unnecessary instances of this class, you can
declare it as a static class, like this:
C# Copy Code
Use a static class as a unit of organization for methods not associated with particular objects. Also, a static class can make your implementation simpler and
faster because you do not have to create an object in order to call its methods. It is useful to organize the methods inside the class in a meaningful way, such
as the methods of the Math class in the System namespace.
Static Members
A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created,
they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static
fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math
library might contain static methods for calculating sine and cosine.
Static class members are declared using the static keyword before the return type of the member, for example:
C# Copy Code
Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class
member, use the name of the class instead of a variable name to specify the location of the member. For example:
C# Copy Code
Automobile.Drive();
int i = Automobile.NumberOfWheels;
Example
Here is an example of a static class that contains two methods that convert temperature from Celsius to Fahrenheit and vice versa:
C# Copy Code
return fahrenheit;
}
class TestTemperatureConverter
{
static void Main()
{
System.Console.WriteLine("Please select the convertor direction");
System.Console.WriteLine("1. From Celsius to Fahrenheit.");
System.Console.WriteLine("2. From Fahrenheit to Celsius.");
System.Console.Write(":");
switch (selection)
{
case "1":
System.Console.Write("Please enter the Celsius temperature: ");
F = TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
break;
case "2":
System.Console.Write("Please enter the Fahrenheit temperature: ");
C = TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Celsius: {0:F2}", C);
break;
default:
System.Console.WriteLine("Please select a convertor.");
break;
}
}
}
Input
98.6
Sample Output:
:2
:1
C# Copy Code
class SimpleClass
{
// Static constructor
static SimpleClass()
{
//...
}
}
Example
In this example, the class Bus has a static constructor and one static member, Drive(). When Drive() is called, the static constructor is invoked to initialize the
class.
C# Copy Code
class TestBus
{
static void Main()
{
Bus.Drive();
}
}
C# Copy Code
class CoOrds
{
public int x, y;
// constructor
public CoOrds()
{
x = 0;
y = 0;
}
}
Note
For clarity, this class contains public data members. This is not a recommended programming practice because it allows any method anywhere in a
program unrestricted and unverified access to an object's inner workings. Data members should generally be private, and should be accessed only through
class methods and properties.
Output
Instance constructors are used to create and initialize instances. The class constructor is invoked when you create a new object, for example:
This constructor is called whenever an object based on the CoOrds class is created. A constructor like this one, which takes no arguments, is called a default
constructor. However, it is often useful to provide additional constructors. For example, we can add a constructor to the CoOrds class that allows us to specify
the initial values for the data members:
C# Copy Code
This allows CoOrd objects to be created with default or specific initial values, like this:
C# Copy Code
If a class does not have a default constructor, one is automatically generated and default values are used to initialize the object fields, for example, an int is
initialized to 0. For more information on default values, see Default Values Table (C# Reference). Therefore, because the CoOrds class default constructor
initializes all data members to zero, it can be removed altogether without changing how the class works. A complete example using multiple constructors is
provided in Example 1 later in this topic, and an example of an automatically generated constructor is provided in Example 2.
Instance constructors can also be used to call the instance constructors of base classes. The class constructor can invoke the constructor of the base class
through the initializer, as follows:
C# Copy Code
In this example, the Circle class passes values representing radius and height to the constructor provided by Shape from which Circle is derived. A complete
example using Shape and Circle appears in this topic as Example 3.
Example 1
The following example demonstrates a class with two class constructors, one without arguments and one with two arguments.
C# Copy Code
class CoOrds
{
public int x, y;
// Default constructor:
public CoOrds()
{
x = 0;
y = 0;
}
class MainClass
{
static void Main()
{
CoOrds p1 = new CoOrds();
CoOrds p2 = new CoOrds(5, 3);
Output
CoOrds #1 at (0,0)
CoOrds #2 at (5,3)
Example 2
In this example, the class Person does not have any constructors, in which case, a default constructor is automatically provided and the fields are initialized to
their default values.
C# Copy Code
class TestPerson
{
static void Main()
{
Person p = new Person();
Output
Name: , Age: 0
Notice that the default value of age is 0 and the default value of name is null. For more information on default values, see Default Values Table (C#
Reference).
Example 3
The following example demonstrates using the base class initializer. The Circle class is derived from the general class Shape, and the Cylinder class is
derived from the Circle class. The constructor on each derived class is using its base class initializer.
C# Copy Code
abstract class Shape
{
public const double pi = System.Math.PI;
protected double x, y;
class TestShapes
{
static void Main()
{
double radius = 2.5;
double height = 3.0;
Output
For more examples on invoking the base class constructors, see virtual (C# Reference), override (C# Reference), and
Other classes provide services supporting data type conversion, method parameter manipulation, mathematics, remote and local program invocation,
application environment management, and supervision of managed and unmanaged applications.
Classes
Class Description
AccessViolationException The exception that is thrown when there is an attempt to read or write protected memory.
ActivationContext Identifies the activation context for the current application. This class cannot be inherited.
Activator Contains methods to create types of objects locally or remotely, or obtain references to existing remote
objects. This class cannot be inherited.
AppDomain Represents an application domain, which is an isolated environment where applications execute. This class
cannot be inherited.
AppDomainSetup Represents assembly binding information that can be added to an instance of AppDomain.
AppDomainUnloadedException The exception that is thrown when an attempt is made to access an unloaded application domain.
ApplicationException The exception that is thrown when a non-fatal application error occurs.
ApplicationId Contains information used to uniquely identify an application. This class cannot be inherited.
ApplicationIdentity Provides the ability to uniquely identify a manifest-activated application. This class cannot be inherited.
ArgumentException The exception that is thrown when one of the arguments provided to a method is not valid.
ArgumentNullException The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does
not accept it as a valid argument.
ArgumentOutOfRangeException The exception that is thrown when the value of an argument is outside the allowable range of values as
defined by the invoked method.
ArithmeticException The exception that is thrown for errors in an arithmetic, casting, or conversion operation.
Array Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class
for all arrays in the common language runtime.
ArrayTypeMismatchException The exception that is thrown when an attempt is made to store an element of the wrong type within an array.
AttributeUsageAttribute Specifies the usage of another attribute class. This class cannot be inherited.
BadImageFormatException The exception that is thrown when the file image of a DLL or an executable program is invalid.
BitConverter Converts base data types to an array of bytes, and an array of bytes to base data types.
CannotUnloadAppDomainException The exception that is thrown when an attempt to unload an application domain fails.
CharEnumerator Supports iterating over a String object and reading its individual characters. This class cannot be inherited.
CLSCompliantAttribute Indicates whether a program element is compliant with the Common Language Specification (CLS). This class
cannot be inherited.
Console Represents the standard input, output, and error streams for console applications. This class cannot be
inherited.
ConsoleCancelEventArgs Provides data for the Console.CancelKeyPress event. This class cannot be inherited.
ContextMarshalException The exception that is thrown when an attempt to marshal an object across a context boundary fails.
ContextStaticAttribute Indicates that the value of a static field is unique for a particular context.
DataMisalignedException The exception that is thrown when a unit of data is read from or written to an address that is not a multiple of
the data size. This class cannot be inherited.
Delegate Represents a delegate, which is a data structure that refers to a static method or to a class instance and an
instance method of that class.
DivideByZeroException The exception that is thrown when there is an attempt to divide an integral or decimal value by zero.
DllNotFoundException The exception that is thrown when a DLL specified in a DLL import cannot be found.
DuplicateWaitObjectException The exception that is thrown when an object appears more than once in an array of synchronization objects.
EntryPointNotFoundException The exception that is thrown when an attempt to load a class fails due to the absence of an entry method.
Environment Provides information about, and means to manipulate, the current environment and platform. This class cannot
be inherited.
EventArgs EventArgs is the base class for classes containing event data.
ExecutionEngineException The exception that is thrown when there is an internal error in the execution engine of the common language
runtime. This class cannot be inherited.
FieldAccessException The exception that is thrown when there is an invalid attempt to access a private or protected field inside a
class.
FlagsAttribute Indicates that an enumeration can be treated as a bit field; that is, a set of flags.
FormatException The exception that is thrown when the format of an argument does not meet the parameter specifications of
the invoked method.
FtpStyleUriParser A customizable parser based on the File Transfer Protocol (FTP) scheme.
GC Controls the system garbage collector, a service that automatically reclaims unused memory.
InsufficientMemoryException The exception that is thrown when a check for sufficient available memory fails. This class cannot be inherited.
InvalidCastException The exception that is thrown for invalid casting or explicit conversion.
InvalidOperationException The exception that is thrown when a method call is invalid for the object's current state.
InvalidProgramException The exception that is thrown when a program contains invalid Microsoft intermediate language (MSIL) or
metadata. Generally this indicates a bug in the compiler that generated the program.
LdapStyleUriParser A customizable parser based on the Lightweight Directory Access Protocol (LDAP) scheme.
LoaderOptimizationAttribute Used to set the default loader optimization policy for the main method of an executable application.
LocalDataStoreSlot Encapsulates a memory slot to store local data. This class cannot be inherited.
MarshalByRefObject Enables access to objects across application domain boundaries in applications that support remoting.
Math Provides constants and static methods for trigonometric, logarithmic, and other common mathematical
functions.
MemberAccessException The exception that is thrown when an attempt to access a class member fails.
MethodAccessException The exception that is thrown when there is an invalid attempt to access a private or protected method inside a
class.
MissingFieldException The exception that is thrown when there is an attempt to dynamically access a field that does not exist.
MissingMemberException The exception that is thrown when there is an attempt to dynamically access a class member that does not
exist.
MissingMethodException The exception that is thrown when there is an attempt to dynamically access a method that does not exist.
MTAThreadAttribute Indicates that the COM threading model for an application is multithreaded apartment (MTA).
MulticastDelegate Represents a multicast delegate; that is, a delegate that can have more than one element in its invocation list.
MulticastNotSupportedException The exception that is thrown when there is an attempt to combine two instances of a non-combinable delegate
type unless one of the operands is a null reference (Nothing in Visual Basic). This class cannot be inherited.
NetPipeStyleUriParser A parser based on the NetPipe scheme for the "Indigo" system.
NetTcpStyleUriParser A parser based on the NetTcp scheme for the "Indigo" system.
NewsStyleUriParser A customizable parser based on the news scheme using the Network News Transfer Protocol (NNTP).
NonSerializedAttribute Indicates that a field of a serializable class should not be serialized. This class cannot be inherited.
NotFiniteNumberException The exception that is thrown when a floating-point value is positive infinity, negative infinity, or Not-a-Number
(NaN).
NotImplementedException The exception that is thrown when a requested method or operation is not implemented.
NotSupportedException The exception that is thrown when an invoked method is not supported, or when there is an attempt to read,
seek, or write to a stream that does not support the invoked functionality.
Nullable Supports a value type that can be assigned a null reference (Nothing in Visual Basic) like a reference type.
This class cannot be inherited.
NullReferenceException The exception that is thrown when there is an attempt to dereference a null object reference.
Object Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived
classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type
hierarchy.
ObjectDisposedException The exception that is thrown when an operation is performed on a disposed object.
ObsoleteAttribute Marks the program elements that are no longer in use. This class cannot be inherited.
OperatingSystem Represents information about an operating system, such as the version and platform identifier. This class
cannot be inherited.
OperationCanceledException The exception that is thrown in a thread upon cancellation of an operation that the thread was executing.
OutOfMemoryException The exception that is thrown when there is not enough memory to continue the execution of a program.
OverflowException The exception that is thrown when an arithmetic, casting, or conversion operation in a checked context results
in an overflow.
ParamArrayAttribute Indicates that the method will allow a variable number of arguments in its invocation. This class cannot be
inherited.
PlatformNotSupportedException The exception that is thrown when a feature does not run on a particular platform.
Random Represents a pseudo-random number generator, a device that produces a sequence of numbers that meet
certain statistical requirements for randomness.
RankException The exception that is thrown when an array with the wrong number of dimensions is passed to a method.
ResolveEventArgs Provides data for the TypeResolve, ResourceResolve, and AssemblyResolve events.
SerializableAttribute Indicates that a class can be serialized. This class cannot be inherited.
StackOverflowException The exception that is thrown when the execution stack overflows by having too many pending method calls.
This class cannot be inherited.
STAThreadAttribute Indicates that the COM threading model for an application is single-threaded apartment (STA).
StringComparer Represents a string comparison operation that uses specific case and culture-based or ordinal comparison
rules.
SystemException Defines the base class for predefined exceptions in the System namespace.
ThreadStaticAttribute Indicates that the value of a static field is unique for each thread.
TimeoutException The exception that is thrown when the time allotted for a process or operation has expired.
Type Represents type declarations: class types, interface types, array types, value types, enumeration types, type
parameters, generic type definitions, and open or closed constructed generic types.
TypeInitializationException The exception that is thrown as a wrapper around the exception thrown by the class initializer. This class
cannot be inherited.
TypeUnloadedException The exception that is thrown when there is an attempt to access an unloaded class.
UnauthorizedAccessException The exception that is thrown when the operating system denies access because of an I/O error or a specific
type of security error.
UnhandledExceptionEventArgs Provides data for the event that is raised when there is an exception that is not handled by the application
domain.
Uri Provides an object representation of a uniform resource identifier (URI) and easy access to the parts of the
URI.
UriBuilder Provides a custom constructor for uniform resource identifiers (URIs) and modifies URIs for the Uri class.
UriFormatException The exception that is thrown when an invalid Uniform Resource Identifier (URI) is detected.
Version Represents the version number for a common language runtime assembly. This class cannot be inherited.
WeakReference Represents a weak reference, which references an object while still allowing that object to be garbage
collected.
Interfaces
Interface Description
_AppDomain Exposes the public members of the System.AppDomain class to unmanaged code.
IAppDomainSetup Represents assembly binding information that can be added to an instance of AppDomain.
ICloneable Supports cloning, which creates a new instance of a class with the same value as an existing instance.
IComparable Defines a generalized comparison method that a value type or class implements to create a type-specific comparison method.
IComparable Defines a generalized comparison method that a value type or class implements to create a type-specific comparison method
for ordering instances.
IConvertible Defines methods that convert the value of the implementing reference or value type to a common language runtime type that
has an equivalent value.
ICustomFormatter Defines a method that supports custom, user-defined formatting of the value of an object.
IEquatable Defines a generalized method that a value type or class implements to create a type-specific method for determining equality of
instances.
IFormattable Provides functionality to format the value of an object into a string representation.
IServiceProvider Defines a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.
Structures
Structure Description
ArgIterator Represents a variable-length argument list; that is, the parameters of a function that takes a variable number of
arguments.
ConsoleKeyInfo Describes the console key that was pressed, including the character represented by the console key and the state of the
SHIFT, ALT, and CTRL modifier keys.
DateTime Represents an instant in time, typically expressed as a date and time of day.
Nullable Represents an object whose underlying type is a value type that can also be assigned a null reference (Nothing in Visual
Basic) like a reference type.
TypedReference Describes objects that contain both a managed pointer to a location and a runtime representation of the type that may be
stored at that location.
Delegates
Delegate Description
Action Represents the method that performs an action on the specified object.
AppDomainInitializer Represents the callback method to invoke when the application domain is initialized.
AssemblyLoadEventHandler Represents the method that handles the AssemblyLoad event of an AppDomain.
AsyncCallback References the callback method to be called when the asynchronous operation is completed.
Comparison Represents the method that compares two objects of the same type.
ConsoleCancelEventHandler Represents the method that will handle the CancelKeyPress event of a System.Console.
Converter Represents a method that converts an object from one type to another type.
EventHandler Represents the method that will handle an event that has no event data.
EventHandler Represents the method that will handle an event. The generic type argument specifies the type of the event data
generated by the event. This class cannot be inherited.
Predicate Represents the method that defines a set of criteria and determines whether the specified object meets those
criteria.
ResolveEventHandler Represents the method that handles the TypeResolve, ResourceResolve, and AssemblyResolve events of
an AppDomain.
UnhandledExceptionEventHandler Represents the method that will handle the event raised by an exception that is not handled by the application
domain.
Enumerations
Enumeration Description
AppDomainManagerInitializationOptions Specifies the action that a custom application domain manager takes when initializing a new domain.
ConsoleColor Specifies constants that define foreground and background colors for the console.
ConsoleModifiers Represents the SHIFT, ALT, and CTRL modifier keys on a keyboard.
ConsoleSpecialKey Specifies combinations of modifier and console keys that can interrupt the current process.
DateTimeKind Specifies whether a DateTime object represents a local time, a Coordinated Universal Time (UTC), or is
not specified as either local time or UTC.
DayOfWeek Specifies the day of the week.
Environment.SpecialFolder Specifies enumerated constants used to retrieve directory paths to system special folders.
EnvironmentVariableTarget Specifies the location where an environment variable is stored or retrieved in a set or get operation.
LoaderOptimization An enumeration used with the LoaderOptimizationAttribute class to specify loader optimizations for an
executable.
MidpointRounding Specifies how mathematical rounding methods should process a number that is midway between two
numbers.
StringComparison Specifies the culture, case, and sort rules to be used by certain overloads of the String.Compare and
String.Equals methods.
StringSplitOptions Specifies whether applicable System.String.Split method overloads include or omit empty substrings from
the return value.
UriKind Defines the kinds of Uris for the Uri.IsWellFormedUriString and several System.Uri methods.
Passing parameters
There are four different ways of passing parameters to a method in C#.The four different types of parameters are
1. Value
2. Out
3. Ref
4. Params
1.Value parameters This is the default parameter type in C#.If the parameter does not have any modifier it is "value" parameter by default.When we use
"value" parameters the actual value is passed to the function,which means changes made to the parameter is local to the function and is not passed back to
the calling part.
using System;
class ParameterTest
{
static void Mymethod(int Param1)
{
Param1=100;
}
static void Main()
{
int Myvalue=5;
MyMethod(Myvalue);
Console.WriteLine(Myvalue);
}
}
Output of the above program would be 5.Eventhough the value of the parameter Param1 is changed within MyMethod it is not passed back to the calling part
since value parameters are input only.
2.Out parameters "out" parameters are output only parameters meaning they can only passback a value from a function.We create a "out" parameter by
preceding the parameter data type with the out modifier. When ever a "out" parameter is passed only an unassigned reference is passed to the function.
using System;
class ParameterTest
{
static void Mymethod(out int Param1)
{
Param1=100;
}
static void Main()
{
int Myvalue=5;
MyMethod(Myvalue);
Console.WriteLine(out Myvalue);
}
}
Output of the above program would be 100 since the value of the "out" parameter is passed back to the calling part. Note
The modifier "out" should precede the parameter being passed even in the calling part. "out" parameters cannot be used within the function before assigning
a value to it. A value should be assigned to the "out" parameter before the method returns.
3.Ref parameters "ref" parameters are input/output parameters meaning they can be used for passing a value to a function as well as to get back a value
from a function.We create a "ref" parameter by preceding the parameter data type with the ref modifier. When ever a "ref" parameter is passed a reference is
passed to the function.
using System;
class ParameterTest
{
static void Mymethod(ref int Param1)
{
Param1=Param1 + 100;
}
static void Main()
{
int Myvalue=5;
MyMethod(Myvalue);
Console.WriteLine(ref Myvalue);
}
}
Output of the above program would be 105 since the "ref" parameter acts as both input and output.
Note
The modifier "ref" should precede the parameter being passed even in the calling part. "ref" parameters should be assigned a value before using it to call a
method. 4.Params parameters "params" parameters is a very useful feature in C#. "params" parameter are used when a variable number of arguments need
to be passed.The "params" should be a single dimensional or a jagged array.
using System;
class ParameterTest
{
static int Sum(params int[] Param1)
{
int val=0;
foreach(int P in Param1)
{
val=val+P;
}
return val;
}
static void Main()
{
Console.WriteLine(Sum(1,2,3));
Console.WriteLine(Sum(1,2,3,4,5));
}
}
Output of the above program would be 6 and 15.
Note
The value passed for a "params" parameter can be either comma separated value list or a single dimensional array. "params" parameters are input only.
Second def
Output parameters
Like reference parameters, output parameters don't create a new storage location, but use the storage location of the variable specified on the invocation.
Output parameters need the out modifier as part of both the declaration and the invocation - that means it's always clear when you're passing something as
an output parameter.
Output parameters are very similar to reference parameters. The only differences are:
• The variable specified on the invocation doesn't need to have been assigned a value before it is passed to the function member. If the function
member completes normally, the variable is considered to be assigned afterwards (so you can then "read" it).
• The parameter is considered initially unassigned (in other words, you must assign it a value before you can "read" it in the function member).
• The parameter must be assigned a value before the function member completes normally.
Here is some example code showing this, with an int parameter (int is a value type, but if you understood reference parameters properly, you should be able
to see what the behaviour for reference types is):
Output:
10
Parameter arrays
Parameter arrays allow a variable number of arguments to be passed into a function member. The definition of the parameter has to include the params
modifier, but the use of the parameter has no such keyword. A parameter array has to come at the end of the list of parameters, and must be a single-
dimensional array. When using the function member, any number of parameters (including none) may appear in the invocation, so long as the parameters are
each compatible with the type of the parameter array. Alternatively, a single array may be passed, in which case the parameter acts just as a normal value
parameter. For example:
void ShowNumbers (params int[] numbers)
{
foreach (int x in numbers)
{
Console.Write (x+" ");
}
Console.WriteLine();
}
...
Output:
12345
In the first invocation, the variable x is passed by value, as it's just an array. In the second invocation, a new array of ints is created containing the two values
specified, and a reference to this array is passed.
Mini-glossary
Function member
A function member is a method, property, event, indexer, user-defined operator, instance constructor, static constructor, or destructor.
Output parameter
A parameter very similar to a reference parameter, but with different definite assignment rules.
Reference parameter (pass-by-reference semantics)
A parameter which shares the storage location of the variable used in the function member invocation. As they share the same storage location,
they always have the same value (so changing the parameter value changes the invocation variable value).
Reference type
Type where the value of a variable/expression of that type is a reference to an object rather than the object itself.
Storage location
A portion of memory holding the value of a variable.
Value parameter (the default semantics, which are pass-by-value)
A value parameter that has its own storage location, and thus its own value. The initial value is the value of the expression used in the function
member invocation.
Value type
Type where the value of a variable/expression of that type is the object data itself.
Variable
Name associated with a storage location and type. (Usually a single variable is associated with a storage location. The exceptions are for reference
and output parameters.)
Third
When we pass a parameter as ref to a method, the method refers to the same variable and changes made will affect the actual variable.Even the variable
passed as out parameter is similar to ref, but there are few implementation differences when you use it in C# .
Argument passed as ref must be initialized before it is passed to the method, where as in case of out its is not necessary,but after a call to the method as an
out parameter the variable must be initialized.
When to use ref and out parameter. out parameter can be used when we want to return more than one value from a method.
IMPORTANT NOTE : We now know what are ref and out parameters, but these are only for C#(these are only understood by csc Compiler) when looking
inside the IL Code there is no difference whether you use ref or out parameters. The implementation of ref and out parameter in IL Code is same.
When Calling a method and in the method signature after the datatype of the parameter a & sign is used, indicating the address of the variable.
Source Code:
RefOut.cs
using System;
class RefOut
{
public static void Main(String [] args)
{
int a = 0,b,c=0,d=0;
Console.WriteLine("a is normal parameter will not affect the changes after the function call");
Console.WriteLine("b is out parameter will affect the changes after the function call but not necessary to initialize the variable b but should be initialized in the
function ParamTest ");
Console.WriteLine("c is ref parameter will affect the changes after the function call and is compulsory to initialize the variable c before calling the function
ParamTest");
Console.WriteLine("d is used to store the return value");
d=ParamTest(a,out b,ref c);
Console.WriteLine("a = {0}", a);
Console.WriteLine("b = {0}", b);
Console.WriteLine("c = {0}", c);
Console.WriteLine("d = {0}", d);
}
public static int ParamTest(int a, out int b, ref int c)
{
a=10;
b=20;
c=30;
return 40;
}
}
Fourth
When we are coding a function, we should use out parameter, when we're returning value to it, but we don't need that parameter to be initialized, so that
parameter purpose is to accept value from inside the function, for example ( this is not likely, but only for an example ):
x=0;
We should use ref parameter, when we're returning value to it, but we also need that parameter to be initialized, I think the proper example for this is Swap
function:
int temp ;
temp = x ;
x=y;
y = temp ;
}
In DB2(R), a common language runtime (CLR) routine is an external routine created by executing a CREATE PROCEDURE or CREATE FUNCTION
statement that references a .NET assembly as its external code body.
.NET Framework
A Microsoft(R) application development environment comprised of the CLR and .NET Framework class library designed to provide a consistent
programming environment for developing and integrating code pieces.
Common language runtime (CLR)
The runtime interpreter for all .NET Framework applications.
intermediate language (IL)
Type of compiled byte-code interpreted by the .NET Framework CLR. Source code from all .NET compatible languages compiles to IL byte-code.
assembly
A file that contains IL byte-code. This can either be a library or an executable.
Fifth
In .NET (and therefore C#) there are two main sorts of type: reference types and value types. They act differently, and a lot of confusion about parameter
passing is really down to people not properly understanding the difference between them. Here's a quick explanation:
A reference type is a type which has as its value a reference to the appropriate data rather than the data itself. For instance, consider the following code:
(I have used StringBuilder as a random example of a reference type - there's nothing special about it.) Here, we declare a variable sb, create a new
StringBuilder object, and assign to sb a reference to the object. The value of sb is not the object itself, it's the reference. Assignment involving reference types
is simple - the value which is assigned is the value of the expression/variable - i.e. the reference. This is demonstrated further in this example:
Here we declare a variable first, create a new StringBuilder object, and assign to first a reference to the object. We then assign to second the value of first.
This means that they both refer to the same object. They are still, however, independent variables themselves. Changing the value of first will not change the
value of second - although while their values are still references to the same object, any changes made to the object through the first variable will be visible
through the second variable. Here's a demonstration of that:
using System;
using System.Text;
hello
Here, we declare a variable first, create a new StringBuilder object, and assign to first a reference to the object. We then assign to second the value of first.
We then call the Append method on this object via the reference held in the first variable. After this, we set the first variable to null (a value which doesn't refer
to any object). Finally, we print out the results of calling the ToString method on the StringBuilder object via the reference held in the second variable. hello is
displayed, demonstrating that even though the value of first has changed, the data within the object it used to refer to hasn't - and second still refers to that
object.
Class types, interface types, delegate types and array types are all reference types.
While reference types have a layer of indirection between the variable and the real data, value types don't. Variables of a value type directly contain the data.
Assignment of a value type involves the actual data being copied. Take a simple struct, for example:
Wherever there is a variable of type IntHolder, the value of that variable contains all the data - in this case, the single integer value. An assignment copies the
value, as demonstrated here:
Here, second.i has the value 5, because that's the value first.i has when the assignment second=first occurs - the values in second are independent of the
values in first apart from when the assignment takes place.
Simple types (such as float, int, char), enum types and struct types are all value types.
Note that many types (such as string) appear in some ways to be value types, but in fact are reference types. These are known as immutable types. This
means that once an instance has been constructed, it can't be changed. This allows a reference type to act similarly to a value type in some ways - in
particular, if you hold a reference to an immutable object, you can feel comfortable in returning it from a method or passing it to another method, safe in the
knowledge that it won't be changed behind your back. This is why, for instance, the string.Replace doesn't change the string it is called on, but returns a new
instance with the new string data in - if the original string were changed, any other variables holding a reference to the string would see the change, which is
very rarely what is desired.
Constrast this with a mutable (changeable) type such as ArrayList - if a method returns the ArrayList reference stored in an instance variable, the calling code
could then add items to the list without the instance having any say about it, which is usually a problem. Having said that immutable reference types act like
value types, they are not value types, and shouldn't be thought of as actually being value types.
For more information about value types, reference types, and where the data for each is stored in memory, please see my other article about the subject.
What would you expect to see from the code above if the declaration of the IntHolder type was as a class instead of a struct? If you don't understand why the
output would be 6, please re-read both preambles and mail me if it's still not clear - if you don't get it, it's my fault, not yours, and I need to improve this page.
If you do understand it, parameter passing becomes very easy to understand - read on.
There are four different kinds of parameters in C#: value parameters (the default), reference parameters (which use the ref modifier), output parameters
(which use the out modifier), and parameter arrays (which use the params modifier). You can use any of them with both value and reference types. When you
hear the words "reference" or "value" used (or use them yourself) you should be very clear in your own mind whether you mean that a parameter is a
reference or value parameter, or whether you mean that the type involved is a reference or value type. If you can keep the two ideas separated, they're very
simple.
Value parameters
By default, parameters are value parameters. This means that a new storage location is created for the variable in the function member declaration, and it
starts off with the value that you specify in the function member invocation. If you change that value, that doesn't alter any variables involved in the invocation.
For instance, if we have:
void Foo (StringBuilder x)
{
x = null;
}
...
using System;
using System.Text;
Output:
False
The value of y isn't changed just because x is set to null. Remember though that the value of a reference type variable is the reference - if two reference type
variables refer to the same object, then changes to the data in that object will be seen via both variables. For example:
...
Output:
hello world
After calling Foo, the StringBuilder object that y refers to contains "hello world", as in Foo the data " world" was appended to that object via the reference held
in x.
Now consider what happens when value types are passed by value. As I said before, the value of a value type variable is the data itself. Using the previous
definition of the struct IntHolder, let's write some code similar to the above:
...
using System;
using System.Text;
Output:
When Foo is called, x starts off as a struct with value i=5. Its i value is then changed to 10. Foo knows nothing about the variable y, and after the method
completes, the value in y will be exactly the same as it was before (i.e. 5).
As we did earlier, check that you understand what would happen if IntHolder was declared as a class instead of a struct. You should understand why y.i would
be 10 after calling Foo in that case.
Reference parameters
Reference parameters don't pass the values of the variables used in the function member invocation - they use the variables themselves. Rather than
creating a new storage location for the variable in the function member declaration, the same storage location is used, so the value of the variable in the
function member and the value of the reference parameter will always be the same. Reference parameters need the ref modifier as part of both the
declaration and the invocation - that means it's always clear when you're passing something by reference. Let's look at our previous examples, just changing
the parameter to be a reference parameter:
...
using System;
using System.Text;
Output:
True
Here, because a reference to y is passed rather than its value, changes to the value of parameter x are immediately reflected in y. In the above example, y
ends up being null. Compare this with the result of the same code without the ref modifiers.
Now consider the struct code we had earlier, but using reference parameters:
...
using System;
using System.Text;
10
The two variables are sharing a storage location, so changes to x are also visible through y, so y.i has the value 10 at the end of this code.
Sidenote: what is the difference between passing a value object by reference and a reference object by value?
You may have noticed that the last example, passing a struct by reference, had the same effect in this code as passing a class by value. This
doesn't mean that they're the same thing, however. Consider the following code:
...
Output parameters
Like reference parameters, output parameters don't create a new storage location, but use the storage location of the variable specified on the invocation.
Output parameters need the out modifier as part of both the declaration and the invocation - that means it's always clear when you're passing something as
an output parameter.
Output parameters are very similar to reference parameters. The only differences are:
• The variable specified on the invocation doesn't need to have been assigned a value before it is passed to the function member. If the function
member completes normally, the variable is considered to be assigned afterwards (so you can then "read" it).
• The parameter is considered initially unassigned (in other words, you must assign it a value before you can "read" it in the function member).
• The parameter must be assigned a value before the function member completes normally.
Here is some example code showing this, with an int parameter (int is a value type, but if you understood reference parameters properly, you should be able
to see what the behaviour for reference types is):
// Assignment - this must happen before the method can complete normally
x = 10;
...
// Declare a variable but don't assign a value to it
int y;
using System;
using System.Text;
// Assignment - this must happen before the method can complete normally
x = 10;
Output:
10
Parameter arrays
Parameter arrays allow a variable number of arguments to be passed into a function member. The definition of the parameter has to include the params
modifier, but the use of the parameter has no such keyword. A parameter array has to come at the end of the list of parameters, and must be a single-
dimensional array. When using the function member, any number of parameters (including none) may appear in the invocation, so long as the parameters are
each compatible with the type of the parameter array. Alternatively, a single array may be passed, in which case the parameter acts just as a normal value
parameter. For example:
...
int[] x = {1, 2, 3};
ShowNumbers (x);
ShowNumbers (4, 5);
using System;
using System.Text;
Output:
123
45
In the first invocation, the variable x is passed by value, as it's just an array. In the second invocation, a new array of ints is created containing the two values
specified, and a reference to this array is passed.
Mini-glossary
Function member
A function member is a method, property, event, indexer, user-defined operator, instance constructor, static constructor, or destructor.
Output parameter
A parameter very similar to a reference parameter, but with different definite assignment rules.
Reference parameter (pass-by-reference semantics)
A parameter which shares the storage location of the variable used in the function member invocation. As they share the same storage location,
they always have the same value (so changing the parameter value changes the invocation variable value).
Reference type
Type where the value of a variable/expression of that type is a reference to an object rather than the object itself.
Storage location
A portion of memory holding the value of a variable.
Value parameter (the default semantics, which are pass-by-value)
A value parameter that has its own storage location, and thus its own value. The initial value is the value of the expression used in the function
member invocation.
Value type
Type where the value of a variable/expression of that type is the object data itself.
Variable
Name associated with a storage location and type. (Usually a single variable is associated with a storage location. The exceptions are for reference
and output parameters.)
Enumeratos
An enumeration (enum) is a special form of value type, which inherits from System.Enum and supplies alternate names for the values of an underlying
primitive type. An enumeration type has a name, an underlying type, and a set of fields. The underlying type must be one of the built-in signed or unsigned
integer types (such as Byte, Int32, or UInt64). The fields are static literal fields, each of which represents a constant. The language you are using assigns a
specific value of the underlying type to each field. The same value can be assigned to multiple fields. When this occurs, the language marks one of the values
as the primary enumeration value for purposes of reflection and string conversion. The boxing rules that apply to value types also apply to enumerations.
For example:
enum Months
{
jan, feb, mar, apr
}
By default the first enumerator has the value of zero and the value of each successive enumerator is increased by 1. For example in the above case the value
jan is 0, feb is 1 and so on. Remember that the modifier can be private, public, protected or internal.
enum Months
{
jan = 10, feb = 20, mar = 30, apr=40
}
The underlying type specifies how much storage is allocated for each enumerator. However an explicit cast is needed to convert from unum type to integral
types. This is why the enum types are type safe in C#.
For example:
Two more enum members can have the same value as follows.
enum Months
{
jan = 1, feb = 1, mar, apr
}
All the enum members are explicitly static and so they can be accessed only with the type and not with the instances.
using System;
enum Months : long
{
jan = 10,feb = 20,mar
}
class MyClient
{
public static void Main()
{
long x = (long)Months.jan;
long y = (long)Months.feb;
long z = (long)Months.mar;
Console.WriteLine("JANUARY={0},FEbriary = {1},March={2}",x,y,z);
}
}
The use of enum type is superior to the use of integer constants, because the use of enum makes the code more readable and self-documenting.
C# Language Reference
enum (C# Reference)
The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration
type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int. By default, the first
enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example:
Copy Code
In this enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth. Enumerators can have initializers to override the default values. For example:
Copy Code
A variable of type Days can be assigned any value in the range of the underlying type; the values are not limited to the named constants.
The default value of an enum E is the value produced by the expression (E)0.
Note
The underlying type specifies how much storage is allocated for each enumerator. However, an explicit cast is needed to convert from enum type to an
integral type. For example, the following statement assigns the enumerator Sun to a variable of the type int using a cast to convert from enum to int:
Copy Code
int x = (int)Days.Sun;
When you apply System.FlagsAttribute to an enumeration that contains some elements combined with a bitwise OR operation, you will notice that the
attribute affects the behavior of the enum when used with some tools. You can notice these changes when using tools such as the Console class methods,
the Expression Evaluator, and so forth. (See example 3).
Robust Programming
Assigning additional values new versions of enums, or changing the values of the enum members in a new version, can cause problems for dependant
source code. It is often the case that enum values are used in switch statements, and if additional elements have been added to the enum type, the test for
default values can return true unexpectedly.
If other developers will be using your code, it is important to provide guidelines on how their code should react if new elements are added to any enum types.
Example
In this example, an enumeration, Days, is declared. Two enumerators are explicitly converted to integer and assigned to integer variables.
Copy Code
// keyword_enum.cs
// enum initialization:
using System;
int x = (int)Days.Sun;
int y = (int)Days.Fri;
Output
Sun = 2
Fri = 7
In this example, the base-type option is used to declare an enum whose members are of the type long. Notice that even though the underlying type of the
enumeration is long, the enumeration members must still be explicitly converted to type long using a cast.
Copy Code
// keyword_enum2.cs
using System;
long x = (long)Range.Max;
long y = (long)Range.Min;
Output
Max = 2147483648
Min = 255
The following code example illustrates the use and effect of the System.FlagsAttribute attribute on an enum declaration.
Copy Code
// enumFlags.cs
using System;
[Flags]
SunRoof = 0x01,
Spoiler = 0x02,
FogLights = 0x04,
TintedWindows = 0x08,
class FlagTest
Console.WriteLine(options);
Console.WriteLine((int)options);
Output
SunRoof, FogLights
5
enum
The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration
type has an underlying type, which can be any integral type except char. This declaration takes the following form::
where:
attributes (Optional)
Additional declarative information. For more information on attributes and attribute classes, see 17. Attributes.
modifiers (Optional)
The allowed modifiers are new and the four access modifiers.
identifier
The enum name.
base-type (Optional)
The underlying type that specifies the storage allocated for each enumerator. It can be one of the integral types except char. The default is int.
enumerator-list
The enumerators' identifiers separated by commas, optionally including a value assignment.
Remarks
The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator
is increased by 1. For example:
Copy Code
In this enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth. Enumerators can have initializers to override the default values. For example:
Copy Code
The default value of an enum E is the value produced by the expression (E)0.
The underlying type specifies how much storage is allocated for each enumerator. However, an explicit cast is needed to convert from enum type to an
integral type. For example, the following statement assigns the enumerator Sun to a variable of the type int using a cast to convert from enum to int:
Copy Code
Example 1
In this example, an enumeration, Days, is declared. Two enumerators are explicitly converted to int and assigned to int variables.
Copy Code
// keyword_enum.cs
// enum initialization:
using System;
Output
Copy Code
Sun = 2
Fri = 7
Notice that if you remove the initializer from Sat=1, the result will be:
Copy Code
Sun = 1
Fri = 6
Example 2
In this example, the base-type option is used to declare an enum whose members are of the type long. Notice that even though the underlying type of the
enumeration is long, the enumeration members must still be explicitly converted to type long using a cast.
Copy Code
// keyword_enum2.cs
using System;
Output
Copy Code
Max = 2147483648
Min = 255
Definition:
"EXCEPTION IS A RUNTIME ERROR WHICH ARISES BECAUSE OF ABNORMAL CONDITION IN A CODE SEQUENCE. "
In C# Exception is a class in the system namespace. An object of an exception is that describe the exceptional conditions occur in a code That means, we
are catching an exception, creating an object of it, and then throwing it. C# supports exceptions in a very much the same way as Java and C++.
Before going into detail, I must say the usefulness of knowing and performing exception handling :
• They cannot be ignored, as if calling code does not handle the error, it causes program termination.
• They do not need to be to be handled at the point where error took place. This makes them very suitable for library or system code, which can
signal an error and leave us to handle it
• They can be used when passing back a return value cannot be used
Exceptions are handled by using try...catch statements. Code which may give rise to exceptions is enclosed in a try block, which is followed by one or
more catch blocks. Well if you don't use try...catch, you could get errors like the following:
The try block contains the code segment expected to raise an exception. This block is executed until an exception is thrown The catch block contains the
exception handler. This block catches the exception and executes the code written in the block. If we do not know what kind of exception is going to be
thrown we can simply omit the type of exception. We can collect it in Exception object as shown in the following program:
int a, b = 0 ;
Console.WriteLine( "My program starts " ) ;
try
{
a = 10 / b;
}
catch ( Exception e )
{
Console.WriteLine ( e ) ;
}
Console.WriteLine ( "Remaining program" ) ;
My program starts
Remaining program
The exception 'Divide by zero' was caught, but the execution of the program did not stop. There are a number of exception classes provided by C#, all of
which inherit from the System.Exception class. Following are some common exception classes:
The finally block is used to do all the clean up code. It does not support the error message, but all the code contained in the finally block is executed after
the exception is raised. We can use this block along with try...catch and only with catch too. The finally block is executed even if the error is raised. Control is
always passed to the finally block regardless of how the try blocks exits.
int a, b = 0 ;
Console.WriteLine( "My program starts" ) ;
try
{
a = 10 / b;
}
catch ( InvalidOperationException e )
{
Console.WriteLine ( e ) ;
}
catch ( DivideByZeroException e)
{
Console.WriteLine ( e ) ;
}
finally
{
Console.WriteLine ( "finally" ) ;
}
Console.WriteLine ( "Remaining program" ) ;
My program starts
Remaining program
Console.WriteLine ("finally");
after the catch block, and not write the finally block at all. Writing finally did not make much of a difference. Anyway the code written after catch gets executed.
The answer to this is not clear in this program. It will be clear when we see the try-finally and the throw statement.
int a, b = 0 ;
Console.WriteLine( "My program starts" )
try
{
a = 10 / b;
}
finally
{
Console.WriteLine ( "finally" ) ;
}
Console.WriteLine ( "Remaining program" ) ;
My program starts
Note that "Remaining program" is not printed out. Only "finally" is printed which is written in the finally block.
The throw statement throws an exception. A throw statement with an expression throws the exception produced by evaluating the expression. A throw
statement with no expression is used in the catch block. It re-throws the exception that is currently being handled by the catch block.
int a, b = 0 ;
Console.WriteLine( "My program starts" ) ;
try
{
a = 10 / b;
}
catch ( Exception e)
{
throw
}
finally
{
Console.WriteLine ( "finally" ) ;
}
This shows that the exception is re-thrown. Whatever is written in finally is executed and the program terminates. Note again that "Remaining program" is not
printed.
Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard
exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user
(programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the
program execution.
C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch
handles an exception if one exists. The finally can be used for doing any clean up process.
try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}
If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block.
But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and
finally blocks.
If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is
executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.
In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides
couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of
the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc.
Uncaught Exceptions
The following program will compile but will show an error during execution. The division by zero is a runtime anomaly and program terminates with an error
message. Any uncaught exceptions in the current context propagate to a higher context and looks for an appropriate catch block to handle it. If it can't find
any suitable catch blocks, the default mechanism of the .NET runtime will terminate the execution of the entire program.
The modified form of the above program with exception handling mechanism is as follows. Here we are using the object of the standard exception class
DivideByZeroException to handle the exception caused by division by zero.
In the above case the program do not terminate unexpectedly. Instead the program control passes from the point where exception occurred inside the try
block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the
program statements.
If a finally block is present, the code inside the finally block will get also be executed.
Remember that in C#, the catch block is optional. The following program is perfectly legal in C#.
But in this case, since there is no exception handling catch block, the execution will get terminated. But before the termination of the program statements
inside the finally block will get executed. In C#, a try block must be followed by either a catch or finally block.
A try block can throw multiple exceptions, which can handle by using multiple catch blocks. Remember that more specialized catch block should come before
a generalized one. Otherwise the compiler will show a compilation error.
By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an
Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the
Exception class.
Throwing an Exception
In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this purpose. The general form of throwing an exception is as
follows.
throw exception_obj;
Re-throwing an Exception
The exceptions, which we caught inside a catch block, can re-throw to a higher context by using the keyword throw inside the catch block. The following
program shows how to do this.
Standard Exceptions
There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime.
System.Exception is the base class for all exceptions in C#. Several exception classes inherit from this class including ApplicationException and
SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions that derive directly from System.Exception include
IOException, WebException etc.
The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. The
SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good
programming practice to throw SystemExceptions in our applications.
• System.OutOfMemoryException
• System.NullReferenceException
• Syste.InvalidCastException
• Syste.ArrayTypeMismatchException
• System.IndexOutOfRangeException
• System.ArithmeticException
• System.DevideByZeroException
• System.OverFlowException
User-defined Exceptions
In C#, it is possible to create our own exception class. But Exception must be the ultimate base class for all exceptions in C#. So the user-defined exception
classes must inherit from either Exception class or one of its standard derived classes.
Design Guidelines
Exceptions should be used to communicate exceptional conditions. Don't use them to communicate events that are expected, such as reaching the end of a
file. If there's a good predefined exception in the System namespace that describes the exception condition-one that will make sense to the users of the
class-use that one rather than defining a new exception class, and put specific information in the message. Finally, if code catches an exception that it isn't
going to handle, consider whether it should wrap that exception with additional information before re-throwing it.
The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions.
Remarks
The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully. For
example, the following attempt to cast a null object raises the NullReferenceException exception:
Copy Code
object o2 = null;
try
{
int i2 = (int)o2; // Error
The catch clause can be used without arguments, in which case it catches any type of exception, and referred to as the general catch clause. It can also take
an object argument derived from System.Exception, in which case it handles a specific exception. For example:
Copy Code
catch (InvalidCastException e)
It is possible to use more than one specific catch clause in the same try-catch statement. In this case, the order of the catch clauses is important because
the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones.
A throw statement can be used in the catch block to re-throw the exception, which has been caught by the catch statement. For example:
Copy Code
catch (InvalidCastException e)
If you want to re-throw the exception currently handled by a parameter-less catch clause, use the throw statement without arguments. For example:
Copy Code
catch
throw;
When inside a try block, only initialize variables that are declared therein; otherwise, an exception can occur before the execution of the block is completed.
For example, in the following code example, the variable x is initialized inside the try block. An attempt to use this variable outside the try block in the Write(x)
statement will generate the compiler error: Use of unassigned local variable.
Copy Code
int x;
try
{
// Don't initialize this variable here.
x = 123;
catch
Console.Write(x);
Example
In this example, the try block contains a call to the method MyMethod() that may cause an exception. The catch clause contains the exception handler that
simply displays a message on the screen. When the throw statement is called from inside MyMethod, the system looks for the catch statement and displays
the message Exception caught.
Copy Code
// try_catch_example.cs
using System;
class MainClass
if (s == null)
try
{
string s = null;
ProcessString(s);
catch (Exception e)
Sample Output
System.ArgumentNullException: Value cannot be null.
at MainClass.Main() Exception caught.
In this example, two catch statements are used. The most specific exception, which comes first, is caught.
Copy Code
// try_catch_ordering_catch_clauses.cs
using System;
class MainClass
if (s == null)
try
string s = null;
ProcessString(s);
}
// Most specific:
catch (ArgumentNullException e)
// Least specific:
catch (Exception e)
Sample Output
System.ArgumentNullException: Value cannot be null.
at MainClass.Main() First exception caught.
Comments
In the preceding example, if you start with the least specific catch clause, you will get the error message:A previous catch clause already catches all
exceptions of this or a super type ('System.Exception')
However, to catch the least specific exception, replace the throw statement by the following one:
A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and
release the resources in the finally block.
Example
Copy Code
// try-catch-finally
using System;
{
public static void Main ()
try
catch(NullReferenceException e)
catch
finally
Output
Copy Code
This chapter divides neatly into two main topics. First, we.ll consider the classes provided by the .NET Framework classes, which meet the lower-level data
transfer requirements of the streams-based I/O framework. These classes further divide into stream classes and file system classes.that is, classes that
actually represent data streams, and classes that represent file system objects such as files and directories. Then we.ll look at how you can enhance any
custom class to allow it to fit seamlessly into the standard I/O framework. This enhancement is based on a standard attribute that marks your class as
capable of being serialized. The serialization process is used in conjunction with the streams classes to stream your custom class objects from one place to
another.in memory, to a remote location, or to persistent storage. As part of our exploration of the streams framework, we.ll consider the different types of
stream, types of file system objects, and potential application environments, including Microsoft Windows.based and Web-based environments.
Stream Classes
The .NET Framework classes offer a streams-based I/O framework, with the core classes in the System.IO namespace. All classes that represent streams
inherit from the Stream class, and the key classes are listed in Table 1.
Class Description
Stream The abstract base class Stream supports reading and writing bytes.
FileStream In addition to basic Stream behavior, this class supports random access to
files through its Seek method and supports both synchronous and
asynchronous operation.
MemoryStream A nonbuffered stream whose encapsulated data is directly accessible in
memory. This stream has no backing store and might be useful as a
temporary buffer.
BufferedStream A Stream that adds buffering to another Stream, such as a NetworkStream.
(FileStream already has buffering internally, and a MemoryStream doesn't
need buffering.) A BufferedStream object can be composed around some
types of streams to improve read and write performance.
TextReader The abstract base class for StreamReader and StringReader objects. While
the implementations of the abstract Stream class are designed for byte input
and output, the implementations of TextReader are designed for Unicode
character output.
StreamReader Reads characters from a Stream, using Encoding to convert characters to and
from bytes.
StringReader Reads characters from a String. StringReader allows you to treat a String with
the same API; thus, your output can be either a Stream in any encoding or a
String.
TextWriter The abstract base class for StreamWriter and StringWriter objects. While the
implementations of the abstract Stream class are designed for byte input and
output, the implementations of TextWriter are designed for Unicode character
input.
StreamWriter Writes characters to a Stream, using Encoding to convert characters to bytes.
StringWriter Writes characters to a String. StringWriter allows you to treat a String with the
same API; thus, your output can be either a Stream in any encoding or a
String.
BinaryReader Reads binary data from a stream.
BinaryWriter Writes binary data to a stream.
Two classes derived from Stream but not listed in Table 1 are offered in other namespaces. The NetworkStream class represents a Stream over a network
connection and resides in the System.Net.Sockets namespace, and the CryptoStream class links data streams to cryptographic transformations and resides
in the System.Security.Cryptography namespace.
The design of the Stream class and its derivatives is intended to provide a generic view of data sources and destinations so that the developer can
interchangeably use any of these classes without redesigning the application. In general, Stream objects are capable of one or more of the following:
• Reading The transfer of data from a stream into a data structure, such as an array of bytes
• Writing The transfer of data from a data structure into a stream
• Seeking The querying and modifying of the current position within a stream
Note that a given stream might not support all these features. For example, NetworkStream objects don't support seeking. You can use the CanRead,
CanWrite, and CanSeek properties of Stream and its derived classes to determine precisely which operations a given stream does in fact support.
Abstract
Introduction
Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don’t
want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'.
An abstract class means that, no object of this class can be instantiated, but can make derivations of this.
An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but
the same has to be provided in its derived class.
Also, note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract
members. For example:
Collapse
using System;
namespace abstractSample
{
//Creating an Abstract Class
abstract class absClass
{
//A Non abstract method
public int AddTwoNumbers(int Num1, int Num2)
{
return Num1 + Num2;
}
In the above sample, you can see that the abstract class absClass contains two methods AddTwoNumbers and MultiplyTwoNumbers. AddTwoNumbers is a
non-abstract method which contains implementation and MultiplyTwoNumbers is an abstract method that does not contain implementation.
The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within the Main, an instance (calculate) of the
absDerived is created, and calls AddTwoNumbers and MultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the
child class it is optional to make the implementation of the abstract methods of the parent class.
Example
//Abstract Class1
abstract class absClass1
{
public abstract int AddTwoNumbers(int Num1, int Num2);
public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}
//Abstract Class2
abstract class absClass2:absClass1
{
//Implementing AddTwoNumbers
public override int AddTwoNumbers(int Num1, int Num2)
{
return Num1+Num2;
}
}
In the above example, absClass1 contains two abstract methods AddTwoNumbers and MultiplyTwoNumbers. The AddTwoNumbers is implemented in the
derived class absClass2. The class absDerived is derived from absClass2 and the MultiplyTwoNumbers is implemented there.
Abstract properties
class absDerived:absClass
{
//Implementing abstract properties
public override int numbers
{
get
{
return myNumber;
}
set
{
myNumber = value;
}
}
}
In the above example, there is a protected member declared in the abstract class. The get/set properties for the member variable myNumber is defined in the
derived class absDerived.
An abstract class cannot be a sealed class. I.e. the following declaration is incorrect.
//Incorrect
abstract sealed class absClass
{
}
Declaration of abstract methods are only allowed in abstract classes.
//Incorrect
private abstract int MultiplyTwoNumbers();
The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it
should be protected in its derived class. Otherwise, the compiler will raise an error.
An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.
//Incorrect
public abstract virtual int MultiplyTwoNumbers();
//Incorrect
publpublic abstract static int MultiplyTwoNumbers();
An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members
of the interface must override to its derived class.
An example of interface:
interface iSampleInterface
{
//All methods are automaticall abstract
int AddNumbers(int Num1, int Num2);
int MultiplyNumbers(int Num1, int Num2);
}
Defining an abstract class with abstract members has the same effect to defining an interface.
The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.
A class can inherit one or more interfaces, but only one abstract class.
Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional
functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.
The selection of interface or abstract class depends on the need and design of your project. You can make an abstract class, interface or combination of both
depending on your needs.
A class representing a base class which other types can subclass. A normal, non-abstract class is called a concrete class. An abstract class may
contain either or both abstract and concrete methods. (Properties cannot be marked abstract.) As in ordinary inheritance, a type derived from an
abstract class inherits all the base type members including any method implementations. But, if any abstract methods are inherited, the class must
either declare itself abstract or provide an implementation.
Abstract and Sealed Classes and Class Members (C# Programming Guide)
The abstract keyword enables you to create classes and class members solely for the purpose of inheritance—to define features of derived, non-abstract
classes. The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual. For more
information, see How to: Define Abstract Properties (C# Programming Guide).
Classes can be declared as abstract. This is accomplished by putting the keyword abstract before the keyword class in the class definition. For example:
C#
Copy Code
An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can
share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that
library to provide their own implementation of the class by creating a derived class.
Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method. For example:
C#
Copy Code
Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the
abstract class must implement all abstract methods. When an abstract class inherits a virtual method from a base class, the abstract class can override the
virtual method with an abstract method. For example:
C#
Copy Code
public class D
// Original implementation.
public class F : E
// New implementation.
If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the
original implementation of the method—in the previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class can force
derived classes to provide new method implementations for virtual methods.
Classes can be declared as sealed. This is accomplished by putting the keyword sealed before the keyword class in the class definition. For example:
C#
Copy Code
A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation.
Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster.
A class member, method, field, property, or event, on a derived class that is overriding a virtual member of the base class can declare that member as sealed.
This negates the virtual aspect of the member for any further derived class. This is accomplished by putting the sealed keyword before the override keyword
in the class member declaration. For example:
C#
Copy Code
public class D : C
}
This is a detailed analysis of Abstract classes and methods in C# with some concrete examples.
The keyword abstract can be used with both classes and methods in C# to declare them as abstract.
The classes, which we can't initialize, are known as abstract classes. They provide only partial implementations. But another class can inherit from an
abstract class and can create their instances.
using System;
abstract class MyAbs
{
public void NonAbMethod()
{
Console.WriteLine("Non-Abstract Method");
}
}
class MyClass : MyAbs
{
}
class MyClient
{
public static void Main()
{
//MyAbs mb = new MyAbs();//not possible to create an instance
MyClass mc = new MyClass();
mc.NonAbMethod(); // Displays 'Non-Abstract Method'
}
}
An abstract class can contain abstract and non-abstract methods. When a class inherits from an abstract, the derived class must implement all the abstract
methods declared in the base class.
An abstract method is a method without any method body. They are implicitly virtual in C#.
using System;
abstract class MyAbs
{
public void NonAbMethod()
{
Console.WriteLine("Non-Abstract Method");
}
public abstract void AbMethod(); // An abstract method
}
class MyClass : MyAbs//must implement base class abstract methods
{
public override void AbMethod()
{
Console.WriteLine("Abstarct method");
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.NonAbMethod();
mc.AbMethod();
}
}
But by declaring the derived class also abstract, we can avoid the implementation of all or certain abstract methods. This is what is known as partial
implementation of an abstract class.
using System;
abstract class MyAbs
{
public abstract void AbMethod1();
public abstract void AbMethod2();
}
//not necessary to implement all abstract methods
//partial implementation is possible
abstract class MyClass1 : MyAbs
{
public override void AbMethod1()
{
Console.WriteLine("Abstarct method #1");
}
}
class MyClass : MyClass1
{
public override void AbMethod2()
{
Console.WriteLine("Abstarct method #2");
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.AbMethod1();
mc.AbMethod2();
}
}
In C#, an abstract class can inherit from another non-abstract class. In addition to the methods it inherited from the base class, it is possible to add new
abstract and non-abstract methods as showing below.
using System;
class MyClass1 // Non-Abstract class
{
public void Method1()
{
Console.WriteLine("Method of a non-abstract class");
}
}
abstract class MyAbs : MyClass1 // Inherits from an non-abstract class
{
public abstract void AbMethod1();
}
class MyClass : MyAbs//must implement base class abstract methods
{
public override void AbMethod1()
{
Console.WriteLine("Abstarct method #1 of MyClass");
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.Method1();
mc.AbMethod1();
}
}
An abstract class can also implement from an interface. In this case we must provide method body for all methods it implemented from the interface.
using System;
interface IInterface
{
void Method1();
}
abstract class MyAbs : IInterface
{
public void Method1()
{
Console.WriteLine("Method implemented from the IInterface");
}
}
class MyClass : MyAbs//must implement base class abstract method
{
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.Method1();
}
}
}
}
We can't use the key word abstract along with sealed in C#, since a sealed class can't be abstract.
The abstract methods are implicitly virtual and hence they can't mark explicitly virtual in C#.
For example
using System;
abstract class MyAbs
{
public abstract void AbMethod1();
public abstract void AbMethod2();
}
class MyClass1 : MyAbs
{
public override void AbMethod1(){
Console.WriteLine("Abstarct method #1 of MyClass1");
}
public override void AbMethod2()
{
Console.WriteLine("Abstarct method #2 of MyClass1");
}
}
class MyClient
{
public static void Main()
{
MyAbs ma1 = new MyClass1();// Polymorphism
ma1.AbMethod1();
ma1.AbMethod2();
}
}
C# Interview Questions
This is a list of questions I have gathered from other sources and created myself over a period of time from my experience, many of which I felt where
incomplete or simply wrong. I have finally taken the time to go through each question and correct them to the best of my ability. However, please feel free to
post feedback to challenge, improve, or suggest new questions. I want to thank those of you that have contributed quality questions and corrections thus far.
There are some question in this list that I do not consider to be good questions for an interview. However, they do exist on other lists available on the Internet
so I felt compelled to keep them easy access.
General Questions
1. Does C# support multiple-inheritance?
No.
11. How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
12. What’s the .NET collection class that allows an element to be accessed using a unique key?
HashTable.
14. Will the finally block get executed if an exception has not occurred?
Yes.
16. Can multiple catch blocks be executed for a single try statement?
No. Once the proper catch block processed, control is transferred to the finally block (if there are any).
17. Explain the three services model commonly know as a three-tier application.
Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).
Class Questions
1. What is the syntax to inherit from a class in C#?
Place a colon and then the name of the base class.
Example: class MyNewClass : MyBaseClass
2. Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.
3. Can you allow a class to be inherited, but prevent the method from being over-ridden?
Yes. Just leave the class public and make the method sealed.
7. Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public, and are therefore public by default.
9. What happens if you inherit multiple interfaces and they have conflicting method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-
level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
To Do: Investigate
1. What’s the implicit name of the parameter that gets passed into the set method/property of a class?
Value. The data type of the value parameter is defined by whatever data type the property is declared as.
4. Can you declare an override method to be static if the original method is not static?
No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override)
1. What’s a delegate?
A delegate object encapsulates a reference to a method.
1. Is XML case-sensitive?
Yes.
3. How do you generate documentation from the C# file commented properly with a command-line compiler?
Compile it with the /doc switch.
3. What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
7. What are three test cases you should go through in unit testing?
1. Positive test cases (correct data, correct output).
2. Negative test cases (broken or missing data, proper handling).
3. Exception test cases (exceptions are thrown and caught properly).
2. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for
accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as
fastest and efficient as SqlServer.NET.
6. Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is
untrusted, since SQL Server is the only verifier participating in the transaction.
7. What does the Initial Catalog parameter define in the connection string?
The database name to connect to.
Assembly Questions
C# Interview Questions
This is a list of questions I have gathered from other sources and created myself over a period of time from my experience, many of which I felt where
incomplete or simply wrong. I have finally taken the time to go through each question and correct them to the best of my ability. However, please feel free to
post feedback to challenge, improve, or suggest new questions. I want to thank those of you that have contributed quality questions and corrections thus far.
There are some question in this list that I do not consider to be good questions for an interview. However, they do exist on other lists available on the Internet
so I felt compelled to keep them easy access.
General Questions
12. What’s the .NET collection class that allows an element to be accessed using a unique key?
HashTable.
14. Will the finally block get executed if an exception has not occurred?
Yes.
16. Can multiple catch blocks be executed for a single try statement?
No. Once the proper catch block processed, control is transferred to the finally block (if there are any).
17. Explain the three services model commonly know as a three-tier application.
Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).
Class Questions
2. Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.
3. Can you allow a class to be inherited, but prevent the method from being over-ridden?
Yes. Just leave the class public and make the method sealed.
7. Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public, and are therefore public by default.
9. What happens if you inherit multiple interfaces and they have conflicting method names?
It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-
level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
To Do: Investigate
1. What’s the implicit name of the parameter that gets passed into the set method/property of a class?
Value. The data type of the value parameter is defined by whatever data type the property is declared as.
4. Can you declare an override method to be static if the original method is not static?
No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override)
6. If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you
enforce a call from an inherited constructor to a specific base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside
the inherited class.
1. What’s a delegate?
A delegate object encapsulates a reference to a method.
1. Is XML case-sensitive?
Yes.
3. How do you generate documentation from the C# file commented properly with a command-line compiler?
Compile it with the /doc switch.
3. What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
7. What are three test cases you should go through in unit testing?
1. Positive test cases (correct data, correct output).
2. Negative test cases (broken or missing data, proper handling).
3. Exception test cases (exceptions are thrown and caught properly).
2. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for
accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as
fastest and efficient as SqlServer.NET.
6. Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is
untrusted, since SQL Server is the only verifier participating in the transaction.
7. What does the Initial Catalog parameter define in the connection string?
The database name to connect to.
Assembly Questions